public override Job2 NewJob(JobInvocationInfo specification) { if (specification == null) { throw new ArgumentNullException("specification"); } if (specification.Definition == null) { throw new ArgumentException(Resources.NewJobDefinitionNull, "specification"); } if (specification.Definition.JobSourceAdapterType != GetType()) { throw new InvalidOperationException(Resources.NewJobWrongType); } if (specification.Parameters.Count == 0) { // If there are no parameters passed in, we create one child job with nothing specified. specification.Parameters.Add(new CommandParameterCollection()); } // validation has to happen before job creation bool? isSuspendable = null; Activity activity = ValidateWorkflow(specification, null, ref isSuspendable); ContainerParentJob newJob = GetJobManager().CreateJob(specification, activity); // We do not want to generate the warning message if the request is coming from // Server Manager if (PSSessionConfigurationData.IsServerManager == false) { foreach (PSWorkflowJob job in newJob.ChildJobs) { bool?psPersistValue = null; PSWorkflowContext context = job.PSWorkflowInstance.PSWorkflowContext; if (context != null && context.PSWorkflowCommonParameters != null && context.PSWorkflowCommonParameters.ContainsKey(Constants.Persist)) { psPersistValue = context.PSWorkflowCommonParameters[Constants.Persist] as bool?; } // check for invocation time pspersist value if not true then there is a possibility that workflow is not suspendable. if (psPersistValue == null || (psPersistValue == false)) { // check for authoring time definition of persist activity if (isSuspendable != null && isSuspendable.Value == false) { job.Warning.Add(new WarningRecord(Resources.WarningMessageForPersistence)); job.IsSuspendable = isSuspendable; } } } } StoreJobIdForReuse(newJob, true); _jobRepository.Add(newJob); return(newJob); }
/// <summary> /// NewJob /// </summary> public override Job2 NewJob(JobInvocationInfo specification) { var job = specification.Parameters[0][0].Value as ThreadJob; if (job != null) { _repository.TryAdd(job.InstanceId, job); } return(job); }
public override Job2 NewJob(JobInvocationInfo specification) { if (specification != null) { ScheduledJobDefinition scheduledJobDefinition = new ScheduledJobDefinition(specification, null, null, null); return(new ScheduledJob(specification.Command, specification.Name, scheduledJobDefinition)); } else { throw new PSArgumentNullException("specification"); } }
protected override void ProcessRecord() { // Get full path to source. ProviderInfo provider; string fullSourcePath = GetResolvedProviderPathFromPSPath(SourcePath, out provider).FirstOrDefault(); if (string.IsNullOrEmpty(fullSourcePath)) { throw new ArgumentException(SourcePath); } // Get full path for destination file (which may not exist). string fullDestPath = null; string destFile = Path.GetFileName(DestinationPath); string path = GetResolvedProviderPathFromPSPath( Path.GetDirectoryName(DestinationPath), out provider).FirstOrDefault(); if (path != null) { fullDestPath = Path.Combine(path, destFile); } if (string.IsNullOrEmpty(fullDestPath)) { throw new ArgumentException(DestinationPath); } // Create job source adapter. FileCopyJobSourceAdapter jobSourceAdapter = new FileCopyJobSourceAdapter(); // Create FileCopyJob parameters (source and destination paths). Dictionary <string, object> copyJobParameters = new Dictionary <string, object>(); copyJobParameters.Add(FileCopyJobSourceAdapter.SourcePathProperty, fullSourcePath); copyJobParameters.Add(FileCopyJobSourceAdapter.DestinationPathProperty, fullDestPath); // Create job specification. JobInvocationInfo copyJobSpecification = new JobInvocationInfo( new JobDefinition(typeof(FileCopyJobSourceAdapter), string.Empty, Name), copyJobParameters); copyJobSpecification.Name = Name; // Create file copy job from job source adapter and start it. Job2 fileCopyJob = jobSourceAdapter.NewJob(copyJobSpecification); fileCopyJob.StartJob(); WriteObject(fileCopyJob); }
private void __Initialize() { var iss = InitialSessionState.CreateDefault2(); iss.Commands.Add(this.__commandEntries); iss.LanguageMode = PSLanguageMode.FullLanguage; this.__input = new PSDataCollection <object>(); this.__output = new PSDataCollection <PSObject>(); this.__runspace = RunspaceFactory.CreateRunspace(this.__psCmdlet.Host, iss); this.__powershell = PowerShell.Create(); this.__powershell.Runspace = this.__runspace; this.__powershell.InvocationStateChanged += (sender, psStateChanged) => this.SetJobState(psStateChanged.InvocationStateInfo); this.PSJobTypeName = "Promise"; this.Information = this.__powershell.Streams.Information; this.Information.EnumeratorNeverBlocks = true; this.Debug = this.__powershell.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; this.Output = this.__output; this.Output.EnumeratorNeverBlocks = true; this.Progress = this.__powershell.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Error = this.__powershell.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Warning = this.__powershell.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; var PromiseDefinition = new JobDefinition(typeof(PromiseSourceAdapter), "", this.Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(PromiseDefinition, parameterCollection); var newJob = this.__psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }
public override Job2 NewJob(JobInvocationInfo specification) { if (specification == null) { throw new NullReferenceException("specification"); } if (specification.Parameters.Count != 1) { throw new ArgumentException("JobInvocationInfo specification parameters not specified."); } // Retrieve source and destination path information from specification // parameters. string sourcePath = null; string destinationPath = null; CommandParameterCollection parameters = specification.Parameters[0]; foreach (var item in parameters) { if (item.Name.Equals(SourcePathProperty, StringComparison.OrdinalIgnoreCase)) { sourcePath = item.Value as string; } else if (item.Name.Equals(DestinationPathProperty, StringComparison.OrdinalIgnoreCase)) { destinationPath = item.Value as string; } } // Create FileCopyJob FileCopyJob rtnJob = new FileCopyJob(specification.Name, sourcePath, destinationPath); lock (JobRepository) { JobRepository.Add(rtnJob); } return(rtnJob); }
/// <summary> /// Constructor. /// </summary> /// <param name="name"></param> /// <param name="command"></param> /// <param name="sb"></param> /// <param name="filePath"></param> /// <param name="initSb"></param> /// <param name="argumentList"></param> /// <param name="inputObject"></param> /// <param name="psCmdlet"></param> public ThreadJob( string name, string command, ScriptBlock sb, string filePath, ScriptBlock initSb, object[] argumentList, PSObject inputObject, PSCmdlet psCmdlet) : base(command, name) { _sb = sb; _filePath = filePath; _initSb = initSb; _argumentList = argumentList; _input = new PSDataCollection <object>(); if (inputObject != null) { _input.Add(inputObject); } _output = new PSDataCollection <PSObject>(); this.PSJobTypeName = "ThreadJob"; // Create host object for thread jobs. ThreadJobHost host = new ThreadJobHost(); HookupHostDataDelegates(host); // Create Runspace/PowerShell object and state callback. // The job script/command will run in a separate thread associated with the Runspace. _rs = RunspaceFactory.CreateRunspace(host); _ps = PowerShell.Create(); _ps.Runspace = _rs; _ps.InvocationStateChanged += (sender, psStateChanged) => { var newStateInfo = psStateChanged.InvocationStateInfo; // Update Job state. switch (newStateInfo.State) { case PSInvocationState.Running: SetJobState(JobState.Running); break; case PSInvocationState.Stopped: SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Failed: SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Completed: if (_runningInitScript) { // Begin running main script. _runningInitScript = false; RunScript(); } else { SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true); } break; } }; // Get script block to run. if (!string.IsNullOrEmpty(_filePath)) { _sb = GetScriptBlockFromFile(_filePath, psCmdlet); if (_sb == null) { throw new InvalidOperationException(Properties.Resources.ResourceManager.GetString("CannotParseScriptFile")); } } else if (_sb == null) { throw new PSArgumentNullException(Properties.Resources.ResourceManager.GetString("NoScriptToRun")); } // Get any using variables. var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>(); if (usingAsts != null && usingAsts.FirstOrDefault() != null) { // Get using variables as an array or dictionary, depending on PowerShell version. if (psCmdlet.Host.Version.Major >= 5) { _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet); } else if (psCmdlet.Host.Version.Major == 3 || psCmdlet.Host.Version.Major == 4) { _usingValuesArray = GetUsingValuesAsArray(usingAsts, psCmdlet); } } // Hook up data streams. this.Output = _output; this.Output.EnumeratorNeverBlocks = true; this.Error = _ps.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Progress = _ps.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Verbose = _ps.Streams.Verbose; this.Verbose.EnumeratorNeverBlocks = true; this.Warning = _ps.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; this.Debug = _ps.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; // Create the JobManager job definition and job specification, and add to the JobManager. ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection); var newJob = psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }
private Activity ValidateWorkflow(JobInvocationInfo invocationInfo, Activity activity, ref bool?isSuspendable) { PSWorkflowRuntime runtime = PSWorkflowRuntime.Instance; JobDefinition definition = invocationInfo.Definition; WorkflowJobDefinition workflowJobDefinition = WorkflowJobDefinition.AsWorkflowJobDefinition(definition); bool externalActivity = true; if (activity == null) { bool windowsWorkflow; activity = DefinitionCache.Instance.GetActivityFromCache(workflowJobDefinition, out windowsWorkflow); // Debug.Assert(activity != null, "WorkflowManager failed validation for a null activity"); if (activity == null) { throw new InvalidOperationException(); } externalActivity = false; // skip validation if it is a windows workflow if (windowsWorkflow) { return(activity); } } // If validation is disabled, just return the activity as is... if (!runtime.Configuration.EnableValidation) { return(activity); } if (externalActivity && !DefinitionCache.Instance.AllowExternalActivity) { // If there is a custom validator activity, then call it. If it returns true // then just return the activity. if (Validation.CustomHandler == null) { throw new InvalidOperationException(); } if (Validation.CustomHandler.Invoke(activity)) { return(activity); } string displayName = activity.DisplayName; if (string.IsNullOrEmpty(displayName)) { displayName = this.GetType().Name; } string message = string.Format(CultureInfo.CurrentCulture, Resources.InvalidActivity, displayName); throw new ValidationException(message); } PSWorkflowValidationResults validationResults = GetWorkflowValidator().ValidateWorkflow( definition.InstanceId, activity, DefinitionCache.Instance.GetRuntimeAssemblyName(workflowJobDefinition)); if (validationResults.Results != null) { GetWorkflowValidator().ProcessValidationResults(validationResults.Results); } isSuspendable = validationResults.IsWorkflowSuspendable; return(activity); }
/// <summary> /// Constructor. /// </summary> /// <param name="name"></param> /// <param name="command"></param> /// <param name="sb"></param> /// <param name="filePath"></param> /// <param name="initSb"></param> /// <param name="argumentList"></param> /// <param name="inputObject"></param> /// <param name="psCmdlet"></param> /// <param name="currentLocationPath"></param> /// <param name="streamingHost"></param> public ThreadJob( string name, string command, ScriptBlock sb, string filePath, ScriptBlock initSb, object[] argumentList, PSObject inputObject, PSCmdlet psCmdlet, string currentLocationPath, PSHost streamingHost) : base(command, name) { _sb = sb; _filePath = filePath; _initSb = initSb; _argumentList = argumentList; _input = new PSDataCollection <object>(); if (inputObject != null) { _input.Add(inputObject); } _output = new PSDataCollection <PSObject>(); _streamingHost = streamingHost; _currentLocationPath = currentLocationPath; this.PSJobTypeName = "ThreadJob"; // Get script block to run. if (!string.IsNullOrEmpty(_filePath)) { _sb = GetScriptBlockFromFile(_filePath, psCmdlet); if (_sb == null) { throw new InvalidOperationException(Properties.Resources.CannotParseScriptFile); } } else if (_sb == null) { throw new PSArgumentNullException(Properties.Resources.NoScriptToRun); } // Create Runspace/PowerShell object and state callback. // The job script/command will run in a separate thread associated with the Runspace. var iss = InitialSessionState.CreateDefault2(); // Determine session language mode for Windows platforms WarningRecord lockdownWarning = null; if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase)) { bool enforceLockdown = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce); if (enforceLockdown && !string.IsNullOrEmpty(_filePath)) { // If script source is a file, check to see if it is trusted by the lock down policy enforceLockdown = (SystemPolicy.GetLockdownPolicy(_filePath, null) == SystemEnforcementMode.Enforce); if (!enforceLockdown && (_initSb != null)) { // Even if the script file is trusted, an initialization script cannot be trusted, so we have to enforce // lock down. Otherwise untrusted script could be run in FullLanguage mode along with the trusted file script. enforceLockdown = true; lockdownWarning = new WarningRecord( string.Format( CultureInfo.InvariantCulture, Properties.Resources.CannotRunTrustedFileInFL, _filePath)); } } iss.LanguageMode = enforceLockdown ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; } if (_streamingHost != null) { _rs = RunspaceFactory.CreateRunspace(_streamingHost, iss); } else { _rs = RunspaceFactory.CreateRunspace(iss); } _ps = PowerShell.Create(); _ps.Runspace = _rs; _ps.InvocationStateChanged += (sender, psStateChanged) => { var newStateInfo = psStateChanged.InvocationStateInfo; // Update Job state. switch (newStateInfo.State) { case PSInvocationState.Running: SetJobState(JobState.Running); break; case PSInvocationState.Stopped: SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Failed: SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Completed: if (_runningInitScript) { // Begin running main script. _runningInitScript = false; RunScript(); } else { SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true); } break; } }; // Get any using variables. var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>(); if (usingAsts != null && usingAsts.FirstOrDefault() != null) { // Get using variables as dictionary, since we now only support PowerShell version 5.1 and greater _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet); } // Hook up data streams. this.Output = _output; this.Output.EnumeratorNeverBlocks = true; this.Error = _ps.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Progress = _ps.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Verbose = _ps.Streams.Verbose; this.Verbose.EnumeratorNeverBlocks = true; this.Warning = _ps.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; if (lockdownWarning != null) { this.Warning.Add(lockdownWarning); } this.Debug = _ps.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; this.Information = _ps.Streams.Information; this.Information.EnumeratorNeverBlocks = true; // Create the JobManager job definition and job specification, and add to the JobManager. ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection); var newJob = psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }
private Activity ValidateWorkflow(JobInvocationInfo invocationInfo, Activity activity, ref bool?isSuspendable) { bool flag = false; PSWorkflowRuntime instance = PSWorkflowRuntime.Instance; JobDefinition definition = invocationInfo.Definition; WorkflowJobDefinition workflowJobDefinition = WorkflowJobDefinition.AsWorkflowJobDefinition(definition); bool flag1 = true; if (activity == null) { activity = DefinitionCache.Instance.GetActivityFromCache(workflowJobDefinition, out flag); if (activity != null) { flag1 = false; if (flag) { return(activity); } } else { throw new InvalidOperationException(); } } if (instance.Configuration.EnableValidation) { if (!flag1 || DefinitionCache.Instance.AllowExternalActivity) { PSWorkflowValidationResults pSWorkflowValidationResult = this.GetWorkflowValidator().ValidateWorkflow(definition.InstanceId, activity, DefinitionCache.Instance.GetRuntimeAssemblyName(workflowJobDefinition)); if (pSWorkflowValidationResult.Results != null) { this.GetWorkflowValidator().ProcessValidationResults(pSWorkflowValidationResult.Results); } isSuspendable = new bool?(pSWorkflowValidationResult.IsWorkflowSuspendable); return(activity); } else { if (Validation.CustomHandler != null) { if (!Validation.CustomHandler(activity)) { string displayName = activity.DisplayName; if (string.IsNullOrEmpty(displayName)) { displayName = base.GetType().Name; } object[] objArray = new object[1]; objArray[0] = displayName; string str = string.Format(CultureInfo.CurrentCulture, Resources.InvalidActivity, objArray); throw new ValidationException(str); } else { return(activity); } } else { throw new InvalidOperationException(); } } } else { return(activity); } }
public override Job2 NewJob(JobInvocationInfo specification) { bool hasValue; if (specification != null) { if (specification.Definition != null) { if (specification.Definition.JobSourceAdapterType == base.GetType()) { if (specification.Parameters.Count == 0) { specification.Parameters.Add(new CommandParameterCollection()); } bool? nullable = null; Activity activity = this.ValidateWorkflow(specification, null, ref nullable); ContainerParentJob containerParentJob = this.GetJobManager().CreateJob(specification, activity); if (!PSSessionConfigurationData.IsServerManager) { foreach (PSWorkflowJob childJob in containerParentJob.ChildJobs) { bool?item = null; PSWorkflowContext pSWorkflowContext = childJob.PSWorkflowInstance.PSWorkflowContext; if (pSWorkflowContext != null && pSWorkflowContext.PSWorkflowCommonParameters != null && pSWorkflowContext.PSWorkflowCommonParameters.ContainsKey("PSPersist")) { item = (bool?)(pSWorkflowContext.PSWorkflowCommonParameters["PSPersist"] as bool?); } if (item.HasValue) { bool?nullable1 = item; if (nullable1.GetValueOrDefault()) { hasValue = false; } else { hasValue = nullable1.HasValue; } if (!hasValue) { continue; } } if (!nullable.HasValue || nullable.Value) { continue; } childJob.Warning.Add(new WarningRecord(Resources.WarningMessageForPersistence)); childJob.IsSuspendable = nullable; } } base.StoreJobIdForReuse(containerParentJob, true); this._jobRepository.Add(containerParentJob); return(containerParentJob); } else { throw new InvalidOperationException(Resources.NewJobWrongType); } } else { throw new ArgumentException(Resources.NewJobDefinitionNull, "specification"); } } else { throw new ArgumentNullException("specification"); } }
public override Job2 NewJob(JobInvocationInfo specification) { throw new NotImplementedException(); }