예제 #1
0
        private bool CheckIfJob2CanBeRemoved(bool checkForRemove, string parameterName, Job2 job2, string resourceString, params object[] args)
        {
            if (checkForRemove)
            {
                if (job2.IsFinishedState(job2.JobStateInfo.State))
                {
                    return(true);
                }

                string    message = PSRemotingErrorInvariants.FormatResourceString(resourceString, args);
                Exception ex      = new ArgumentException(message, parameterName);
                WriteError(new ErrorRecord(ex, "JobObjectNotFinishedCannotBeRemoved", ErrorCategory.InvalidOperation, job2));
                return(false);
            }

            return(true);
        }
예제 #2
0
        /// <summary>
        /// Gets the job object as per the parameter and removes it.
        /// </summary>
        protected override void ProcessRecord()
        {
            List <Job> listOfJobsToRemove = null;

            switch (ParameterSetName)
            {
            case NameParameterSet:
            {
                listOfJobsToRemove = FindJobsMatchingByName(false, false, true, !_force);
            }
            break;

            case InstanceIdParameterSet:
            {
                listOfJobsToRemove = FindJobsMatchingByInstanceId(true, false, true, !_force);
            }
            break;

            case SessionIdParameterSet:
            {
                listOfJobsToRemove = FindJobsMatchingBySessionId(true, false, true, !_force);
            }
            break;

            case CommandParameterSet:
            {
                listOfJobsToRemove = FindJobsMatchingByCommand(false);
            }
            break;

            case StateParameterSet:
            {
                listOfJobsToRemove = FindJobsMatchingByState(false);
            }
            break;

            case FilterParameterSet:
            {
                listOfJobsToRemove = FindJobsMatchingByFilter(false);
            }
            break;

            default:
            {
                listOfJobsToRemove = CopyJobsToList(_jobs, false, !_force);
            }
            break;
            }

            //Now actually remove the jobs
            foreach (Job job in listOfJobsToRemove)
            {
                string message = GetMessage(RemotingErrorIdStrings.StopPSJobWhatIfTarget,
                                            job.Command, job.Id);

                if (!ShouldProcess(message, VerbsCommon.Remove))
                {
                    continue;
                }

                Job2 job2 = job as Job2;
                if (!job.IsFinishedState(job.JobStateInfo.State))
                {
                    // if it is a Job2, then async is supported
                    // stop the job asynchronously
                    if (job2 != null)
                    {
                        _cleanUpActions.Add(job2, HandleStopJobCompleted);
                        job2.StopJobCompleted += HandleStopJobCompleted;

                        lock (_syncObject)
                        {
                            if (!job2.IsFinishedState(job2.JobStateInfo.State) &&
                                !_pendingJobs.Contains(job2.InstanceId))
                            {
                                _pendingJobs.Add(job2.InstanceId);
                            }
                        }

                        job2.StopJobAsync();
                    }
                    else
                    {
                        job.StopJob();
                        RemoveJobAndDispose(job, false);
                    }
                }
                else
                {
                    RemoveJobAndDispose(job, job2 != null);
                }
            }
        } // ProcessRecord
예제 #3
0
        public async Task <ActionResult> Add(int?p1Count, int?p2Count, int?p3Count, int?p4Count, int?p5Count)
        {
            var appID = ConfigurationManager.AppSettings["ApplicationID"];

            if (string.IsNullOrWhiteSpace(appID))
            {
                appID = "Shift.Demo.MVC";
            }

            var message = "";

            if (p1Count > 0)
            {
                for (var i = 0; i < p1Count; i++)
                {
                    var job1        = new Job1();
                    var progress    = new SynchronousProgress <ProgressInfo>(); //placeholder to be replaced by Server progress object
                    var cancelToken = (new CancellationTokenSource()).Token;    //placeholder to be replaced by Server token
                    var pauseToken  = (new PauseTokenSource()).Token;
                    await jobClient.AddAsync(appID, () => job1.Start("Hello World!", progress, cancelToken, pauseToken));
                }

                message += p1Count + " - Job1 added to queue. <br/>";
            }

            if (p2Count > 0)
            {
                for (var i = 0; i < p2Count; i++)
                {
                    var job2        = new Job2();
                    var progress    = new SynchronousProgress <ProgressInfo>();
                    var cancelToken = (new CancellationTokenSource()).Token; //placeholder to be replaced by Server token
                    var pauseToken  = (new PauseTokenSource()).Token;
                    await jobClient.AddAsync(appID, () => job2.Start(progress, 1, cancelToken, pauseToken));
                }

                message += p2Count + " - Job2 added to queue. <br/>";
            }

            if (p3Count > 0)
            {
                var simpleList = new List <int>();
                for (var i = 1; i <= 100; i++)
                {
                    simpleList.Add(i);
                }

                for (var i = 0; i < p3Count; i++)
                {
                    var job3     = new Job3();
                    var progress = new SynchronousProgress <ProgressInfo>();
                    await jobClient.AddAsync(appID, () => job3.Start(progress, simpleList));
                }

                message += p3Count + " - Job3 added to queue. <br/>";
            }

            if (p4Count > 0)
            {
                var complexList = new List <TestData>();
                for (var i = 1; i <= 100; i++)
                {
                    var newData = new TestData();
                    newData.MyNumber = i;
                    newData.MyString = "mystring " + i;
                    complexList.Add(newData);
                }

                for (var i = 0; i < p4Count; i++)
                {
                    var job4        = new Job4();
                    var progress    = new SynchronousProgress <ProgressInfo>();
                    var cancelToken = (new CancellationTokenSource()).Token; //placeholder to be replaced by Server token
                    var pauseToken  = (new PauseTokenSource()).Token;
                    await jobClient.AddAsync(appID, () => job4.Start(progress, complexList, cancelToken, pauseToken));
                }

                message += p4Count + " - Job4 added to queue. <br/>";
            }

            if (p5Count > 0)
            {
                var simpleList = new List <int>();
                for (var i = 1; i <= 100; i++)
                {
                    simpleList.Add(i);
                }

                for (var i = 0; i < p5Count; i++)
                {
                    var job5        = new Job5();
                    var cancelToken = (new CancellationTokenSource()).Token; //placeholder to be replaced by Server token
                    var pauseToken  = (new PauseTokenSource()).Token;
                    var progress    = new SynchronousProgress <ProgressInfo>();
                    await jobClient.AddAsync(appID, () => job5.StartAsync(progress, simpleList, cancelToken, pauseToken));
                }

                message += p5Count + " - Job5 added to queue. <br/>";
            }

            ViewBag.Message = message;

            return(View("Index"));
        }
예제 #4
0
        /// <summary>
        /// The expression will be executed in the remote computer if a
        /// remote runspace parameter or computer name is specified. If
        /// none other than command parameter is specified, then it
        /// just executes the command locally without creating a new
        /// remote runspace object.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (ParameterSetName == DefinitionNameParameterSet)
            {
                // Get the Job2 object from the Job Manager for this definition name and start the job.
                string resolvedPath = null;
                if (!string.IsNullOrEmpty(_definitionPath))
                {
                    ProviderInfo provider = null;
                    System.Collections.ObjectModel.Collection <string> paths =
                        this.Context.SessionState.Path.GetResolvedProviderPathFromPSPath(_definitionPath, out provider);

                    // Only file system paths are allowed.
                    if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotFSProvider,
                                                           _definitionName,
                                                           _definitionPath,
                                                           provider.FullName);
                        WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotFileSystemProvider",
                                                   ErrorCategory.InvalidArgument, null));

                        return;
                    }

                    // Only a single file path is allowed.
                    if (paths.Count != 1)
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotSingle,
                                                           _definitionName,
                                                           _definitionPath);
                        WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotSingle",
                                                   ErrorCategory.InvalidArgument, null));

                        return;
                    }

                    resolvedPath = paths[0];
                }
                List <Job2> jobs = JobManager.GetJobToStart(_definitionName, resolvedPath, _definitionType, this, false);

                if (jobs.Count == 0)
                {
                    string message = (_definitionType != null) ?
                                     StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound2, _definitionType, _definitionName) :
                                     StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound1, _definitionName);

                    WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameNotFound",
                                               ErrorCategory.ObjectNotFound, null));

                    return;
                }

                if (jobs.Count > 1)
                {
                    string message = StringUtil.Format(RemotingErrorIdStrings.StartJobManyDefNameMatches, _definitionName);
                    WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameMoreThanOneMatch",
                                               ErrorCategory.InvalidResult, null));

                    return;
                }

                // Start job.
                Job2 job = jobs[0];
                job.StartJob();

                // Write job object to host.
                WriteObject(job);

                return;
            }

            if (_firstProcessRecord)
            {
                _firstProcessRecord = false;

                PSRemotingJob job = new PSRemotingJob(ResolvedComputerNames, Operations,
                                                      ScriptBlock.ToString(), ThrottleLimit, _name);

                job.PSJobTypeName = s_startJobType;

                this.JobRepository.Add(job);
                WriteObject(job);
            }

            // inject input
            if (InputObject != AutomationNull.Value)
            {
                foreach (IThrottleOperation operation in Operations)
                {
                    ExecutionCmdletHelper helper = (ExecutionCmdletHelper)operation;
                    helper.Pipeline.Input.Write(InputObject);
                }
            }
        } // ProcessRecord
예제 #5
0
        protected override void ProcessRecord()
        {
            List <System.Management.Automation.Job> collection = null;
            string parameterSetName = base.ParameterSetName;

            if (parameterSetName != null)
            {
                if (!(parameterSetName == "NameParameterSet"))
                {
                    if (parameterSetName == "InstanceIdParameterSet")
                    {
                        collection = base.FindJobsMatchingByInstanceId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "SessionIdParameterSet")
                    {
                        collection = base.FindJobsMatchingBySessionId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "StateParameterSet")
                    {
                        collection = base.FindJobsMatchingByState(false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "FilterParameterSet")
                    {
                        collection = base.FindJobsMatchingByFilter(false);
                        goto Label_00A2;
                    }
                }
                else
                {
                    collection = base.FindJobsMatchingByName(true, false, true, false);
                    goto Label_00A2;
                }
            }
            collection = base.CopyJobsToList(this.jobs, false, false);
Label_00A2:
            this._allJobsToResume.AddRange(collection);
            foreach (System.Management.Automation.Job job in collection)
            {
                Job2 key = job as Job2;
                if (key == null)
                {
                    base.WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException("RemotingErrorIdStrings", "JobResumeNotSupported", new object[] { job.Id }), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, job));
                }
                else
                {
                    string target = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, new object[] { job.Command, job.Id });
                    if (base.ShouldProcess(target, "Resume"))
                    {
                        this._cleanUpActions.Add(key, new EventHandler <AsyncCompletedEventArgs>(this.HandleResumeJobCompleted));
                        key.ResumeJobCompleted += new EventHandler <AsyncCompletedEventArgs>(this.HandleResumeJobCompleted);
                        lock (this._syncObject)
                        {
                            if (!this._pendingJobs.Contains(key.InstanceId))
                            {
                                this._pendingJobs.Add(key.InstanceId);
                            }
                        }
                        key.ResumeJobAsync();
                    }
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Finds and load the Job associated with this ScheduledJobDefinition object
        /// having the job run date time provided.
        /// </summary>
        /// <param name="jobRun">DateTime of job run to load.</param>
        /// <param name="definitionName">ScheduledJobDefinition name.</param>
        /// <returns>Job2 job loaded from store.</returns>
        internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun)
        {
            FileStream fsResults     = null;
            Exception  ex            = null;
            bool       corruptedFile = false;
            Job2       job           = null;

            try
            {
                // Results
                fsResults = ScheduledJobStore.GetFileForJobRunItem(
                    definitionName,
                    jobRun,
                    ScheduledJobStore.JobRunItem.Results,
                    FileMode.Open,
                    FileAccess.Read,
                    FileShare.Read);

                job = LoadResultsFromFile(fsResults);
            }
            catch (ArgumentException e)
            {
                ex = e;
            }
            catch (DirectoryNotFoundException e)
            {
                ex = e;
            }
            catch (FileNotFoundException e)
            {
                ex            = e;
                corruptedFile = true;
            }
            catch (UnauthorizedAccessException e)
            {
                ex = e;
            }
            catch (IOException e)
            {
                ex = e;
            }
            catch (System.Runtime.Serialization.SerializationException)
            {
                corruptedFile = true;
            }
            catch (System.Runtime.Serialization.InvalidDataContractException)
            {
                corruptedFile = true;
            }
            catch (System.Xml.XmlException)
            {
                corruptedFile = true;
            }
            catch (System.TypeInitializationException)
            {
                corruptedFile = true;
            }
            finally
            {
                if (fsResults != null)
                {
                    fsResults.Close();
                }
            }

            if (corruptedFile)
            {
                // Remove the corrupted job results file.
                ScheduledJobStore.RemoveJobRun(definitionName, jobRun);
            }

            if (ex != null)
            {
                string msg = StringUtil.Format(ScheduledJobErrorStrings.CantLoadJobRunFromStore, definitionName, jobRun);
                throw new ScheduledJobException(msg, ex);
            }

            return(job);
        }
예제 #7
0
        /// <summary>
        /// Remove a job from the store
        /// </summary>
        /// <param name="job">job object to remove</param>
        public override void RemoveJob(Job2 job)
        {
            if (job == null)
            {
                throw new ArgumentNullException("job");
            }
            _structuredTracer.RemoveJobStarted(job.InstanceId);

            var jobInMemory = _jobRepository.GetItem(job.InstanceId);

            if (jobInMemory == null)
            {
                // the specified job is not available in memory
                // load the job repository
                PopulateJobRepositoryIfRequired();
            }

            if (!(job is ContainerParentJob))
            {
                throw new InvalidOperationException(Resources.CannotRemoveWorkflowJobDirectly);
            }

            _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Removing Workflow job with instance id: {0}", job.InstanceId));

            Exception innerException = null;

            foreach (Job childJob in job.ChildJobs)
            {
                PSWorkflowJob workflowChildJob = childJob as PSWorkflowJob;

                if (workflowChildJob == null)
                {
                    continue;
                }

                try
                {
                    GetJobManager().RemoveJob(workflowChildJob.InstanceId);
                    _structuredTracer.JobRemoved(job.InstanceId,
                                                 childJob.InstanceId, workflowChildJob.WorkflowGuid);
                }
                catch (ArgumentException exception)
                {
                    //ignoring the error message and just logging them into ETW
                    _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                                       "WorkflowJobSourceAdapter: Ingnoring the exception. Exception details: {0}",
                                                       exception));
                    innerException = exception;
                    _structuredTracer.JobRemoveError(job.InstanceId,
                                                     childJob.InstanceId, workflowChildJob.WorkflowGuid,
                                                     exception.Message);
                }
            }

            // remove the container parent job from repository
            try
            {
                _jobRepository.Remove((ContainerParentJob)job);
            }
            catch (ArgumentException exception)
            {
                //ignoring the error message and just logging them into ETW
                _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                                   "WorkflowJobSourceAdapter: Ingnoring the exception. Exception details: {0}",
                                                   exception));
                innerException = exception;
            }
            job.Dispose();

            // Failed to remove the job?
            if (innerException != null)
            {
                ArgumentException exc = new ArgumentException(Resources.WorkflowChildCouldNotBeRemoved, "job", innerException);
                throw exc;
            }
        }
예제 #8
0
        internal void RemoveChildJob(Job2 childWorkflowJob)
        {
            _structuredTracer.RemoveJobStarted(childWorkflowJob.InstanceId);
            PopulateJobRepositoryIfRequired();

            _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Removing Workflow job with instance id: {0}", childWorkflowJob.InstanceId));

            lock (_syncRemoveChilJob)
            {
                PSWorkflowJob childJob = childWorkflowJob as PSWorkflowJob;
                if (childJob == null)
                {
                    return;
                }

                object             data;
                PSWorkflowInstance instance = childJob.PSWorkflowInstance;

                if (!instance.PSWorkflowContext.JobMetadata.TryGetValue(Constants.JobMetadataParentInstanceId, out data))
                {
                    return;
                }
                var parentInstanceId   = (Guid)data;
                ContainerParentJob job = _jobRepository.GetItem(parentInstanceId);

                job.ChildJobs.Remove(childJob);


                try
                {
                    GetJobManager().RemoveJob(childJob.InstanceId);
                    _structuredTracer.JobRemoved(job.InstanceId,
                                                 childJob.InstanceId, childJob.WorkflowGuid);
                }
                catch (ArgumentException exception)
                {
                    //ignoring the error message and just logging them into ETW
                    _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                                       "WorkflowJobSourceAdapter: Ingnoring the exception. Exception details: {0}",
                                                       exception));

                    _structuredTracer.JobRemoveError(job.InstanceId,
                                                     childJob.InstanceId, childJob.WorkflowGuid,
                                                     exception.Message);
                }

                if (job.ChildJobs.Count == 0)
                {
                    // remove the container parent job from repository
                    try
                    {
                        _jobRepository.Remove(job);
                    }
                    catch (ArgumentException exception)
                    {
                        //ignoring the error message and just logging them into ETW
                        _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                                           "WorkflowJobSourceAdapter: Ingnoring the exception. Exception details: {0}",
                                                           exception));
                    }
                    job.Dispose();
                }
            }
        }
예제 #9
0
        public async Task TestSystemJobsInitializedIsExecuted()
        {
            using var cancellationTokenSource1 = new CancellationTokenSource();
            using var cancellationTokenSource2 = new CancellationTokenSource();

            var waitForStop1 = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);
            var waitForStop2 = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

            cancellationTokenSource1.Token.Register(state =>
            {
                var tcs = (TaskCompletionSource <object>)state;
                tcs.TrySetResult(null);
            }, waitForStop1);

            cancellationTokenSource2.Token.Register(state =>
            {
                var tcs = (TaskCompletionSource <object>)state;
                tcs.TrySetResult(null);
            }, waitForStop2);

            var job1Executed = false;
            var job2Executed = false;

            var loggerMock = new Mock <ILogger <Scheduler> >();

            await using var services = new ServiceCollection()
                                       .AddSingleton(loggerMock.Object)
                                       .AddScheduler()
                                       .AddTransient(p =>
            {
                var job = new Job();

                job.Initialize(() => !job1Executed ? (DateTimeOffset?)DateTimeOffset.Now.AddMilliseconds(100) : null,
                               ct =>
                {
                    job1Executed = true;
                    cancellationTokenSource1.Cancel();

                    return(Task.CompletedTask);
                });

                return(job);
            })
                                       .AddTransient(p =>
            {
                var job = new Job2();

                job.Initialize(() => !job2Executed ? (DateTimeOffset?)DateTimeOffset.Now.AddMilliseconds(100) : null,
                               ct =>
                {
                    job2Executed = true;
                    cancellationTokenSource2.Cancel();

                    return(Task.CompletedTask);
                });

                return(job);
            })
                                       .AddSystemJob <Job>()
                                       .AddSystemJob <Job2>()
                                       .BuildServiceProvider(true);

            var scheduler = services.GetRequiredService <IHostedService>();

            await scheduler.StartAsync(CancellationToken.None).ConfigureAwait(false);

            var allTask = Task.WhenAll(waitForStop1.Task, waitForStop2.Task);

            var result = await Task.WhenAny(allTask, Task.Delay(10000, CancellationToken.None));

            await scheduler.StopAsync(CancellationToken.None).ConfigureAwait(false);

            // If this assertion fails, something has hanged during execution so that the jobs isn't executed.
            Assert.Equal(allTask, result);
        }
예제 #10
0
        private void ProcessExecutionErrorsAndReleaseWaitHandle(Job job)
        {
            bool releaseWait = false;

            lock (_syncObject)
            {
                if (_pendingJobs.Contains(job.InstanceId))
                {
                    _pendingJobs.Remove(job.InstanceId);
                }
                else
                {
                    // there could be a possibility of race condition where this function is getting called twice
                    // so if job doesn't present in the _pendingJobs then just return
                    return;
                }
                if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0)
                {
                    releaseWait = true;
                }
            }

            if (!_wait)
            {
                job.StateChanged -= noWait_Job2_StateChanged;
                Job2 job2 = job as Job2;
                if (job2 != null)
                {
                    job2.SuspendJobCompleted -= HandleSuspendJobCompleted;
                }
            }

            var parentJob = job as ContainerParentJob;

            if (parentJob != null && parentJob.ExecutionError.Count > 0)
            {
                foreach (
                    var e in
                    parentJob.ExecutionError.Where(e => e.FullyQualifiedErrorId == "ContainerParentJobSuspendAsyncError")
                    )
                {
                    if (e.Exception is InvalidJobStateException)
                    {
                        // if any errors were invalid job state exceptions, warn the user.
                        // This is to support Get-Job | Resume-Job scenarios when many jobs
                        // are Completed, etc.
                        _warnInvalidState = true;
                    }
                    else
                    {
                        _errorsToWrite.Add(e);
                    }
                }
            }

            // end processing has been called
            // set waithandle if this is the last one
            if (releaseWait)
            {
                _waitForJobs.Set();
            }
        }
예제 #11
0
        protected override void ProcessRecord()
        {
            List <System.Management.Automation.Job> list = null;

            switch (base.ParameterSetName)
            {
            case "NameParameterSet":
                list = base.FindJobsMatchingByName(false, false, true, !this.force);
                break;

            case "InstanceIdParameterSet":
                list = base.FindJobsMatchingByInstanceId(true, false, true, !this.force);
                break;

            case "SessionIdParameterSet":
                list = base.FindJobsMatchingBySessionId(true, false, true, !this.force);
                break;

            case "CommandParameterSet":
                list = base.FindJobsMatchingByCommand(false);
                break;

            case "StateParameterSet":
                list = base.FindJobsMatchingByState(false);
                break;

            case "FilterParameterSet":
                list = base.FindJobsMatchingByFilter(false);
                break;

            default:
                list = base.CopyJobsToList(this.jobs, false, !this.force);
                break;
            }
            foreach (System.Management.Automation.Job job in list)
            {
                string message = base.GetMessage(RemotingErrorIdStrings.StopPSJobWhatIfTarget, new object[] { job.Command, job.Id });
                if (base.ShouldProcess(message, "Remove"))
                {
                    Job2 key = job as Job2;
                    if (!job.IsFinishedState(job.JobStateInfo.State))
                    {
                        if (key != null)
                        {
                            this._cleanUpActions.Add(key, new EventHandler <AsyncCompletedEventArgs>(this.HandleStopJobCompleted));
                            key.StopJobCompleted += new EventHandler <AsyncCompletedEventArgs>(this.HandleStopJobCompleted);
                            lock (this._syncObject)
                            {
                                if (!key.IsFinishedState(key.JobStateInfo.State) && !this._pendingJobs.Contains(key.InstanceId))
                                {
                                    this._pendingJobs.Add(key.InstanceId);
                                }
                            }
                            key.StopJobAsync();
                        }
                        else
                        {
                            job.StopJob();
                            this.RemoveJobAndDispose(job, false);
                        }
                    }
                    else
                    {
                        this.RemoveJobAndDispose(job, key != null);
                    }
                }
            }
        }
예제 #12
0
        protected override void ProcessRecord()
        {
            List <System.Management.Automation.Job> collection = null;
            string parameterSetName = base.ParameterSetName;

            if (parameterSetName != null)
            {
                if (!(parameterSetName == "NameParameterSet"))
                {
                    if (parameterSetName == "InstanceIdParameterSet")
                    {
                        collection = base.FindJobsMatchingByInstanceId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "SessionIdParameterSet")
                    {
                        collection = base.FindJobsMatchingBySessionId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "StateParameterSet")
                    {
                        collection = base.FindJobsMatchingByState(false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "FilterParameterSet")
                    {
                        collection = base.FindJobsMatchingByFilter(false);
                        goto Label_00A2;
                    }
                }
                else
                {
                    collection = base.FindJobsMatchingByName(true, false, true, false);
                    goto Label_00A2;
                }
            }
            collection = base.CopyJobsToList(this.jobs, false, false);
Label_00A2:
            this._allJobsToStop.AddRange(collection);
            foreach (System.Management.Automation.Job job in collection)
            {
                if (base.Stopping)
                {
                    break;
                }
                if (!job.IsFinishedState(job.JobStateInfo.State))
                {
                    string target = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, new object[] { job.Command, job.Id });
                    if (base.ShouldProcess(target, "Stop"))
                    {
                        Job2 key = job as Job2;
                        if (key != null)
                        {
                            this._cleanUpActions.Add(key, new EventHandler <AsyncCompletedEventArgs>(this.HandleStopJobCompleted));
                            key.StopJobCompleted += new EventHandler <AsyncCompletedEventArgs>(this.HandleStopJobCompleted);
                            lock (this._syncObject)
                            {
                                if (!key.IsFinishedState(key.JobStateInfo.State) && !this._pendingJobs.Contains(key.InstanceId))
                                {
                                    this._pendingJobs.Add(key.InstanceId);
                                }
                            }
                            key.StopJobAsync();
                        }
                        else
                        {
                            job.StopJob();
                            ContainerParentJob job3 = job as ContainerParentJob;
                            if ((job3 != null) && (job3.ExecutionError.Count > 0))
                            {
                                foreach (ErrorRecord record in from e in job3.ExecutionError
                                         where e.FullyQualifiedErrorId == "ContainerParentJobStopError"
                                         select e)
                                {
                                    base.WriteError(record);
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #13
0
        /// <summary>
        /// Stop the Job.
        /// </summary>
        protected override void ProcessRecord()
        {
            //List of jobs to stop
            List <Job> jobsToStop = null;

            switch (ParameterSetName)
            {
            case NameParameterSet:
            {
                jobsToStop = FindJobsMatchingByName(true, false, true, false);
            }
            break;

            case InstanceIdParameterSet:
            {
                jobsToStop = FindJobsMatchingByInstanceId(true, false, true, false);
            }
            break;

            case SessionIdParameterSet:
            {
                jobsToStop = FindJobsMatchingBySessionId(true, false, true, false);
            }
            break;

            case StateParameterSet:
            {
                jobsToStop = FindJobsMatchingByState(false);
            }
            break;

            case FilterParameterSet:
            {
                jobsToStop = FindJobsMatchingByFilter(false);
            }
            break;

            default:
            {
                jobsToStop = CopyJobsToList(_jobs, false, false);
            }
            break;
            }

            _allJobsToStop.AddRange(jobsToStop);

            foreach (Job job in jobsToStop)
            {
                if (this.Stopping)
                {
                    return;
                }
                if (job.IsFinishedState(job.JobStateInfo.State))
                {
                    continue;
                }
                string targetString =
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget,
                                                                   job.Command, job.Id);
                if (ShouldProcess(targetString, VerbsLifecycle.Stop))
                {
                    Job2 job2 = job as Job2;
                    // if it is a Job2, then async is supported
                    // stop the job asynchronously
                    if (job2 != null)
                    {
                        _cleanUpActions.Add(job2, HandleStopJobCompleted);
                        job2.StopJobCompleted += HandleStopJobCompleted;

                        lock (_syncObject)
                        {
                            if (!job2.IsFinishedState(job2.JobStateInfo.State) &&
                                !_pendingJobs.Contains(job2.InstanceId))
                            {
                                _pendingJobs.Add(job2.InstanceId);
                            }
                        }

                        job2.StopJobAsync();
                    }
                    else
                    {
                        job.StopJob();
                        var parentJob = job as ContainerParentJob;
                        if (parentJob != null && parentJob.ExecutionError.Count > 0)
                        {
                            foreach (
                                var e in
                                parentJob.ExecutionError.Where(
                                    e => e.FullyQualifiedErrorId == "ContainerParentJobStopError"))
                            {
                                WriteError(e);
                            }
                        }
                    }
                }
            }
        }
예제 #14
0
        protected override void ProcessRecord()
        {
            List <System.Management.Automation.Job> collection = null;
            string parameterSetName = base.ParameterSetName;

            if (parameterSetName != null)
            {
                if (!(parameterSetName == "NameParameterSet"))
                {
                    if (parameterSetName == "InstanceIdParameterSet")
                    {
                        collection = base.FindJobsMatchingByInstanceId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "SessionIdParameterSet")
                    {
                        collection = base.FindJobsMatchingBySessionId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "StateParameterSet")
                    {
                        collection = base.FindJobsMatchingByState(false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "FilterParameterSet")
                    {
                        collection = base.FindJobsMatchingByFilter(false);
                        goto Label_00A2;
                    }
                }
                else
                {
                    collection = base.FindJobsMatchingByName(true, false, true, false);
                    goto Label_00A2;
                }
            }
            collection = base.CopyJobsToList(this.jobs, false, false);
Label_00A2:
            this._allJobsToSuspend.AddRange(collection);
            foreach (System.Management.Automation.Job job in collection)
            {
                Job2 key = job as Job2;
                if (key == null)
                {
                    base.WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException("RemotingErrorIdStrings", "JobSuspendNotSupported", new object[] { job.Id }), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, job));
                }
                else
                {
                    string target = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, new object[] { job.Command, job.Id });
                    if (base.ShouldProcess(target, "Suspend"))
                    {
                        if (this._wait)
                        {
                            this._cleanUpActions.Add(key, new EventHandler <AsyncCompletedEventArgs>(this.HandleSuspendJobCompleted));
                        }
                        else
                        {
                            if (key.IsFinishedState(key.JobStateInfo.State) || (key.JobStateInfo.State == JobState.Stopping))
                            {
                                this._warnInvalidState = true;
                                goto Label_0277;
                            }
                            if ((key.JobStateInfo.State == JobState.Suspending) || (key.JobStateInfo.State == JobState.Suspended))
                            {
                                goto Label_0277;
                            }
                            key.StateChanged += new EventHandler <JobStateEventArgs>(this.noWait_Job2_StateChanged);
                        }
                        key.SuspendJobCompleted += new EventHandler <AsyncCompletedEventArgs>(this.HandleSuspendJobCompleted);
                        lock (this._syncObject)
                        {
                            if (!this._pendingJobs.Contains(key.InstanceId))
                            {
                                this._pendingJobs.Add(key.InstanceId);
                            }
                        }
                        if (!this._wait && ((key.IsFinishedState(key.JobStateInfo.State) || (key.JobStateInfo.State == JobState.Suspending)) || (key.JobStateInfo.State == JobState.Suspended)))
                        {
                            this.ProcessExecutionErrorsAndReleaseWaitHandle(key);
                        }
                        key.SuspendJobAsync(this.force, RemotingErrorIdStrings.ForceSuspendJob);
                    }
                    Label_0277 :;
                }
            }
        }
        internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun)
        {
            FileStream fileForJobRunItem = null;
            Exception  exception         = null;
            bool       flag = false;
            Job2       job2 = null;

            try
            {
                try
                {
                    fileForJobRunItem = ScheduledJobStore.GetFileForJobRunItem(definitionName, jobRun, ScheduledJobStore.JobRunItem.Results, FileMode.Open, FileAccess.Read, FileShare.Read);
                    job2 = ScheduledJobSourceAdapter.LoadResultsFromFile(fileForJobRunItem);
                }
                catch (ArgumentException argumentException1)
                {
                    ArgumentException argumentException = argumentException1;
                    exception = argumentException;
                }
                catch (DirectoryNotFoundException directoryNotFoundException1)
                {
                    DirectoryNotFoundException directoryNotFoundException = directoryNotFoundException1;
                    exception = directoryNotFoundException;
                }
                catch (FileNotFoundException fileNotFoundException1)
                {
                    FileNotFoundException fileNotFoundException = fileNotFoundException1;
                    exception = fileNotFoundException;
                    flag      = true;
                }
                catch (UnauthorizedAccessException unauthorizedAccessException1)
                {
                    UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1;
                    exception = unauthorizedAccessException;
                }
                catch (IOException oException1)
                {
                    IOException oException = oException1;
                    exception = oException;
                }
                catch (SerializationException serializationException)
                {
                    flag = true;
                }
                catch (InvalidDataContractException invalidDataContractException)
                {
                    flag = true;
                }
                catch (XmlException xmlException)
                {
                    flag = true;
                }
                catch (TypeInitializationException typeInitializationException)
                {
                    flag = true;
                }
            }
            finally
            {
                if (fileForJobRunItem != null)
                {
                    fileForJobRunItem.Close();
                }
            }
            if (flag)
            {
                ScheduledJobStore.RemoveJobRun(definitionName, jobRun);
            }
            if (exception == null)
            {
                return(job2);
            }
            else
            {
                object[] objArray = new object[2];
                objArray[0] = definitionName;
                objArray[1] = jobRun;
                string str = StringUtil.Format(ScheduledJobErrorStrings.CantLoadJobRunFromStore, objArray);
                throw new ScheduledJobException(str, exception);
            }
        }