File size: 26,900 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 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Management.Automation.Internal
{
/// <summary>
/// A PipelineReader for an ObjectStream.
/// </summary>
/// <remarks>
/// This class is not safe for multi-threaded operations.
/// </remarks>
internal abstract class ObjectReaderBase<T> : PipelineReader<T>, IDisposable
{
/// <summary>
/// Construct with an existing ObjectStream.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <exception cref="ArgumentNullException">Thrown if the specified stream is null.</exception>
protected ObjectReaderBase([In, Out] ObjectStreamBase stream)
{
ArgumentNullException.ThrowIfNull(stream);
_stream = stream;
}
#region Events
/// <summary>
/// Event fired when objects are added to the underlying stream.
/// </summary>
public override event EventHandler DataReady
{
add
{
lock (_monitorObject)
{
bool firstRegistrant = (InternalDataReady == null);
InternalDataReady += value;
if (firstRegistrant)
{
_stream.DataReady += this.OnDataReady;
}
}
}
remove
{
lock (_monitorObject)
{
InternalDataReady -= value;
if (InternalDataReady == null)
{
_stream.DataReady -= this.OnDataReady;
}
}
}
}
public event EventHandler InternalDataReady = null;
#endregion Events
#region Public Properties
/// <summary>
/// Waitable handle for caller's to block until data is ready to read from the underlying stream.
/// </summary>
public override WaitHandle WaitHandle
{
get
{
return _stream.ReadHandle;
}
}
/// <summary>
/// Check if the stream is closed and contains no data.
/// </summary>
/// <value>True if the stream is closed and contains no data, otherwise; false.</value>
/// <remarks>
/// Attempting to read from the underlying stream if EndOfPipeline is true returns
/// zero objects.
/// </remarks>
public override bool EndOfPipeline
{
get
{
return _stream.EndOfPipeline;
}
}
/// <summary>
/// Check if the stream is open for further writes.
/// </summary>
/// <value>true if the underlying stream is open, otherwise; false.</value>
/// <remarks>
/// The underlying stream may be readable after it is closed if data remains in the
/// internal buffer. Check <see cref="EndOfPipeline"/> to determine if
/// the underlying stream is closed and contains no data.
/// </remarks>
public override bool IsOpen
{
get
{
return _stream.IsOpen;
}
}
/// <summary>
/// Returns the number of objects in the underlying stream.
/// </summary>
public override int Count
{
get
{
return _stream.Count;
}
}
/// <summary>
/// Get the capacity of the stream.
/// </summary>
/// <value>
/// The capacity of the stream.
/// </value>
/// <remarks>
/// The capacity is the number of objects that stream may contain at one time. Once this
/// limit is reached, attempts to write into the stream block until buffer space
/// becomes available.
/// </remarks>
public override int MaxCapacity
{
get
{
return _stream.MaxCapacity;
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Close the stream.
/// </summary>
/// <remarks>
/// Causes subsequent calls to IsOpen to return false and calls to
/// a write operation to throw an ObjectDisposedException.
/// All calls to Close() after the first call are silently ignored.
/// </remarks>
/// <exception cref="ObjectDisposedException">
/// The stream is already disposed
/// </exception>
public override void Close()
{
// 2003/09/02-JonN added call to close underlying stream
_stream.Close();
}
#endregion Public Methods
#region Private Methods
/// <summary>
/// Handle DataReady events from the underlying stream.
/// </summary>
/// <param name="sender">The stream raising the event.</param>
/// <param name="args">Standard event args.</param>
private void OnDataReady(object sender, EventArgs args)
{
// call any event handlers on this, replacing the
// ObjectStream sender with 'this' since receivers
// are expecting a PipelineReader<object>
InternalDataReady.SafeInvoke(this, args);
}
#endregion Private Methods
#region Private fields
/// <summary>
/// The underlying stream.
/// </summary>
/// <remarks>Can never be null</remarks>
protected ObjectStreamBase _stream;
/// <summary>
/// This object is used to acquire an exclusive lock
/// on event handler registration.
/// </summary>
/// <remarks>
/// Note that we lock _monitorObject rather than "this" so that
/// we are protected from outside code interfering in our
/// critical section. Thanks to Wintellect for the hint.
/// </remarks>
private readonly object _monitorObject = new object();
#endregion Private fields
#region IDisposable
/// <summary>
/// Public method for dispose.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all managed resources.</param>
protected abstract void Dispose(bool disposing);
#endregion IDisposable
}
/// <summary>
/// A PipelineReader reading objects from an ObjectStream.
/// </summary>
/// <remarks>
/// This class is not safe for multi-threaded operations.
/// </remarks>
internal class ObjectReader : ObjectReaderBase<object>
{
#region ctor
/// <summary>
/// Construct with an existing ObjectStream.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <exception cref="ArgumentNullException">Thrown if the specified stream is null.</exception>
public ObjectReader([In, Out] ObjectStream stream)
: base(stream)
{ }
#endregion ctor
/// <summary>
/// Read at most <paramref name="count"/> objects.
/// </summary>
/// <param name="count">The maximum number of objects to read.</param>
/// <returns>The objects read.</returns>
/// <remarks>
/// This method blocks if the number of objects in the stream is less than <paramref name="count"/>
/// and the stream is not closed.
/// </remarks>
public override Collection<object> Read(int count)
{
return _stream.Read(count);
}
/// <summary>
/// Read a single object from the stream.
/// </summary>
/// <returns>The next object in the stream.</returns>
/// <remarks>This method blocks if the stream is empty</remarks>
public override object Read()
{
return _stream.Read();
}
/// <summary>
/// Blocks until the pipeline closes and reads all objects.
/// </summary>
/// <returns>A collection of zero or more objects.</returns>
/// <remarks>
/// If the stream is empty, an empty collection is returned.
/// </remarks>
public override Collection<object> ReadToEnd()
{
return _stream.ReadToEnd();
}
/// <summary>
/// Reads all objects currently in the stream, but does not block.
/// </summary>
/// <returns>A collection of zero or more objects.</returns>
/// <remarks>
/// This method performs a read of all objects currently in the
/// stream. The method will block until exclusive access to the
/// stream is acquired. If there are no objects in the stream,
/// an empty collection is returned.
/// </remarks>
public override Collection<object> NonBlockingRead()
{
return _stream.NonBlockingRead(Int32.MaxValue);
}
/// <summary>
/// Reads objects currently in the stream, but does not block.
/// </summary>
/// <returns>A collection of zero or more objects.</returns>
/// <remarks>
/// This method performs a read of objects currently in the
/// stream. The method will block until exclusive access to the
/// stream is acquired. If there are no objects in the stream,
/// an empty collection is returned.
/// </remarks>
/// <param name="maxRequested">
/// Return no more than maxRequested objects.
/// </param>
public override Collection<object> NonBlockingRead(int maxRequested)
{
return _stream.NonBlockingRead(maxRequested);
}
/// <summary>
/// Peek the next object.
/// </summary>
/// <returns>The next object in the stream or ObjectStream.EmptyObject if the stream is empty.</returns>
public override object Peek()
{
return _stream.Peek();
}
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all managed resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_stream.Close();
}
}
}
/// <summary>
/// A PipelineReader reading PSObjects from an ObjectStream.
/// </summary>
/// <remarks>
/// This class is not safe for multi-threaded operations.
/// </remarks>
internal class PSObjectReader : ObjectReaderBase<PSObject>
{
#region ctor
/// <summary>
/// Construct with an existing ObjectStream.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <exception cref="ArgumentNullException">Thrown if the specified stream is null.</exception>
public PSObjectReader([In, Out] ObjectStream stream)
: base(stream)
{ }
#endregion ctor
/// <summary>
/// Read at most <paramref name="count"/> objects.
/// </summary>
/// <param name="count">The maximum number of objects to read.</param>
/// <returns>The objects read.</returns>
/// <remarks>
/// This method blocks if the number of objects in the stream is less than <paramref name="count"/>
/// and the stream is not closed.
/// </remarks>
public override Collection<PSObject> Read(int count)
{
return MakePSObjectCollection(_stream.Read(count));
}
/// <summary>
/// Read a single PSObject from the stream.
/// </summary>
/// <returns>The next PSObject in the stream.</returns>
/// <remarks>This method blocks if the stream is empty</remarks>
public override PSObject Read()
{
return MakePSObject(_stream.Read());
}
/// <summary>
/// Blocks until the pipeline closes and reads all objects.
/// </summary>
/// <returns>A collection of zero or more objects.</returns>
/// <remarks>
/// If the stream is empty, an empty collection is returned.
/// </remarks>
public override Collection<PSObject> ReadToEnd()
{
return MakePSObjectCollection(_stream.ReadToEnd());
}
/// <summary>
/// Reads all objects currently in the stream, but does not block.
/// </summary>
/// <returns>A collection of zero or more objects.</returns>
/// <remarks>
/// This method performs a read of all objects currently in the
/// stream. The method will block until exclusive access to the
/// stream is acquired. If there are no objects in the stream,
/// an empty collection is returned.
/// </remarks>
public override Collection<PSObject> NonBlockingRead()
{
return MakePSObjectCollection(_stream.NonBlockingRead(Int32.MaxValue));
}
/// <summary>
/// Reads objects currently in the stream, but does not block.
/// </summary>
/// <returns>A collection of zero or more objects.</returns>
/// <remarks>
/// This method performs a read of objects currently in the
/// stream. The method will block until exclusive access to the
/// stream is acquired. If there are no objects in the stream,
/// an empty collection is returned.
/// </remarks>
/// <param name="maxRequested">
/// Return no more than maxRequested objects.
/// </param>
public override Collection<PSObject> NonBlockingRead(int maxRequested)
{
return MakePSObjectCollection(_stream.NonBlockingRead(maxRequested));
}
/// <summary>
/// Peek the next PSObject.
/// </summary>
/// <returns>The next PSObject in the stream or ObjectStream.EmptyObject if the stream is empty.</returns>
public override PSObject Peek()
{
return MakePSObject(_stream.Peek());
}
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all managed resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_stream.Close();
}
}
#region Private
private static PSObject MakePSObject(object o)
{
if (o == null)
return null;
return PSObject.AsPSObject(o);
}
// It might ultimately be more efficient to
// make ObjectStream generic and convert the objects to PSObject
// before inserting them into the initial Collection, so that we
// don't have to convert the collection later.
private static Collection<PSObject> MakePSObjectCollection(
Collection<object> coll)
{
if (coll == null)
return null;
Collection<PSObject> retval = new Collection<PSObject>();
foreach (object o in coll)
{
retval.Add(MakePSObject(o));
}
return retval;
}
#endregion Private
}
/// <summary>
/// A ObjectReader for a PSDataCollection ObjectStream.
/// </summary>
/// <remarks>
/// PSDataCollection is introduced after 1.0. PSDataCollection is
/// used to store data which can be used with different
/// commands concurrently.
/// Only Read() operation is supported currently.
/// </remarks>
internal class PSDataCollectionReader<T, TResult>
: ObjectReaderBase<TResult>
{
#region Private Data
private readonly PSDataCollectionEnumerator<T> _enumerator;
#endregion
#region ctor
/// <summary>
/// Construct with an existing ObjectStream.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <exception cref="ArgumentNullException">Thrown if the specified stream is null.</exception>
public PSDataCollectionReader(PSDataCollectionStream<T> stream)
: base(stream)
{
System.Management.Automation.Diagnostics.Assert(stream.ObjectStore != null,
"Stream should have a valid data store");
_enumerator = (PSDataCollectionEnumerator<T>)stream.ObjectStore.GetEnumerator();
}
#endregion ctor
/// <summary>
/// This method is not supported.
/// </summary>
/// <param name="count">The maximum number of objects to read.</param>
/// <returns>The objects read.</returns>
public override Collection<TResult> Read(int count)
{
throw new NotSupportedException();
}
/// <summary>
/// Read a single object from the stream.
/// </summary>
/// <returns>
/// The next object in the buffer or AutomationNull if buffer is closed
/// and data is not available.
/// </returns>
/// <remarks>
/// This method blocks if the buffer is empty.
/// </remarks>
public override TResult Read()
{
object result = AutomationNull.Value;
if (_enumerator.MoveNext())
{
result = _enumerator.Current;
}
return ConvertToReturnType(result);
}
/// <summary>
/// This method is not supported.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public override Collection<TResult> ReadToEnd()
{
throw new NotSupportedException();
}
/// <summary>
/// This method is not supported.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public override Collection<TResult> NonBlockingRead()
{
return NonBlockingRead(Int32.MaxValue);
}
/// <summary>
/// This method is not supported.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
/// <param name="maxRequested">
/// Return no more than maxRequested objects.
/// </param>
public override Collection<TResult> NonBlockingRead(int maxRequested)
{
if (maxRequested < 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxRequested), maxRequested);
}
if (maxRequested == 0)
{
return new Collection<TResult>();
}
Collection<TResult> result = new Collection<TResult>();
int readCount = maxRequested;
while (readCount > 0)
{
if (_enumerator.MoveNext(false))
{
result.Add(ConvertToReturnType(_enumerator.Current));
continue;
}
break;
}
return result;
}
/// <summary>
/// This method is not supported.
/// </summary>
/// <returns></returns>
public override TResult Peek()
{
throw new NotSupportedException();
}
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all managed resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_stream.Close();
}
}
private static TResult ConvertToReturnType(object inputObject)
{
Type resultType = typeof(TResult);
if (typeof(PSObject) == resultType || typeof(object) == resultType)
{
TResult result;
LanguagePrimitives.TryConvertTo(inputObject, out result);
return result;
}
System.Management.Automation.Diagnostics.Assert(false,
"ReturnType should be either object or PSObject only");
throw PSTraceSource.NewNotSupportedException();
}
}
/// <summary>
/// A ObjectReader for a PSDataCollection ObjectStream.
/// </summary>
/// <remarks>
/// PSDataCollection is introduced after 1.0. PSDataCollection is
/// used to store data which can be used with different
/// commands concurrently.
/// Only Read() operation is supported currently.
/// </remarks>
internal class PSDataCollectionPipelineReader<T, TReturn>
: ObjectReaderBase<TReturn>
{
#region Private Data
private readonly PSDataCollection<T> _datastore;
#endregion Private Data
#region ctor
/// <summary>
/// Construct with an existing ObjectStream.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <param name="computerName"></param>
/// <param name="runspaceId"></param>
internal PSDataCollectionPipelineReader(PSDataCollectionStream<T> stream,
string computerName, Guid runspaceId)
: base(stream)
{
System.Management.Automation.Diagnostics.Assert(stream.ObjectStore != null,
"Stream should have a valid data store");
_datastore = stream.ObjectStore;
ComputerName = computerName;
RunspaceId = runspaceId;
}
#endregion ctor
/// <summary>
/// Computer name passed in by the pipeline which
/// created this reader.
/// </summary>
internal string ComputerName { get; }
/// <summary>
/// Runspace Id passed in by the pipeline which
/// created this reader.
/// </summary>
internal Guid RunspaceId { get; }
/// <summary>
/// This method is not supported.
/// </summary>
/// <param name="count">The maximum number of objects to read.</param>
/// <returns>The objects read.</returns>
public override Collection<TReturn> Read(int count)
{
throw new NotSupportedException();
}
/// <summary>
/// Read a single object from the stream.
/// </summary>
/// <returns>
/// The next object in the buffer or AutomationNull if buffer is closed
/// and data is not available.
/// </returns>
/// <remarks>
/// This method blocks if the buffer is empty.
/// </remarks>
public override TReturn Read()
{
object result = AutomationNull.Value;
if (_datastore.Count > 0)
{
Collection<T> resultCollection = _datastore.ReadAndRemove(1);
// ReadAndRemove returns a Collection<T> type but we
// just want the single object contained in the collection.
if (resultCollection.Count == 1)
{
result = resultCollection[0];
}
}
return ConvertToReturnType(result);
}
/// <summary>
/// This method is not supported.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public override Collection<TReturn> ReadToEnd()
{
throw new NotSupportedException();
}
/// <summary>
/// This method is not supported.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public override Collection<TReturn> NonBlockingRead()
{
return NonBlockingRead(Int32.MaxValue);
}
/// <summary>
/// This method is not supported.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
/// <param name="maxRequested">
/// Return no more than maxRequested objects.
/// </param>
public override Collection<TReturn> NonBlockingRead(int maxRequested)
{
if (maxRequested < 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxRequested), maxRequested);
}
if (maxRequested == 0)
{
return new Collection<TReturn>();
}
Collection<TReturn> results = new Collection<TReturn>();
int readCount = maxRequested;
while (readCount > 0)
{
if (_datastore.Count > 0)
{
results.Add(ConvertToReturnType((_datastore.ReadAndRemove(1))[0]));
readCount--;
continue;
}
break;
}
return results;
}
/// <summary>
/// This method is not supported.
/// </summary>
/// <returns></returns>
public override TReturn Peek()
{
throw new NotSupportedException();
}
/// <summary>
/// Converts to the return type based on language primitives.
/// </summary>
/// <param name="inputObject">Input object to convert.</param>
/// <returns>Input object converted to the specified return type.</returns>
private static TReturn ConvertToReturnType(object inputObject)
{
Type resultType = typeof(TReturn);
if (typeof(PSObject) == resultType || typeof(object) == resultType)
{
TReturn result;
LanguagePrimitives.TryConvertTo(inputObject, out result);
return result;
}
System.Management.Automation.Diagnostics.Assert(false,
"ReturnType should be either object or PSObject only");
throw PSTraceSource.NewNotSupportedException();
}
#region IDisposable
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all managed resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_datastore.Dispose();
}
}
#endregion IDisposable
}
}
|