// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using System.Management.Automation.Tracing; using System.Reflection; using System.Security; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; // Stops compiler from warning about unknown warnings #pragma warning disable 1634, 1691 namespace System.Management.Automation { /// /// Manager for JobSourceAdapters for invocation and management of specific Job types. /// public sealed class JobManager { private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); /// /// Collection of registered JobSourceAdapters. /// private readonly Dictionary _sourceAdapters = new Dictionary(); private readonly object _syncObject = new object(); /// /// Collection of job IDs that are valid for reuse. /// private static readonly Dictionary> s_jobIdsForReuse = new Dictionary>(); private static readonly object s_syncObject = new object(); /// /// Creates a JobManager instance. /// internal JobManager() { } /// /// Returns true if the type is already registered. /// /// Type to check. /// Whether the type is registered already. public bool IsRegistered(string typeName) { if (string.IsNullOrEmpty(typeName)) { return false; } lock (_syncObject) { return _sourceAdapters.ContainsKey(typeName); } } /// /// Adds a new JobSourceAdapter to the JobManager instance. /// After addition, creating a NewJob with a JobDefinition /// indicating the JobSourceAdapter derivative type will function. /// /// The derivative JobSourceAdapter type to /// register. /// Throws when there is no public /// default constructor on the type. internal void RegisterJobSourceAdapter(Type jobSourceAdapterType) { Dbg.Assert(typeof(JobSourceAdapter).IsAssignableFrom(jobSourceAdapterType), "BaseType of any type being registered with the JobManager should be JobSourceAdapter."); Dbg.Assert(jobSourceAdapterType != typeof(JobSourceAdapter), "JobSourceAdapter abstract type itself should never be registered."); Dbg.Assert(jobSourceAdapterType != null, "JobSourceAdapterType should never be called with null value."); object instance = null; ConstructorInfo constructor = jobSourceAdapterType.GetConstructor(Type.EmptyTypes); if (!constructor.IsPublic) { string message = string.Format(CultureInfo.CurrentCulture, RemotingErrorIdStrings.JobManagerRegistrationConstructorError, jobSourceAdapterType.FullName); throw new InvalidOperationException(message); } try { instance = constructor.Invoke(null); } catch (MemberAccessException exception) { _tracer.TraceException(exception); throw; } catch (TargetInvocationException exception) { _tracer.TraceException(exception); throw; } catch (TargetParameterCountException exception) { _tracer.TraceException(exception); throw; } catch (NotSupportedException exception) { _tracer.TraceException(exception); throw; } catch (SecurityException exception) { _tracer.TraceException(exception); throw; } if (instance != null) { lock (_syncObject) { _sourceAdapters.Add(jobSourceAdapterType.Name, (JobSourceAdapter)instance); } } } /// /// Returns a token that allows a job to be constructed with a specific id and instanceId. /// The original job must have been saved using "SaveJobIdForReconstruction" in the JobSourceAdapter. /// /// The instance id desired. /// The requesting type name for JobSourceAdapter implementation. /// Token for job creation. internal static JobIdentifier GetJobIdentifier(Guid instanceId, string typeName) { lock (s_syncObject) { KeyValuePair keyValuePair; if (s_jobIdsForReuse.TryGetValue(instanceId, out keyValuePair) && keyValuePair.Value.Equals(typeName)) return new JobIdentifier(keyValuePair.Key, instanceId); return null; } } /// /// Saves the Id information for a job so that it can be constructed at a later time by a JobSourceAdapter /// with the same type. /// /// The instance id to save. /// The session specific id to save. /// The type name for the JobSourceAdapter implementation doing the save. internal static void SaveJobId(Guid instanceId, int id, string typeName) { lock (s_syncObject) { if (s_jobIdsForReuse.ContainsKey(instanceId)) { return; } s_jobIdsForReuse.Add(instanceId, new KeyValuePair(id, typeName)); } } #region NewJob /// /// Creates a new job of the appropriate type given by JobDefinition passed in. /// /// JobDefinition defining the command. /// Job2 object of the appropriate type specified by the definition. /// If JobSourceAdapter type specified /// in definition is not registered. /// JobSourceAdapter implementation exception thrown on error. /// public Job2 NewJob(JobDefinition definition) { ArgumentNullException.ThrowIfNull(definition); JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); Job2 newJob; #pragma warning disable 56500 try { newJob = sourceAdapter.NewJob(definition); } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. // sourceAdapter.NewJob returned unknown error. _tracer.TraceException(exception); throw; } #pragma warning restore 56500 return newJob; } /// /// Creates a new job of the appropriate type given by JobDefinition passed in. /// /// JobInvocationInfo defining the command. /// Job2 object of the appropriate type specified by the definition. /// If JobSourceAdapter type specified /// in definition is not registered. /// JobSourceAdapter implementation exception thrown on error. /// public Job2 NewJob(JobInvocationInfo specification) { ArgumentNullException.ThrowIfNull(specification); if (specification.Definition == null) { throw new ArgumentException(RemotingErrorIdStrings.NewJobSpecificationError, nameof(specification)); } JobSourceAdapter sourceAdapter = GetJobSourceAdapter(specification.Definition); Job2 newJob = null; #pragma warning disable 56500 try { newJob = sourceAdapter.NewJob(specification); } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. // sourceAdapter.NewJob returned unknown error. _tracer.TraceException(exception); throw; } #pragma warning restore 56500 return newJob; } #endregion NewJob #region Persist Job /// /// Saves the job to a persisted store. /// /// Job2 type job to persist. /// Job definition containing source adapter information. public void PersistJob(Job2 job, JobDefinition definition) { if (job == null) { throw new PSArgumentNullException(nameof(job)); } if (definition == null) { throw new PSArgumentNullException(nameof(definition)); } JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); try { sourceAdapter.PersistJob(job); } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. // sourceAdapter.NewJob returned unknown error. _tracer.TraceException(exception); throw; } } #endregion /// /// Helper method, finds source adapter if registered, otherwise throws /// an InvalidOperationException. /// /// The name of the JobSourceAdapter derivative desired. /// The JobSourceAdapter instance. /// If JobSourceAdapter type specified /// is not found. private JobSourceAdapter AssertAndReturnJobSourceAdapter(string adapterTypeName) { JobSourceAdapter adapter; lock (_syncObject) { if (!_sourceAdapters.TryGetValue(adapterTypeName, out adapter)) { throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound); } } return adapter; } /// /// Helper method to find and return the job source adapter if currently loaded or /// otherwise load the associated module and the requested source adapter. /// /// JobDefinition supplies the JobSourceAdapter information. /// JobSourceAdapter. private JobSourceAdapter GetJobSourceAdapter(JobDefinition definition) { string adapterTypeName; if (!string.IsNullOrEmpty(definition.JobSourceAdapterTypeName)) { adapterTypeName = definition.JobSourceAdapterTypeName; } else if (definition.JobSourceAdapterType != null) { adapterTypeName = definition.JobSourceAdapterType.Name; } else { throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound); } JobSourceAdapter adapter; bool adapterFound = false; lock (_syncObject) { adapterFound = _sourceAdapters.TryGetValue(adapterTypeName, out adapter); } if (!adapterFound) { if (!string.IsNullOrEmpty(definition.ModuleName)) { // Attempt to load the module. Exception ex = null; try { InitialSessionState iss = InitialSessionState.CreateDefault2(); iss.Commands.Clear(); iss.Formats.Clear(); iss.Commands.Add(new SessionStateCmdletEntry("Import-Module", typeof(Microsoft.PowerShell.Commands.ImportModuleCommand), null)); using (PowerShell powerShell = PowerShell.Create(iss)) { powerShell.AddCommand("Import-Module"); powerShell.AddParameter("Name", definition.ModuleName); powerShell.Invoke(); if (powerShell.ErrorBuffer.Count > 0) { ex = powerShell.ErrorBuffer[0].Exception; } } } catch (RuntimeException e) { ex = e; } catch (InvalidOperationException e) { ex = e; } catch (ScriptCallDepthException e) { ex = e; } catch (SecurityException e) { ex = e; } if (ex != null) { throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound, ex); } // Now try getting the job source adapter again. adapter = AssertAndReturnJobSourceAdapter(adapterTypeName); } else { throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound); } } return adapter; } #region GetJobs /// /// Get list of all jobs. /// /// Cmdlet requesting this, for error processing. /// /// /// Job source adapter type names. /// Collection of jobs. /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobs( Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, string[] jobSourceAdapterTypes) { return GetFilteredJobs(null, FilterType.None, cmdlet, writeErrorOnException, writeObject, false, jobSourceAdapterTypes); } /// /// Get list of jobs that matches the specified names. /// /// Names to match, can support /// wildcard if the store supports. /// Cmdlet requesting this, for error processing. /// /// /// /// Job source adapter type names. /// Collection of jobs that match the specified /// criteria. /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobsByName( string name, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { return GetFilteredJobs(name, FilterType.Name, cmdlet, writeErrorOnException, writeObject, recurse, jobSourceAdapterTypes); } /// /// Get list of jobs that run the specified command. /// /// Command to match. /// Cmdlet requesting this, for error processing. /// /// /// /// Job source adapter type names. /// Collection of jobs that match the specified /// criteria. /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobsByCommand( string command, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { return GetFilteredJobs(command, FilterType.Command, cmdlet, writeErrorOnException, writeObject, recurse, jobSourceAdapterTypes); } /// /// Get list of jobs that are in the specified state. /// /// State to match. /// Cmdlet requesting this, for error processing. /// /// /// /// Job source adapter type names. /// Collection of jobs with the specified /// state. /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobsByState( JobState state, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { return GetFilteredJobs(state, FilterType.State, cmdlet, writeErrorOnException, writeObject, recurse, jobSourceAdapterTypes); } /// /// Get list of jobs based on the adapter specific /// filter parameters. /// /// Dictionary containing name value /// pairs for adapter specific filters. /// Cmdlet requesting this, for error processing. /// /// /// /// Collection of jobs that match the /// specified criteria. /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobsByFilter(Dictionary filter, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { return GetFilteredJobs(filter, FilterType.Filter, cmdlet, writeErrorOnException, writeObject, recurse, null); } /// /// Get a filtered list of jobs based on adapter name. /// /// Job id. /// Adapter name. /// internal bool IsJobFromAdapter(Guid id, string name) { lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { if (sourceAdapter.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { return (sourceAdapter.GetJobByInstanceId(id, false) != null); } } } return false; } /// /// Get a filtered list of jobs based on filter type. /// /// Object to use for filtering. /// Type of filter, specifies which "get" from /// JobSourceAdapter to call, and dictates the type for filter. /// Cmdlet requesting this, for error processing. /// /// /// /// Job source adapter type names. /// Filtered list of jobs. /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. private List GetFilteredJobs( object filter, FilterType filterType, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { Diagnostics.Assert(cmdlet != null, "Cmdlet should be passed to JobManager"); List allJobs = new List(); lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { List jobs = null; // Filter search based on job source adapter types if provided. if (!CheckTypeNames(sourceAdapter, jobSourceAdapterTypes)) { continue; } #pragma warning disable 56500 try { jobs = CallJobFilter(sourceAdapter, filter, filterType, recurse); } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. // sourceAdapter.GetJobsByFilter() threw unknown exception. _tracer.TraceException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobsError", sourceAdapter); } #pragma warning restore 56500 if (jobs == null) { continue; } allJobs.AddRange(jobs); } } if (writeObject) { foreach (Job2 job in allJobs) { cmdlet.WriteObject(job); } } return allJobs; } /// /// Compare sourceAdapter name with the provided source adapter type /// name list. /// /// /// /// private static bool CheckTypeNames(JobSourceAdapter sourceAdapter, string[] jobSourceAdapterTypes) { // If no type names were specified then allow all adapter types. if (jobSourceAdapterTypes == null || jobSourceAdapterTypes.Length == 0) { return true; } string sourceAdapterName = GetAdapterName(sourceAdapter); Diagnostics.Assert(sourceAdapterName != null, "Source adapter should have name or type."); // Look for name match allowing wildcards. foreach (string typeName in jobSourceAdapterTypes) { WildcardPattern typeNamePattern = WildcardPattern.Get(typeName, WildcardOptions.IgnoreCase); if (typeNamePattern.IsMatch(sourceAdapterName)) { return true; } } return false; } private static string GetAdapterName(JobSourceAdapter sourceAdapter) { return (!string.IsNullOrEmpty(sourceAdapter.Name) ? sourceAdapter.Name : sourceAdapter.GetType().ToString()); } /// /// Gets a filtered list of jobs from the given JobSourceAdapter. /// /// JobSourceAdapter to query. /// Filter object. /// Filter type. /// /// List of jobs from sourceAdapter filtered on filterType. /// Throws exception on error from JobSourceAdapter /// implementation. private static List CallJobFilter(JobSourceAdapter sourceAdapter, object filter, FilterType filterType, bool recurse) { List jobs = new List(); IList matches; switch (filterType) { case FilterType.Command: matches = sourceAdapter.GetJobsByCommand((string)filter, recurse); break; case FilterType.Filter: matches = sourceAdapter.GetJobsByFilter((Dictionary)filter, recurse); break; case FilterType.Name: matches = sourceAdapter.GetJobsByName((string)filter, recurse); break; case FilterType.State: matches = sourceAdapter.GetJobsByState((JobState)filter, recurse); break; case FilterType.None: default: matches = sourceAdapter.GetJobs(); break; } if (matches != null) { jobs.AddRange(matches); } return jobs; } /// /// Get job specified by the session specific id provided. /// /// Session specific job id. /// Cmdlet requesting this, for error processing. /// /// /// /// Job that match the specified criteria. /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal Job2 GetJobById(int id, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { return GetJobThroughId(Guid.Empty, id, cmdlet, writeErrorOnException, writeObject, recurse); } /// /// Get job that has the specified id. /// /// Guid to match. /// Cmdlet requesting this, for error processing. /// /// /// /// Job with the specified guid. /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal Job2 GetJobByInstanceId(Guid instanceId, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { return GetJobThroughId(instanceId, 0, cmdlet, writeErrorOnException, writeObject, recurse); } private Job2 GetJobThroughId(Guid guid, int id, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { Diagnostics.Assert(cmdlet != null, "Cmdlet should always be passed to JobManager"); Job2 job = null; lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { try { if (typeof(T) == typeof(Guid)) { Diagnostics.Assert(id == 0, "id must be zero when invoked with guid"); job = sourceAdapter.GetJobByInstanceId(guid, recurse); } else if (typeof(T) == typeof(int)) { Diagnostics.Assert(guid == Guid.Empty, "Guid must be empty when used with int"); job = sourceAdapter.GetJobBySessionId(id, recurse); } } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. // sourceAdapter.GetJobByInstanceId threw unknown exception. _tracer.TraceException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); } if (job == null) { continue; } if (writeObject) { cmdlet.WriteObject(job); } return job; } } return null; } /// /// Gets or creates a Job2 object with the given definition name, path /// and definition type if specified, that can be run via the StartJob() /// method. /// /// Job definition name. /// Job definition file path. /// JobSourceAdapter type that contains the job definition. /// Cmdlet making call. /// Whether to write jobsourceadapter errors. /// List of matching Job2 objects. internal List GetJobToStart( string definitionName, string definitionPath, string definitionType, Cmdlet cmdlet, bool writeErrorOnException) { List jobs = new List(); WildcardPattern typeNamePattern = (definitionType != null) ? WildcardPattern.Get(definitionType, WildcardOptions.IgnoreCase) : null; lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { try { if (typeNamePattern != null) { string sourceAdapterName = GetAdapterName(sourceAdapter); if (!typeNamePattern.IsMatch(sourceAdapterName)) { continue; } } Job2 job = sourceAdapter.NewJob(definitionName, definitionPath); if (job != null) { jobs.Add(job); } if (typeNamePattern != null) { // Adapter type found, can quit. break; } } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. _tracer.TraceException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); } } } return jobs; } private static void WriteErrorOrWarning(bool writeErrorOnException, Cmdlet cmdlet, Exception exception, string identifier, JobSourceAdapter sourceAdapter) { try { if (writeErrorOnException) { cmdlet.WriteError(new ErrorRecord(exception, identifier, ErrorCategory.OpenError, sourceAdapter)); } else { // Write a warning string message = string.Format(CultureInfo.CurrentCulture, RemotingErrorIdStrings.JobSourceAdapterError, exception.Message, sourceAdapter.Name); cmdlet.WriteWarning(message); } } catch (Exception) { // if this call is not made from a cmdlet thread or if // the cmdlet is closed this will thrown an exception // it is fine to eat that exception } } /// /// Returns a List of adapter names currently loaded. /// /// Adapter names to filter on. /// List of names. internal List GetLoadedAdapterNames(string[] adapterTypeNames) { List adapterNames = new List(); lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { if (CheckTypeNames(sourceAdapter, adapterTypeNames)) { adapterNames.Add(GetAdapterName(sourceAdapter)); } } } return adapterNames; } #endregion GetJobs #region RemoveJob /// /// Remove a job from the appropriate store. /// /// Session specific Job ID to remove. /// /// internal void RemoveJob(int sessionJobId, Cmdlet cmdlet, bool writeErrorOnException) { Job2 job = GetJobById(sessionJobId, cmdlet, writeErrorOnException, false, false); RemoveJob(job, cmdlet, false); } /// /// Remove a job from the appropriate store. /// /// Job object to remove. /// /// /// If true, will throw all JobSourceAdapter exceptions to caller. /// This is needed if RemoveJob is being called from an event handler in Receive-Job. /// True if job is found. internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, bool throwExceptions = false) { bool jobFound = false; lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { Job2 foundJob = null; #pragma warning disable 56500 try { foundJob = sourceAdapter.GetJobByInstanceId(job.InstanceId, true); } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. // sourceAdapter.GetJobByInstanceId() threw unknown exception. _tracer.TraceException(exception); if (throwExceptions) { throw; } WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", sourceAdapter); } #pragma warning restore 56500 if (foundJob == null) { continue; } jobFound = true; RemoveJobIdForReuse(foundJob); #pragma warning disable 56500 try { sourceAdapter.RemoveJob(job); } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. // sourceAdapter.RemoveJob() threw unknown exception. _tracer.TraceException(exception); if (throwExceptions) { throw; } WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterRemoveJobError", sourceAdapter); } #pragma warning restore 56500 } } if (!jobFound && throwExceptions) { var message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository, "Job repository", job.InstanceId.ToString()); throw new ArgumentException(message); } return jobFound; } private void RemoveJobIdForReuse(Job job) { Hashtable duplicateDetector = new Hashtable(); duplicateDetector.Add(job.Id, job.Id); RemoveJobIdForReuseHelper(duplicateDetector, job); } private void RemoveJobIdForReuseHelper(Hashtable duplicateDetector, Job job) { lock (s_syncObject) { s_jobIdsForReuse.Remove(job.InstanceId); } foreach (Job child in job.ChildJobs) { if (duplicateDetector.ContainsKey(child.Id)) { continue; } duplicateDetector.Add(child.Id, child.Id); RemoveJobIdForReuse(child); } } #endregion RemoveJob /// /// Filters available for GetJob, used internally to centralize Exception handling. /// private enum FilterType { /// /// Use no filter. /// None, /// /// Filter on command (string). /// Command, /// /// Filter on custom dictionary (dictionary(string, object)). /// Filter, /// /// Filter on name (string). /// Name, /// /// Filter on job state (JobState). /// State } } }