File size: 62,035 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 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Internal;
using System.Management.Automation.Security;
using System.Management.Automation.Tracing;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
using PSHost = System.Management.Automation.Host.PSHost;
namespace System.Management.Automation.Runspaces.Internal
{
/// <summary>
/// Class which supports pooling local powerShell runspaces.
/// </summary>
internal class RunspacePoolInternal : IDisposable
{
#region Private data
protected int maxPoolSz;
protected int minPoolSz;
// we need total active runspaces to avoid lock() statements everywhere
protected int totalRunspaces;
protected List<Runspace> runspaceList = new List<Runspace>(); // info of all the runspaces in the pool.
protected Stack<Runspace> pool; // stack of runspaces that are available.
protected Queue<GetRunspaceAsyncResult> runspaceRequestQueue; // request queue.
// let requesters request on the runspaceRequestQueue..internally
// pool services on this queue.
protected Queue<GetRunspaceAsyncResult> ultimateRequestQueue;
protected RunspacePoolStateInfo stateInfo;
protected InitialSessionState _initialSessionState;
protected PSHost host;
protected Guid instanceId;
private bool _isDisposed;
protected bool isServicingRequests;
protected object syncObject = new object();
private static readonly TimeSpan s_defaultCleanupPeriod = new TimeSpan(0, 15, 0); // 15 minutes.
private TimeSpan _cleanupInterval;
private readonly Timer _cleanupTimer;
#endregion
#region Constructor
/// <summary>
/// Constructor which creates a RunspacePool using the
/// supplied <paramref name="configuration"/>, <paramref name="minRunspaces"/>
/// and <paramref name="maxRunspaces"/>
/// </summary>
/// <param name="maxRunspaces">
/// The maximum number of Runspaces that can exist in this pool.
/// Should be greater than or equal to 1.
/// </param>
/// <param name="minRunspaces">
/// The minimum number of Runspaces that can exist in this pool.
/// Should be greater than or equal to 1.
/// </param>
/// <param name="host">
/// The explicit PSHost implementation.
/// </param>
/// <exception cref="ArgumentNullException">
/// Host is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Maximum runspaces is less than 1.
/// Minimum runspaces is less than 1.
/// </exception>
public RunspacePoolInternal(int minRunspaces,
int maxRunspaces,
PSHost host)
: this(minRunspaces, maxRunspaces)
{
if (host == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(host));
}
this.host = host;
pool = new Stack<Runspace>();
runspaceRequestQueue = new Queue<GetRunspaceAsyncResult>();
ultimateRequestQueue = new Queue<GetRunspaceAsyncResult>();
_initialSessionState = InitialSessionState.CreateDefault();
}
/// <summary>
/// Constructor which creates a RunspacePool using the
/// supplied <paramref name="configuration"/>, <paramref name="minRunspaces"/>
/// and <paramref name="maxRunspaces"/>
/// </summary>
/// <param name="initialSessionState">
/// InitialSessionState to use when creating a new Runspace.
/// </param>
/// <param name="maxRunspaces">
/// The maximum number of Runspaces that can exist in this pool.
/// Should be greater than or equal to 1.
/// </param>
/// <param name="minRunspaces">
/// The minimum number of Runspaces that can exist in this pool.
/// Should be greater than or equal to 1.
/// </param>
/// <param name="host">
/// The explicit PSHost implementation.
/// </param>
/// <exception cref="ArgumentNullException">
/// initialSessionState is null.
/// Host is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Maximum runspaces is less than 1.
/// Minimum runspaces is less than 1.
/// </exception>
public RunspacePoolInternal(int minRunspaces,
int maxRunspaces,
InitialSessionState initialSessionState,
PSHost host)
: this(minRunspaces, maxRunspaces)
{
if (initialSessionState == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState));
}
if (host == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(host));
}
_initialSessionState = initialSessionState.Clone();
this.host = host;
ThreadOptions = initialSessionState.ThreadOptions;
this.ApartmentState = initialSessionState.ApartmentState;
pool = new Stack<Runspace>();
runspaceRequestQueue = new Queue<GetRunspaceAsyncResult>();
ultimateRequestQueue = new Queue<GetRunspaceAsyncResult>();
}
/// <summary>
/// Constructor for doing common initialization between
/// this class and its derivatives.
/// </summary>
/// <param name="maxRunspaces">
/// The maximum number of Runspaces that can exist in this pool.
/// Should be greater than or equal to 1.
/// </param>
/// <param name="minRunspaces">
/// The minimum number of Runspaces that can exist in this pool.
/// Should be greater than or equal to 1.
/// </param>
protected RunspacePoolInternal(int minRunspaces, int maxRunspaces)
{
if (maxRunspaces < 1)
{
throw PSTraceSource.NewArgumentException(nameof(maxRunspaces), RunspacePoolStrings.MaxPoolLessThan1);
}
if (minRunspaces < 1)
{
throw PSTraceSource.NewArgumentException(nameof(minRunspaces), RunspacePoolStrings.MinPoolLessThan1);
}
if (minRunspaces > maxRunspaces)
{
throw PSTraceSource.NewArgumentException(nameof(minRunspaces), RunspacePoolStrings.MinPoolGreaterThanMaxPool);
}
maxPoolSz = maxRunspaces;
minPoolSz = minRunspaces;
stateInfo = new RunspacePoolStateInfo(RunspacePoolState.BeforeOpen, null);
instanceId = Guid.NewGuid();
PSEtwLog.SetActivityIdForCurrentThread(instanceId);
_cleanupInterval = s_defaultCleanupPeriod;
_cleanupTimer = new Timer(new TimerCallback(CleanupCallback), null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Default constructor.
/// </summary>
internal RunspacePoolInternal() { }
#endregion
#region Public Properties
/// <summary>
/// Get unique id for this instance of runspace pool. It is primarily used
/// for logging purposes.
/// </summary>
public Guid InstanceId
{
get
{
return instanceId;
}
}
/// <summary>
/// Gets a boolean which describes if the runspace pool is disposed.
/// </summary>
public bool IsDisposed
{
get
{
return _isDisposed;
}
}
/// <summary>
/// Gets State of the current runspace pool.
/// </summary>
public RunspacePoolStateInfo RunspacePoolStateInfo
{
get
{
return stateInfo;
}
}
/// <summary>
/// Private data to be used by applications built on top of PowerShell.
///
/// Local runspace pool is created with application private data set to an empty <see cref="PSPrimitiveDictionary"/>.
/// </summary>
internal virtual PSPrimitiveDictionary GetApplicationPrivateData()
{
if (_applicationPrivateData == null)
{
lock (this.syncObject)
{
_applicationPrivateData ??= new PSPrimitiveDictionary();
}
}
return _applicationPrivateData;
}
internal virtual void PropagateApplicationPrivateData(Runspace runspace)
{
runspace.SetApplicationPrivateData(this.GetApplicationPrivateData());
}
private PSPrimitiveDictionary _applicationPrivateData;
/// <summary>
/// Gets the InitialSessionState object that this pool uses
/// to create the runspaces.
/// </summary>
public InitialSessionState InitialSessionState
{
get
{
return _initialSessionState;
}
}
/// <summary>
/// The connection associated with this runspace pool.
/// </summary>
public virtual RunspaceConnectionInfo ConnectionInfo
{
get
{
return null;
}
}
/// <summary>
/// Specifies how often unused runspaces are disposed.
/// </summary>
public TimeSpan CleanupInterval
{
get
{
return _cleanupInterval;
}
set
{
lock (this.syncObject)
{
_cleanupInterval = value;
}
}
}
/// <summary>
/// Returns runspace pool availability.
/// </summary>
public virtual RunspacePoolAvailability RunspacePoolAvailability
{
get
{
return (stateInfo.State == RunspacePoolState.Opened) ?
RunspacePoolAvailability.Available :
RunspacePoolAvailability.None;
}
}
#endregion
#region events
/// <summary>
/// Event raised when RunspacePoolState changes.
/// </summary>
public event EventHandler<RunspacePoolStateChangedEventArgs> StateChanged;
/// <summary>
/// Event raised when one of the runspaces in the pool forwards an event to this instance.
/// </summary>
public event EventHandler<PSEventArgs> ForwardEvent;
/// <summary>
/// Event raised when a new Runspace is created by the pool.
/// </summary>
internal event EventHandler<RunspaceCreatedEventArgs> RunspaceCreated;
#endregion events
#region Disconnect-Connect Methods
/// <summary>
/// Synchronously disconnect runspace pool.
/// </summary>
public virtual void Disconnect()
{
throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported);
}
/// <summary>
/// Asynchronously disconnect runspace pool.
/// </summary>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
public virtual IAsyncResult BeginDisconnect(AsyncCallback callback, object state)
{
throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported);
}
/// <summary>
/// Wait for BeginDisconnect to complete.
/// </summary>
/// <param name="asyncResult"></param>
public virtual void EndDisconnect(IAsyncResult asyncResult)
{
throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported);
}
/// <summary>
/// Synchronously connect runspace pool.
/// </summary>
public virtual void Connect()
{
throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported);
}
/// <summary>
/// Asynchronously connect runspace pool.
/// </summary>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
public virtual IAsyncResult BeginConnect(AsyncCallback callback, object state)
{
throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported);
}
/// <summary>
/// Wait for BeginConnect to complete.
/// </summary>
/// <param name="asyncResult"></param>
public virtual void EndConnect(IAsyncResult asyncResult)
{
throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported);
}
/// <summary>
/// Creates an array of PowerShell objects that are in the Disconnected state for
/// all currently disconnected running commands associated with this runspace pool.
/// </summary>
/// <returns></returns>
public virtual Collection<PowerShell> CreateDisconnectedPowerShells(RunspacePool runspacePool)
{
throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceDisconnectConnectNotSupported);
}
/// <summary>
/// Returns RunspacePool capabilities.
/// </summary>
/// <returns>RunspacePoolCapability.</returns>
public virtual RunspacePoolCapability GetCapabilities()
{
return RunspacePoolCapability.Default;
}
#endregion
#region Public Methods
/// <summary>
/// Resets the runspace state on a runspace pool with a single
/// runspace.
/// This is currently supported *only* for remote runspaces.
/// </summary>
/// <returns>True if successful.</returns>
internal virtual bool ResetRunspaceState()
{
throw new PSNotSupportedException();
}
/// <summary>
/// Sets the maximum number of Runspaces that can be active concurrently
/// in the pool. All requests above that number remain queued until
/// runspaces become available.
/// </summary>
/// <param name="maxRunspaces">
/// The maximum number of runspaces in the pool.
/// </param>
/// <returns>
/// true if the change is successful; otherwise, false.
/// </returns>
/// <remarks>
/// You cannot set the number of runspaces to a number smaller than
/// the minimum runspaces.
/// </remarks>
internal virtual bool SetMaxRunspaces(int maxRunspaces)
{
bool isSizeIncreased = false;
lock (pool)
{
if (maxRunspaces < this.minPoolSz)
{
return false;
}
if (maxRunspaces > this.maxPoolSz)
{
isSizeIncreased = true;
}
else
{
// since maxrunspaces limit is decreased
// destroy unwanted runspaces from the top
// of the pool.
while (pool.Count > maxRunspaces)
{
Runspace rsToDestroy = pool.Pop();
DestroyRunspace(rsToDestroy);
}
}
maxPoolSz = maxRunspaces;
}
// pool size is incremented.. check if we can release
// some requests.
if (isSizeIncreased)
{
EnqueueCheckAndStartRequestServicingThread(null, false);
}
return true;
}
/// <summary>
/// Retrieves the maximum number of runspaces the pool maintains.
/// </summary>
/// <returns>
/// The maximum number of runspaces in the pool
/// </returns>
public int GetMaxRunspaces()
{
return maxPoolSz;
}
/// <summary>
/// Sets the minimum number of Runspaces that the pool maintains
/// in anticipation of new requests.
/// </summary>
/// <param name="minRunspaces">
/// The minimum number of runspaces in the pool.
/// </param>
/// <returns>
/// true if the change is successful; otherwise, false.
/// </returns>
/// <remarks>
/// You cannot set the number of idle runspaces to a number smaller than
/// 1 or greater than maximum number of active runspaces.
/// </remarks>
internal virtual bool SetMinRunspaces(int minRunspaces)
{
lock (pool)
{
if ((minRunspaces < 1) || (minRunspaces > this.maxPoolSz))
{
return false;
}
minPoolSz = minRunspaces;
}
return true;
}
/// <summary>
/// Retrieves the minimum number of runspaces the pool maintains.
/// </summary>
/// <returns>
/// The minimum number of runspaces in the pool
/// </returns>
public int GetMinRunspaces()
{
return minPoolSz;
}
/// <summary>
/// Retrieves the number of runspaces available at the time of calling
/// this method.
/// </summary>
/// <exception cref="ArgumentException">
/// If the RunspacePool failed or has been closed
/// </exception>
/// <returns>
/// The number of available runspace in the pool.
/// </returns>
internal virtual int GetAvailableRunspaces()
{
// Dont allow state changes while we get the count
lock (syncObject)
{
if (stateInfo.State == RunspacePoolState.Opened)
{
// Win8: 169492 RunspacePool can report that there are negative runspaces available.
// totalRunspaces represents all the runspaces that were ever created by ths RunspacePool
// pool.Count represents the runspaces that are currently available
// maxPoolSz represents the total capacity w.r.t runspaces for this RunspacePool
// Once the RunspacePool allocates a runspace to a consumer, RunspacePool cannot reclaim the
// runspace until the consumer released the runspace back to the pool. A SetMaxRunspaces()
// call can arrive before the runspace is released..It is bad to make SetMaxRunspaces()
// wait for the consumers to release runspaces, so we let SetMaxRunspaces() go by changing
// maxPoolSz. Because of this there may be cases where maxPoolSz - totalRunspaces will become
// less than 0.
int unUsedCapacity = (maxPoolSz - totalRunspaces) < 0 ? 0 : (maxPoolSz - totalRunspaces);
return (pool.Count + unUsedCapacity);
}
else if (stateInfo.State == RunspacePoolState.Disconnected)
{
throw new InvalidOperationException(RunspacePoolStrings.CannotWhileDisconnected);
}
else if (stateInfo.State != RunspacePoolState.BeforeOpen && stateInfo.State != RunspacePoolState.Opening)
{
throw new InvalidOperationException(HostInterfaceExceptionsStrings.RunspacePoolNotOpened);
}
else
{
return maxPoolSz;
}
}
}
/// <summary>
/// Opens the runspacepool synchronously. RunspacePool must
/// be opened before it can be used.
/// </summary>
/// <exception cref="InvalidRunspacePoolStateException">
/// RunspacePoolState is not BeforeOpen
/// </exception>
public virtual void Open()
{
CoreOpen(false, null, null);
}
/// <summary>
/// Opens the RunspacePool asynchronously. RunspacePool must
/// be opened before it can be used.
/// To get the exceptions that might have occurred, call
/// EndOpen.
/// </summary>
/// <param name="callback">
/// A AsyncCallback to call once the BeginOpen completes.
/// </param>
/// <param name="state">
/// A user supplied state to call the <paramref name="callback"/>
/// with.
/// </param>
/// <returns>
/// An AsyncResult object to monitor the state of the async
/// operation.
/// </returns>
public IAsyncResult BeginOpen(AsyncCallback callback, object state)
{
return CoreOpen(true, callback, state);
}
/// <summary>
/// Waits for the pending asynchronous BeginOpen to complete.
/// </summary>
/// <exception cref="ArgumentNullException">
/// asyncResult is a null reference.
/// </exception>
/// <exception cref="ArgumentException">
/// asyncResult object was not created by calling BeginOpen
/// on this runspacepool instance.
/// </exception>
/// <exception cref="InvalidRunspacePoolStateException">
/// RunspacePoolState is not BeforeOpen.
/// </exception>
/// <remarks>
/// TODO: Behavior if EndOpen is called multiple times.
/// </remarks>
public void EndOpen(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(asyncResult));
}
RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult;
if ((rsAsyncResult == null) ||
(rsAsyncResult.OwnerId != instanceId) ||
(!rsAsyncResult.IsAssociatedWithAsyncOpen))
{
throw PSTraceSource.NewArgumentException(nameof(asyncResult),
RunspacePoolStrings.AsyncResultNotOwned,
"IAsyncResult",
"BeginOpen");
}
rsAsyncResult.EndInvoke();
}
/// <summary>
/// Closes the RunspacePool and cleans all the internal
/// resources. This will close all the runspaces in the
/// runspacepool and release all the async operations
/// waiting for a runspace. If the pool is already closed
/// or broken or closing this will just return.
/// </summary>
public virtual void Close()
{
CoreClose(false, null, null);
}
/// <summary>
/// Closes the RunspacePool asynchronously and cleans all the internal
/// resources. This will close all the runspaces in the
/// runspacepool and release all the async operations
/// waiting for a runspace. If the pool is already closed
/// or broken or closing this will just return.
/// </summary>
/// <param name="callback">
/// A AsyncCallback to call once the BeginClose completes.
/// </param>
/// <param name="state">
/// A user supplied state to call the <paramref name="callback"/>
/// with.
/// </param>
/// <returns>
/// An AsyncResult object to monitor the state of the async
/// operation.
/// </returns>
public virtual IAsyncResult BeginClose(AsyncCallback callback, object state)
{
return CoreClose(true, callback, state);
}
/// <summary>
/// Waits for the pending asynchronous BeginClose to complete.
/// </summary>
/// <exception cref="ArgumentException">
/// asyncResult object was not created by calling BeginClose
/// on this runspacepool instance.
/// </exception>
/// <remarks>
/// TODO: Behavior if EndClose is called multiple times.
/// </remarks>
public virtual void EndClose(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(asyncResult));
}
RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult;
if ((rsAsyncResult == null) ||
(rsAsyncResult.OwnerId != instanceId) ||
(rsAsyncResult.IsAssociatedWithAsyncOpen))
{
throw PSTraceSource.NewArgumentException(nameof(asyncResult),
RunspacePoolStrings.AsyncResultNotOwned,
"IAsyncResult",
"BeginClose");
}
rsAsyncResult.EndInvoke();
}
/// <summary>
/// Gets a Runspace from the pool. If no free runspace is available
/// and if max pool size is not reached, a new runspace is created.
/// Otherwise this will block a runspace is released and available.
/// </summary>
/// <returns>
/// An opened Runspace.
/// </returns>
/// <exception cref="InvalidRunspacePoolStateException">
/// Cannot perform operation because RunspacePool is
/// not in the opened state.
/// </exception>
public Runspace GetRunspace()
{
AssertPoolIsOpen();
// Get the runspace asynchronously.
GetRunspaceAsyncResult asyncResult = (GetRunspaceAsyncResult)BeginGetRunspace(null, null);
// Wait for async operation to complete.
asyncResult.AsyncWaitHandle.WaitOne();
// throw the exception that occurred while
// processing the async operation
if (asyncResult.Exception != null)
{
throw asyncResult.Exception;
}
return asyncResult.Runspace;
}
/// <summary>
/// Releases a Runspace to the pool. If pool is closed, this
/// will be a no-op.
/// </summary>
/// <param name="runspace">
/// Runspace to release to the pool.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="runspace"/> is null.
/// </exception>
/// <exception cref="InvalidRunspacePoolStateException">
/// Runspool is not in Opened state.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Cannot release the runspace to this pool as the runspace
/// doesn't belong to this pool.
/// </exception>
public void ReleaseRunspace(Runspace runspace)
{
if (runspace == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(runspace));
}
AssertPoolIsOpen();
bool isRunspaceReleased = false;
bool destroyRunspace = false;
// check if the runspace is owned by the pool
lock (runspaceList)
{
if (!runspaceList.Contains(runspace))
{
throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceNotBelongsToPool);
}
}
// Release this runspace only if it is in valid state and is
// owned by this pool.
if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
{
lock (pool)
{
if (pool.Count < maxPoolSz)
{
isRunspaceReleased = true;
pool.Push(runspace);
}
else
{
// this runspace is not going to be pooled as maxPoolSz is reduced.
// so release the runspace and destroy it.
isRunspaceReleased = true;
destroyRunspace = true;
}
}
}
else
{
destroyRunspace = true;
isRunspaceReleased = true;
}
if (destroyRunspace)
{
// Destroying a runspace might be costly.
// so doing this outside of the lock.
DestroyRunspace(runspace);
}
// it is important to release lock on Pool so that
// other threads can service requests.
if (isRunspaceReleased)
{
// service any pending runspace requests.
EnqueueCheckAndStartRequestServicingThread(null, false);
}
}
/// <summary>
/// Release all resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose off the current runspace pool.
/// </summary>
/// <param name="disposing">
/// true to release all the internal resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
Close();
_cleanupTimer.Dispose();
_initialSessionState = null;
host = null;
}
_isDisposed = true;
}
}
#endregion
#region Internal Methods
/// <summary>
/// The value of this property is propagated to all the Runspaces in this pool;
/// it determines whether a new thread is create when a pipeline is executed.
/// </summary>
/// <remarks>
/// Any updates to the value of this property must be done before the RunspacePool is opened
/// </remarks>
internal PSThreadOptions ThreadOptions { get; set; } = PSThreadOptions.Default;
/// <summary>
/// The value of this property is propagated to all the Runspaces in this pool.
/// </summary>
/// <remarks>
/// Any updates to the value of this property must be done before the RunspacePool is opened
/// </remarks>
internal ApartmentState ApartmentState { get; set; } = Runspace.DefaultApartmentState;
/// <summary>
/// Gets Runspace asynchronously from the runspace pool. The caller
/// will get notified with the runspace using <paramref name="callback"/>
/// </summary>
/// <param name="callback">
/// A AsyncCallback to call once the runspace is available.
/// </param>
/// <param name="state">
/// A user supplied state to call the <paramref name="callback"/>
/// with.
/// </param>
/// <returns>
/// An IAsyncResult object to track the status of the Async operation.
/// </returns>
internal IAsyncResult BeginGetRunspace(
AsyncCallback callback, object state)
{
AssertPoolIsOpen();
GetRunspaceAsyncResult asyncResult = new GetRunspaceAsyncResult(this.InstanceId,
callback, state);
// Enqueue and start servicing thread in one go..saving multiple locks.
EnqueueCheckAndStartRequestServicingThread(asyncResult, true);
return asyncResult;
}
/// <summary>
/// Cancels the pending asynchronous BeginGetRunspace operation.
/// </summary>
/// <param name="asyncResult">
/// </param>
internal void CancelGetRunspace(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(asyncResult));
}
GetRunspaceAsyncResult grsAsyncResult =
asyncResult as GetRunspaceAsyncResult;
if ((grsAsyncResult == null) || (grsAsyncResult.OwnerId != instanceId))
{
throw PSTraceSource.NewArgumentException(nameof(asyncResult),
RunspacePoolStrings.AsyncResultNotOwned,
"IAsyncResult",
"BeginGetRunspace");
}
grsAsyncResult.IsActive = false;
}
/// <summary>
/// Waits for the pending asynchronous BeginGetRunspace to complete.
/// </summary>
/// <param name="asyncResult">
/// </param>
/// <exception cref="ArgumentNullException">
/// asyncResult is a null reference.
/// </exception>
/// <exception cref="ArgumentException">
/// asyncResult object was not created by calling BeginGetRunspace
/// on this runspacepool instance.
/// </exception>
/// <exception cref="InvalidRunspacePoolStateException">
/// RunspacePoolState is not BeforeOpen.
/// </exception>
/// <remarks>
/// TODO: Behavior if EndGetRunspace is called multiple times.
/// </remarks>
internal Runspace EndGetRunspace(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(asyncResult));
}
GetRunspaceAsyncResult grsAsyncResult =
asyncResult as GetRunspaceAsyncResult;
if ((grsAsyncResult == null) || (grsAsyncResult.OwnerId != instanceId))
{
throw PSTraceSource.NewArgumentException(nameof(asyncResult),
RunspacePoolStrings.AsyncResultNotOwned,
"IAsyncResult",
"BeginGetRunspace");
}
grsAsyncResult.EndInvoke();
return grsAsyncResult.Runspace;
}
/// <summary>
/// Opens the runspacepool synchronously / asynchronously.
/// Runspace pool must be opened before it can be used.
/// </summary>
/// <param name="isAsync">
/// true to open asynchronously
/// </param>
/// <param name="callback">
/// A AsyncCallback to call once the BeginOpen completes.
/// </param>
/// <param name="asyncState">
/// A user supplied state to call the <paramref name="callback"/>
/// with.
/// </param>
/// <returns>
/// asyncResult object to monitor status of the async
/// open operation. This is returned only if <paramref name="isAsync"/>
/// is true.
/// </returns>
/// <exception cref="InvalidRunspacePoolStateException">
/// Cannot open RunspacePool because RunspacePool is not in
/// the BeforeOpen state.
/// </exception>
/// <exception cref="OutOfMemoryException">
/// There is not enough memory available to start this asynchronously.
/// </exception>
protected virtual IAsyncResult CoreOpen(bool isAsync, AsyncCallback callback,
object asyncState)
{
lock (syncObject)
{
AssertIfStateIsBeforeOpen();
stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Opening, null);
}
// only one thread will reach here, so no
// need to lock.
RaiseStateChangeEvent(stateInfo);
if (isAsync)
{
AsyncResult asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, true);
// Open pool in another thread
ThreadPool.QueueUserWorkItem(new WaitCallback(OpenThreadProc), asyncResult);
return asyncResult;
}
// open the runspace synchronously
OpenHelper();
return null;
}
/// <summary>
/// Creates a Runspace + opens it synchronously and
/// pushes it into the stack.
/// </summary>
/// <remarks>
/// Caller to make sure this is thread safe.
/// </remarks>
protected void OpenHelper()
{
try
{
PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId);
// Create a Runspace and store it in the pool
// for future use. This will validate whether
// a runspace can be created + opened successfully
Runspace rs = CreateRunspace();
pool.Push(rs);
}
catch (Exception exception)
{
SetStateToBroken(exception);
// rethrow the exception
throw;
}
bool shouldRaiseEvents = false;
// RunspacePool might be closed while we are still opening
// we should not change state from closed to opened..
lock (syncObject)
{
if (stateInfo.State == RunspacePoolState.Opening)
{
// Change state to opened and notify the user.
stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Opened, null);
shouldRaiseEvents = true;
}
}
if (shouldRaiseEvents)
{
RaiseStateChangeEvent(stateInfo);
}
}
private void SetStateToBroken(Exception reason)
{
bool shouldRaiseEvents = false;
lock (syncObject)
{
if ((stateInfo.State == RunspacePoolState.Opening) ||
(stateInfo.State == RunspacePoolState.Opened) ||
(stateInfo.State == RunspacePoolState.Disconnecting) ||
(stateInfo.State == RunspacePoolState.Disconnected) ||
(stateInfo.State == RunspacePoolState.Connecting))
{
stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Broken, null);
shouldRaiseEvents = true;
}
}
if (shouldRaiseEvents)
{
RunspacePoolStateInfo stateInfo = new RunspacePoolStateInfo(this.stateInfo.State,
reason);
RaiseStateChangeEvent(stateInfo);
}
}
/// <summary>
/// Starting point for asynchronous thread.
/// </summary>
/// <remarks>
/// asyncResult object
/// </remarks>
protected void OpenThreadProc(object o)
{
Dbg.Assert(o is AsyncResult, "OpenThreadProc expects AsyncResult");
// Since this is an internal method, we can safely cast the
// object to AsyncResult object.
AsyncResult asyncObject = (AsyncResult)o;
// variable to keep track of exceptions.
Exception exception = null;
try
{
OpenHelper();
}
catch (Exception e)
{
// report non-severe exceptions to the user via the
// asyncresult object
exception = e;
}
finally
{
asyncObject.SetAsCompleted(exception);
}
}
/// <summary>
/// Closes the runspacepool synchronously / asynchronously.
/// </summary>
/// <param name="isAsync">
/// true to close asynchronously
/// </param>
/// <param name="callback">
/// A AsyncCallback to call once the BeginClose completes.
/// </param>
/// <param name="asyncState">
/// A user supplied state to call the <paramref name="callback"/>
/// with.
/// </param>
/// <returns>
/// asyncResult object to monitor status of the async
/// open operation. This is returned only if <paramref name="isAsync"/>
/// is true.
/// </returns>
private IAsyncResult CoreClose(bool isAsync, AsyncCallback callback, object asyncState)
{
lock (syncObject)
{
if ((stateInfo.State == RunspacePoolState.Closed) ||
(stateInfo.State == RunspacePoolState.Broken) ||
(stateInfo.State == RunspacePoolState.Closing) ||
(stateInfo.State == RunspacePoolState.Disconnecting) ||
(stateInfo.State == RunspacePoolState.Disconnected))
{
if (isAsync)
{
RunspacePoolAsyncResult asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false);
asyncResult.SetAsCompleted(null);
return asyncResult;
}
else
{
return null;
}
}
stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Closing, null);
}
// only one thread will reach here.
RaiseStateChangeEvent(stateInfo);
if (isAsync)
{
RunspacePoolAsyncResult asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false);
// Open pool in another thread
ThreadPool.QueueUserWorkItem(new WaitCallback(CloseThreadProc), asyncResult);
return asyncResult;
}
// open the runspace synchronously
CloseHelper();
return null;
}
private void CloseHelper()
{
try
{
InternalClearAllResources();
}
finally
{
stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Closed, null);
RaiseStateChangeEvent(stateInfo);
}
}
private void CloseThreadProc(object o)
{
Dbg.Assert(o is AsyncResult, "CloseThreadProc expects AsyncResult");
// Since this is an internal method, we can safely cast the
// object to AsyncResult object.
AsyncResult asyncObject = (AsyncResult)o;
// variable to keep track of exceptions.
Exception exception = null;
try
{
CloseHelper();
}
catch (Exception e)
{
// report non-severe exceptions to the user via the
// asyncresult object
exception = e;
}
finally
{
asyncObject.SetAsCompleted(exception);
}
}
#endregion
#region Private Methods
/// <summary>
/// Raise state changed event based on the StateInfo
/// object.
/// </summary>
/// <param name="stateInfo">State information object.</param>
protected void RaiseStateChangeEvent(RunspacePoolStateInfo stateInfo)
{
StateChanged.SafeInvoke(this,
new RunspacePoolStateChangedEventArgs(stateInfo));
}
/// <summary>
/// Checks if the Pool is open to honour requests.
/// If not throws an exception.
/// </summary>
/// <exception cref="InvalidRunspacePoolStateException">
/// Cannot perform operation because RunspacePool is
/// not in the opened state.
/// </exception>
internal void AssertPoolIsOpen()
{
lock (syncObject)
{
if (stateInfo.State != RunspacePoolState.Opened)
{
string message = StringUtil.Format(RunspacePoolStrings.InvalidRunspacePoolState, RunspacePoolState.Opened, stateInfo.State);
throw new InvalidRunspacePoolStateException(message,
stateInfo.State, RunspacePoolState.Opened);
}
}
}
/// <summary>
/// Creates a new Runspace and initializes it by calling Open()
/// </summary>
/// <returns>
/// An opened Runspace.
/// </returns>
/// <remarks>
/// TODO: Exceptions thrown here need to be documented.
/// </remarks>
protected Runspace CreateRunspace()
{
Dbg.Assert(_initialSessionState != null, "_initialSessionState should not be null");
// TODO: exceptions thrown here need to be documented
// runspace.Open() did not document all the exceptions.
Runspace result = RunspaceFactory.CreateRunspaceFromSessionStateNoClone(host, _initialSessionState);
result.ThreadOptions = this.ThreadOptions == PSThreadOptions.Default ? PSThreadOptions.ReuseThread : this.ThreadOptions;
result.ApartmentState = this.ApartmentState;
this.PropagateApplicationPrivateData(result);
result.Open();
// Enforce the system lockdown policy if one is defined.
Utils.EnforceSystemLockDownLanguageMode(result.ExecutionContext);
result.Events.ForwardEvent += OnRunspaceForwardEvent; // this must be done after open since open initializes the ExecutionContext
lock (runspaceList)
{
runspaceList.Add(result);
totalRunspaces = runspaceList.Count;
}
// Start/Reset the cleanup timer to release idle runspaces in the pool.
lock (this.syncObject)
{
_cleanupTimer.Change(CleanupInterval, CleanupInterval);
}
// raise the RunspaceCreated event and let callers handle it.
RunspaceCreated.SafeInvoke(this, new RunspaceCreatedEventArgs(result));
return result;
}
/// <summary>
/// Cleans/Closes the runspace.
/// </summary>
/// <param name="runspace">
/// Runspace to be closed/cleaned
/// </param>
protected void DestroyRunspace(Runspace runspace)
{
Dbg.Assert(runspace != null, "Runspace cannot be null");
runspace.Events.ForwardEvent -= OnRunspaceForwardEvent; // this must be done after open since open initializes the ExecutionContext
runspace.Close();
runspace.Dispose();
lock (runspaceList)
{
runspaceList.Remove(runspace);
totalRunspaces = runspaceList.Count;
}
}
/// <summary>
/// Cleans the pool closing the runspaces that are idle.
/// This method is called as part of a timer callback.
/// This method will make sure at least minPoolSz number
/// of Runspaces are active.
/// </summary>
/// <param name="state"></param>
protected void CleanupCallback(object state)
{
Dbg.Assert((this.stateInfo.State != RunspacePoolState.Disconnected &&
this.stateInfo.State != RunspacePoolState.Disconnecting &&
this.stateInfo.State != RunspacePoolState.Connecting),
"Local RunspacePool cannot be in disconnect/connect states");
bool isCleanupTimerChanged = false;
// Clean up the pool only if more runspaces
// than minimum requested are present.
while (totalRunspaces > minPoolSz)
{
// if the pool is closing just return..
if (this.stateInfo.State == RunspacePoolState.Closing)
{
return;
}
// This is getting run on a threadpool thread
// it is ok to take the hit on locking and unlocking.
// this will release request threads depending
// on thread scheduling
Runspace runspaceToDestroy = null;
lock (pool)
{
if (pool.Count == 0)
{
break; // break from while
}
runspaceToDestroy = pool.Pop();
}
// Stop the clean up timer only when we are about to clean runspaces.
// It will be restarted when a new runspace is created.
if (!isCleanupTimerChanged)
{
lock (this.syncObject)
{
_cleanupTimer.Change(Timeout.Infinite, Timeout.Infinite);
isCleanupTimerChanged = true;
}
}
// destroy runspace outside of the lock
DestroyRunspace(runspaceToDestroy);
continue;
}
}
/// <summary>
/// Close all the runspaces in the pool.
/// </summary>
private void InternalClearAllResources()
{
string message = StringUtil.Format(RunspacePoolStrings.InvalidRunspacePoolState, RunspacePoolState.Opened, stateInfo.State);
Exception invalidStateException = new InvalidRunspacePoolStateException(message,
stateInfo.State, RunspacePoolState.Opened);
GetRunspaceAsyncResult runspaceRequester;
// clear the request queue first..this way waiting threads
// are immediately notified.
lock (runspaceRequestQueue)
{
while (runspaceRequestQueue.Count > 0)
{
runspaceRequester = runspaceRequestQueue.Dequeue();
runspaceRequester.SetAsCompleted(invalidStateException);
}
}
lock (ultimateRequestQueue)
{
while (ultimateRequestQueue.Count > 0)
{
runspaceRequester = ultimateRequestQueue.Dequeue();
runspaceRequester.SetAsCompleted(invalidStateException);
}
}
// close all the runspaces
List<Runspace> runspaceListCopy = new List<Runspace>();
lock (runspaceList)
{
runspaceListCopy.AddRange(runspaceList);
runspaceList.Clear();
}
// Start from the most recent runspace.
for (int index = runspaceListCopy.Count - 1; index >= 0; index--)
{
// close runspaces suppress exceptions
try
{
// this will release pipelines executing in the
// runspace.
runspaceListCopy[index].Close();
runspaceListCopy[index].Dispose();
}
catch (InvalidRunspaceStateException)
{
}
}
lock (pool)
{
pool.Clear();
}
// dont release pool/runspacelist/runspaceRequestQueue/ultimateRequestQueue as they
// might be accessed in lock() statements from another thread.
}
/// <summary>
/// If <paramref name="requestToEnqueue"/> is not null, enqueues the request.
/// Checks if a thread pool thread is queued to service pending requests
/// for runspace. If a thread is not queued, queues one.
/// </summary>
/// <param name="requestToEnqueue">
/// Used by calling threads to queue a request before checking and starting
/// servicing thread.
/// </param>
/// <param name="useCallingThread">
/// uses calling thread to assign available runspaces (if any) to runspace
/// requesters.
/// </param>
protected void EnqueueCheckAndStartRequestServicingThread(GetRunspaceAsyncResult requestToEnqueue,
bool useCallingThread)
{
bool shouldStartServicingInSameThread = false;
lock (runspaceRequestQueue)
{
if (requestToEnqueue != null)
{
runspaceRequestQueue.Enqueue(requestToEnqueue);
}
// if a thread is already servicing requests..just return.
if (isServicingRequests)
{
return;
}
if ((runspaceRequestQueue.Count + ultimateRequestQueue.Count) > 0)
{
// we have requests pending..check if a runspace is available to
// service the requests.
lock (pool)
{
if ((pool.Count > 0) || (totalRunspaces < maxPoolSz))
{
isServicingRequests = true;
if ((useCallingThread) && (ultimateRequestQueue.Count == 0))
{
shouldStartServicingInSameThread = true;
}
else
{
// release a async result object using a thread pool thread.
// this way the calling thread will not block.
ThreadPool.QueueUserWorkItem(new WaitCallback(ServicePendingRequests), false);
}
}
}
}
}
// only one thread will be here if any..
// This will allow us to release lock.
if (shouldStartServicingInSameThread)
{
ServicePendingRequests(true);
}
}
/// <summary>
/// Releases any readers in the reader queue waiting for
/// Runspace.
/// </summary>
/// <param name="useCallingThreadState">
/// This is of type object..because this method is called from a ThreadPool
/// Thread.
/// true, if calling thread should be used to assign a runspace.
/// </param>
protected void ServicePendingRequests(object useCallingThreadState)
{
// Check if the pool is closed or closing..if so return.
if ((stateInfo.State == RunspacePoolState.Closed) || (stateInfo.State == RunspacePoolState.Closing))
{
return;
}
Dbg.Assert((this.stateInfo.State != RunspacePoolState.Disconnected &&
this.stateInfo.State != RunspacePoolState.Disconnecting &&
this.stateInfo.State != RunspacePoolState.Connecting),
"Local RunspacePool cannot be in disconnect/connect states");
bool useCallingThread = (bool)useCallingThreadState;
GetRunspaceAsyncResult runspaceRequester = null;
try
{
while (true)
{
lock (ultimateRequestQueue)
{
while (ultimateRequestQueue.Count > 0)
{
// if the pool is closing just return..
if (this.stateInfo.State == RunspacePoolState.Closing)
{
return;
}
Runspace result;
lock (pool)
{
if (pool.Count > 0)
{
result = pool.Pop();
}
else if (totalRunspaces >= maxPoolSz)
{
// no runspace is available..
return;
}
else
{
// TODO: how to handle exceptions if runspace
// creation fails.
// Create a new runspace..since the max limit is
// not reached.
result = CreateRunspace();
}
}
// Dequeue a runspace request
runspaceRequester = ultimateRequestQueue.Dequeue();
// if the runspace is not active send the runspace back to
// the pool and process other requests
if (!runspaceRequester.IsActive)
{
lock (pool)
{
pool.Push(result);
}
// release the runspace requester
runspaceRequester.Release();
continue;
}
// release readers waiting for runspace on a thread pool
// thread.
runspaceRequester.Runspace = result;
// release the async operation on a thread pool thread.
if (useCallingThread)
{
// call DoComplete outside of the lock..as the
// DoComplete handler may handle the runspace
// in the same thread thereby blocking future
// servicing requests.
goto endOuterWhile;
}
else
{
ThreadPool.QueueUserWorkItem(new WaitCallback(runspaceRequester.DoComplete));
}
}
}
lock (runspaceRequestQueue)
{
if (runspaceRequestQueue.Count == 0)
{
break;
}
// copy requests from one queue to another and start
// processing the other queue
while (runspaceRequestQueue.Count > 0)
{
ultimateRequestQueue.Enqueue(runspaceRequestQueue.Dequeue());
}
}
}
endOuterWhile:;
}
finally
{
lock (runspaceRequestQueue)
{
isServicingRequests = false;
// check if any new runspace request has arrived..
EnqueueCheckAndStartRequestServicingThread(null, false);
}
}
if ((useCallingThread) && (runspaceRequester != null))
{
// call DoComplete outside of the lock and finally..as the
// DoComplete handler may handle the runspace in the same
// thread thereby blocking future servicing requests.
runspaceRequester.DoComplete(null);
}
}
/// <summary>
/// Throws an exception if the runspace state is not
/// BeforeOpen.
/// </summary>
protected void AssertIfStateIsBeforeOpen()
{
if (stateInfo.State != RunspacePoolState.BeforeOpen)
{
// Call fails if RunspacePoolState is not BeforeOpen.
InvalidRunspacePoolStateException e =
new InvalidRunspacePoolStateException
(
StringUtil.Format(RunspacePoolStrings.CannotOpenAgain,
new object[] { stateInfo.State.ToString() }
),
stateInfo.State,
RunspacePoolState.BeforeOpen
);
throw e;
}
}
/// <summary>
/// Raises the ForwardEvent event.
/// </summary>
protected virtual void OnForwardEvent(PSEventArgs e)
{
this.ForwardEvent?.Invoke(this, e);
}
/// <summary>
/// Forward runspace events to the pool's event queue.
/// </summary>
private void OnRunspaceForwardEvent(object sender, PSEventArgs e)
{
if (e.ForwardEvent)
{
OnForwardEvent(e);
}
}
#endregion
}
}
|