File size: 27,355 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.PowerShell.Cmdletization
{
/// <summary>
/// Provides common code for processing session-based object models. The common code
/// Session, ThrottleLimit, AsJob parameters and delegates creation of jobs to derived classes.
/// </summary>
/// <typeparam name="TObjectInstance">Type that represents instances of objects from the wrapped object model</typeparam>
/// <typeparam name="TSession">Type representing remote sessions</typeparam>
[SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
public abstract class SessionBasedCmdletAdapter<TObjectInstance, TSession> : CmdletAdapter<TObjectInstance>, IDisposable
where TObjectInstance : class
where TSession : class
{
internal SessionBasedCmdletAdapter()
{
}
#region Constants
private const string CIMJobType = "CimJob";
#endregion
#region IDisposable Members
private bool _disposed;
/// <summary>
/// Releases resources associated with this object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases resources associated with this object.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_parentJob != null)
{
_parentJob.Dispose();
_parentJob = null;
}
}
_disposed = true;
}
}
#endregion
#region Common parameters (AsJob, ThrottleLimit, Session)
/// <summary>
/// Session to operate on.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
protected TSession[] Session
{
get
{
return _session ??= new TSession[] { this.DefaultSession };
}
set
{
ArgumentNullException.ThrowIfNull(value);
_session = value;
_sessionWasSpecified = true;
}
}
private TSession[] _session;
private bool _sessionWasSpecified;
/// <summary>
/// Whether to wrap and emit the whole operation as a background job.
/// </summary>
[Parameter]
public SwitchParameter AsJob
{
get { return _asJob; }
set { _asJob = value; }
}
private bool _asJob;
/// <summary>
/// Maximum number of remote connections that can remain active at any given time.
/// </summary>
[Parameter]
public virtual int ThrottleLimit { get; set; }
#endregion Common CIM-related parameters
#region Abstract methods to be overridden in derived classes
/// <summary>
/// Creates a <see cref="System.Management.Automation.Job"/> object that performs a query against the wrapped object model.
/// </summary>
/// <param name="session">Remote session to query.</param>
/// <param name="query">Query parameters.</param>
/// <remarks>
/// <para>
/// This method shouldn't do any processing or interact with the remote session.
/// Doing so will interfere with ThrottleLimit functionality.
/// </para>
/// <para>
/// <see cref="Job.WriteObject"/> (and other methods returning job results) will block to support throttling and flow-control.
/// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing,
/// until calls from <see cref="Job.WriteObject"/> (and other methods returning job results) return.
/// </para>
/// </remarks>
internal abstract StartableJob CreateQueryJob(TSession session, QueryBuilder query);
private StartableJob DoCreateQueryJob(TSession sessionForJob, QueryBuilder query, Action<TSession, TObjectInstance> actionAgainstResults)
{
StartableJob queryJob = this.CreateQueryJob(sessionForJob, query);
if (queryJob != null)
{
if (actionAgainstResults != null)
{
queryJob.SuppressOutputForwarding = true;
}
bool discardNonPipelineResults = (actionAgainstResults != null) || !this.AsJob.IsPresent;
HandleJobOutput(
queryJob,
sessionForJob,
discardNonPipelineResults,
actionAgainstResults == null
? (Action<PSObject>)null
: ((PSObject pso) =>
{
var objectInstance =
(TObjectInstance)LanguagePrimitives.ConvertTo(
pso,
typeof(TObjectInstance),
CultureInfo.InvariantCulture);
actionAgainstResults(sessionForJob, objectInstance);
}));
}
return queryJob;
}
/// <summary>
/// Creates a <see cref="System.Management.Automation.Job"/> object that invokes an instance method in the wrapped object model.
/// </summary>
/// <param name="session">Remote session to invoke the method in.</param>
/// <param name="objectInstance">The object on which to invoke the method.</param>
/// <param name="methodInvocationInfo">Method invocation details.</param>
/// <param name="passThru"><see langword="true"/> if successful method invocations should emit downstream the <paramref name="objectInstance"/> being operated on.</param>
/// <remarks>
/// <para>
/// This method shouldn't do any processing or interact with the remote session.
/// Doing so will interfere with ThrottleLimit functionality.
/// </para>
/// <para>
/// <see cref="Job.WriteObject"/> (and other methods returning job results) will block to support throttling and flow-control.
/// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing,
/// until calls from <see cref="Job.WriteObject"/> (and other methods returning job results) return.
/// </para>
/// </remarks>
internal abstract StartableJob CreateInstanceMethodInvocationJob(TSession session, TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru);
private StartableJob DoCreateInstanceMethodInvocationJob(TSession sessionForJob, TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru, bool asJob)
{
StartableJob methodInvocationJob = this.CreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru);
if (methodInvocationJob != null)
{
bool discardNonPipelineResults = !asJob;
HandleJobOutput(
methodInvocationJob,
sessionForJob,
discardNonPipelineResults,
outputAction: null);
}
return methodInvocationJob;
}
/// <summary>
/// Creates a <see cref="System.Management.Automation.Job"/> object that invokes a static method in the wrapped object model.
/// </summary>
/// <param name="session">Remote session to invoke the method in.</param>
/// <param name="methodInvocationInfo">Method invocation details.</param>
/// <remarks>
/// <para>
/// This method shouldn't do any processing or interact with the remote session.
/// Doing so will interfere with ThrottleLimit functionality.
/// </para>
/// <para>
/// <see cref="Job.WriteObject"/> (and other methods returning job results) will block to support throttling and flow-control.
/// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing,
/// until calls from <see cref="Job.WriteObject"/> (and other methods returning job results) return.
/// </para>
/// </remarks>
internal abstract StartableJob CreateStaticMethodInvocationJob(TSession session, MethodInvocationInfo methodInvocationInfo);
private StartableJob DoCreateStaticMethodInvocationJob(TSession sessionForJob, MethodInvocationInfo methodInvocationInfo)
{
StartableJob methodInvocationJob = this.CreateStaticMethodInvocationJob(sessionForJob, methodInvocationInfo);
if (methodInvocationJob != null)
{
bool discardNonPipelineResults = !this.AsJob.IsPresent;
HandleJobOutput(
methodInvocationJob,
sessionForJob,
discardNonPipelineResults,
outputAction: null);
}
return methodInvocationJob;
}
private static void HandleJobOutput(Job job, TSession sessionForJob, bool discardNonPipelineResults, Action<PSObject> outputAction)
{
Action<PSObject> processOutput =
(PSObject pso) =>
{
if (pso == null)
{
return;
}
outputAction?.Invoke(pso);
};
job.Output.DataAdded +=
(object sender, DataAddedEventArgs eventArgs) =>
{
var dataCollection = (PSDataCollection<PSObject>)sender;
if (discardNonPipelineResults)
{
foreach (PSObject pso in dataCollection.ReadAll())
{
// TODO/FIXME - need to make sure that the dataCollection will be throttled
// (i.e. it won't accept more items - it will block in Add method)
// until this processOutput call completes
processOutput(pso);
}
}
else
{
PSObject pso = dataCollection[eventArgs.Index];
processOutput(pso);
}
};
if (discardNonPipelineResults)
{
DiscardJobOutputs(job, JobOutputs.NonPipelineResults & (~JobOutputs.Output));
}
}
internal virtual TSession GetSessionOfOriginFromInstance(TObjectInstance instance)
{
return null;
}
/// <summary>
/// Returns default sessions to use when the user doesn't specify the -Session cmdlet parameter.
/// </summary>
/// <returns>Default sessions to use when the user doesn't specify the -Session cmdlet parameter.</returns>
protected abstract TSession DefaultSession { get; }
/// <summary>
/// A new job name to use for the parent job that handles throttling of the child jobs that actually perform querying and method invocation.
/// </summary>
protected abstract string GenerateParentJobName();
#endregion
#region Helper methods
private static void DiscardJobOutputs<T>(PSDataCollection<T> psDataCollection)
{
psDataCollection.DataAdded +=
(object sender, DataAddedEventArgs e) =>
{
var localDataCollection = (PSDataCollection<T>)sender;
localDataCollection.Clear();
};
}
[Flags]
private enum JobOutputs
{
Output = 0x1,
Error = 0x2,
Warning = 0x4,
Verbose = 0x8,
Debug = 0x10,
Progress = 0x20,
Results = 0x40,
NonPipelineResults = Output | Error | Warning | Verbose | Debug | Progress,
PipelineResults = Results,
}
private static void DiscardJobOutputs(Job job, JobOutputs jobOutputsToDiscard)
{
if ((jobOutputsToDiscard & JobOutputs.Output) == JobOutputs.Output)
{
DiscardJobOutputs(job.Output);
}
if ((jobOutputsToDiscard & JobOutputs.Error) == JobOutputs.Error)
{
DiscardJobOutputs(job.Error);
}
if ((jobOutputsToDiscard & JobOutputs.Warning) == JobOutputs.Warning)
{
DiscardJobOutputs(job.Warning);
}
if ((jobOutputsToDiscard & JobOutputs.Verbose) == JobOutputs.Verbose)
{
DiscardJobOutputs(job.Verbose);
}
if ((jobOutputsToDiscard & JobOutputs.Debug) == JobOutputs.Debug)
{
DiscardJobOutputs(job.Debug);
}
if ((jobOutputsToDiscard & JobOutputs.Progress) == JobOutputs.Progress)
{
DiscardJobOutputs(job.Progress);
}
if ((jobOutputsToDiscard & JobOutputs.Results) == JobOutputs.Results)
{
DiscardJobOutputs(job.Results);
}
}
#endregion Helper methods
#region Implementation of ObjectModelWrapper functionality
private ThrottlingJob _parentJob;
/// <summary>
/// Queries for object instances in the object model.
/// </summary>
/// <param name="query">Query parameters.</param>
/// <returns>A lazy evaluated collection of object instances.</returns>
public override void ProcessRecord(QueryBuilder query)
{
_parentJob.DisableFlowControlForPendingCmdletActionsQueue();
foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query))
{
StartableJob childJob = this.DoCreateQueryJob(sessionForJob, query, actionAgainstResults: null);
if (childJob != null)
{
if (!this.AsJob.IsPresent)
{
_parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None);
}
else
{
_parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None);
}
}
}
}
/// <summary>
/// Queries for instance and invokes an instance method.
/// </summary>
/// <param name="query">Query parameters.</param>
/// <param name="methodInvocationInfo">Method invocation details.</param>
/// <param name="passThru"><see langword="true"/> if successful method invocations should emit downstream the object instance being operated on.</param>
public override void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru)
{
_parentJob.DisableFlowControlForPendingJobsQueue();
ThrottlingJob closureOverParentJob = _parentJob;
SwitchParameter closureOverAsJob = this.AsJob;
foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query))
{
StartableJob queryJob = this.DoCreateQueryJob(
sessionForJob,
query,
(TSession sessionForMethodInvocationJob, TObjectInstance objectInstance) =>
{
StartableJob methodInvocationJob = this.DoCreateInstanceMethodInvocationJob(
sessionForMethodInvocationJob,
objectInstance,
methodInvocationInfo,
passThru,
closureOverAsJob.IsPresent);
if (methodInvocationJob != null)
{
closureOverParentJob.AddChildJobAndPotentiallyBlock(methodInvocationJob, ThrottlingJob.ChildJobFlags.None);
}
});
if (queryJob != null)
{
if (!this.AsJob.IsPresent)
{
_parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs);
}
else
{
_parentJob.AddChildJobWithoutBlocking(queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs);
}
}
}
}
private IEnumerable<TSession> GetSessionsToActAgainst(TObjectInstance objectInstance)
{
if (_sessionWasSpecified)
{
return this.Session;
}
TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance);
if (associatedSession != null)
{
return new[] { associatedSession };
}
return new[] { this.GetImpliedSession() };
}
private TSession GetSessionAssociatedWithPipelineObject()
{
object inputVariableValue = this.Cmdlet.Context.GetVariableValue(SpecialVariables.InputVarPath, null);
if (inputVariableValue == null)
{
return null;
}
IEnumerable inputEnumerable = LanguagePrimitives.GetEnumerable(inputVariableValue);
if (inputEnumerable == null)
{
return null;
}
List<object> inputCollection = inputEnumerable.Cast<object>().ToList();
if (inputCollection.Count != 1)
{
return null;
}
TObjectInstance inputInstance;
if (!LanguagePrimitives.TryConvertTo(inputCollection[0], CultureInfo.InvariantCulture, out inputInstance))
{
return null;
}
TSession associatedSession = this.GetSessionOfOriginFromInstance(inputInstance);
return associatedSession;
}
private IEnumerable<TSession> GetSessionsToActAgainst(QueryBuilder queryBuilder)
{
if (_sessionWasSpecified)
{
return this.Session;
}
if (queryBuilder is ISessionBoundQueryBuilder<TSession> sessionBoundQueryBuilder)
{
TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession();
if (sessionOfTheQueryBuilder != null)
{
return new[] { sessionOfTheQueryBuilder };
}
}
TSession sessionAssociatedWithPipelineObject = this.GetSessionAssociatedWithPipelineObject();
if (sessionAssociatedWithPipelineObject != null)
{
return new[] { sessionAssociatedWithPipelineObject };
}
return new[] { this.GetImpliedSession() };
}
private IEnumerable<TSession> GetSessionsToActAgainst(MethodInvocationInfo methodInvocationInfo)
{
if (_sessionWasSpecified)
{
return this.Session;
}
var associatedSessions = new HashSet<TSession>();
foreach (TObjectInstance objectInstance in methodInvocationInfo.GetArgumentsOfType<TObjectInstance>())
{
TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance);
if (associatedSession != null)
{
associatedSessions.Add(associatedSession);
}
}
if (associatedSessions.Count == 1)
{
return associatedSessions;
}
TSession sessionAssociatedWithPipelineObject = this.GetSessionAssociatedWithPipelineObject();
if (sessionAssociatedWithPipelineObject != null)
{
return new[] { sessionAssociatedWithPipelineObject };
}
return new[] { this.GetImpliedSession() };
}
internal PSModuleInfo PSModuleInfo
{
get
{
var scriptCommandInfo = this.Cmdlet.CommandInfo as IScriptCommandInfo;
return scriptCommandInfo.ScriptBlock.Module;
}
}
private TSession GetImpliedSession()
{
TSession sessionFromImportModule;
// When being called from a CIM activity, this will be invoked as
// a function so there will be no module info
if (this.PSModuleInfo != null)
{
if (PSPrimitiveDictionary.TryPathGet(
this.PSModuleInfo.PrivateData as IDictionary,
out sessionFromImportModule,
ScriptWriter.PrivateDataKey_CmdletsOverObjects,
ScriptWriter.PrivateDataKey_DefaultSession))
{
return sessionFromImportModule;
}
}
return this.DefaultSession;
}
/// <summary>
/// Invokes an instance method in the object model.
/// </summary>
/// <param name="objectInstance">The object on which to invoke the method.</param>
/// <param name="methodInvocationInfo">Method invocation details.</param>
/// <param name="passThru"><see langword="true"/> if successful method invocations should emit downstream the <paramref name="objectInstance"/> being operated on.</param>
public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru)
{
ArgumentNullException.ThrowIfNull(objectInstance);
ArgumentNullException.ThrowIfNull(methodInvocationInfo);
foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance))
{
StartableJob childJob = this.DoCreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru, this.AsJob.IsPresent);
if (childJob != null)
{
if (!this.AsJob.IsPresent)
{
_parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None);
}
else
{
_parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None);
}
}
}
}
/// <summary>
/// Invokes a static method in the object model.
/// </summary>
/// <param name="methodInvocationInfo">Method invocation details.</param>
public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo)
{
ArgumentNullException.ThrowIfNull(methodInvocationInfo);
foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo))
{
StartableJob childJob = this.DoCreateStaticMethodInvocationJob(sessionForJob, methodInvocationInfo);
if (childJob != null)
{
if (!this.AsJob.IsPresent)
{
_parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None);
}
else
{
_parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None);
}
}
}
}
/// <summary>
/// Performs initialization of cmdlet execution.
/// </summary>
public override void BeginProcessing()
{
if (this.AsJob.IsPresent)
{
MshCommandRuntime commandRuntime = (MshCommandRuntime)this.Cmdlet.CommandRuntime; // PSCmdlet.CommandRuntime is always MshCommandRuntime
string conflictingParameter = null;
if (commandRuntime.WhatIf.IsPresent)
{
conflictingParameter = "WhatIf";
}
else if (commandRuntime.Confirm.IsPresent)
{
conflictingParameter = "Confirm";
}
if (conflictingParameter != null)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.SessionBasedWrapper_ShouldProcessVsJobConflict,
conflictingParameter);
throw new InvalidOperationException(errorMessage);
}
}
_parentJob = new ThrottlingJob(
command: Job.GetCommandTextFromInvocationInfo(this.Cmdlet.MyInvocation),
jobName: this.GenerateParentJobName(),
jobTypeName: CIMJobType,
maximumConcurrentChildJobs: this.ThrottleLimit,
cmdletMode: !this.AsJob.IsPresent);
}
/// <summary>
/// Performs cleanup after cmdlet execution.
/// </summary>
public override void EndProcessing()
{
_parentJob.EndOfChildJobs();
if (this.AsJob.IsPresent)
{
this.Cmdlet.WriteObject(_parentJob);
this.Cmdlet.JobRepository.Add(_parentJob);
_parentJob = null; // this class doesn't own parentJob after it has been emitted to the outside world
}
else
{
_parentJob.ForwardAllResultsToCmdlet(this.Cmdlet);
_parentJob.Finished.WaitOne();
}
}
/// <summary>
/// Stops the parent job when called.
/// </summary>
public override void StopProcessing()
{
Job jobToStop = _parentJob;
jobToStop?.StopJob();
base.StopProcessing();
}
#endregion
}
internal interface ISessionBoundQueryBuilder<out TSession>
{
TSession GetTargetSession();
}
}
|