private void RunspacesLeakDetected(string key, string relatedBudgetKey) { int num = 0; IPowerShellBudget powerShellBudget = null; if (this.budgets.TryGetValue(key, out powerShellBudget)) { num = powerShellBudget.TotalActiveRunspacesCount; } if (powerShellBudget != null) { ExTraceGlobals.PublicPluginAPITracer.TraceError <string, string, int>(0L, "Connection leak detected for Key {0} in class {1}. Leaked value {2}.", key, base.GetType().ToString(), num); if (num > 0) { AuthZLogger.SafeAppendGenericError("WSManBudgetManagerBase.RunspacesLeakDetected", string.Format("Connection leak detected for Key {0} in class {1}. Leaked value {2}.", key, base.GetType(), num), false); TaskLogger.LogRbacEvent(TaskEventLogConstants.Tuple_PSConnectionLeakDetected, null, new object[] { key, base.GetType().ToString(), num }); this.UpdateConnectionLeakPerfCounter(num); } powerShellBudget.Dispose(); } if (num > 0 && relatedBudgetKey != null) { this.CorrectRelatedBudgetWhenLeak(relatedBudgetKey, num); } }
internal void RemoveBudgetIfNoActiveRunspace(AuthZPluginUserToken userToken) { lock (this.instanceLock) { IPowerShellBudget budget = this.GetBudget(userToken, false, false); if (budget != null && budget.TotalActiveRunspacesCount <= 0) { string text = this.CreateKey(userToken); Unlimited <uint> powerShellMaxRunspacesTimePeriod = budget.ThrottlingPolicy.PowerShellMaxRunspacesTimePeriod; if (powerShellMaxRunspacesTimePeriod.IsUnlimited) { ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Key {0} is removed from budgets dictionary immediately.", text); this.budgets.Remove(text); this.keyToRemoveBudgets.Remove(text); } else { int num = (int)(powerShellMaxRunspacesTimePeriod.Value + 5U); ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string, int>(0L, "Register key {0} to keyToRemoveBudgets, timeout {1} seconds.", text, num); this.keyToRemoveBudgets.InsertAbsolute(text, BudgetManager.NormalCleanupCacheValue, TimeSpan.FromSeconds((double)num), new RemoveItemDelegate <string, string>(this.OnKeyToRemoveBudgetsCacheValueRemoved)); } } } this.UpdateBudgetsPerfCounter(this.budgets.Count); this.UpdateKeyToRemoveBudgetsPerfCounter(this.keyToRemoveBudgets.Count); }
protected void EnforceDelay() { if (this.context.ErrorInfo.TerminatePipeline) { return; } IPowerShellBudget psbudget = this.PSBudget; if (psbudget != null) { T t = (default(T) == null) ? Activator.CreateInstance <T>() : default(T); DelayEnforcementResults delayEnforcementResults = t.EnforceDelay(this, ThrottlingModule <T> .costTypesInEnforceDelay, ThrottlingModule <T> .CmdletMaxPreferredDelay); LocalizedString localizedString = this.GenerateDelayInfoLogString(this.PSBudget, delayEnforcementResults); if (!string.IsNullOrEmpty(localizedString)) { string text = string.Format("; PolicyDN: {0}; Snapshot: {1}", psbudget.ThrottlingPolicy.GetIdentityString(), psbudget); LocalizedString warningMessage = new LocalizedString(localizedString + text); this.context.Items["ThrottlingInfo"] = text; this.context.Items["DelayedInfo"] = localizedString; Guid uniqueId = this.context.UniqueId; CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.ThrottlingInfo, text); CmdletLogger.SafeSetLogger(uniqueId, RpsCmdletMetadata.DelayInfo, CmdletLogHelper.NeedConvertLogMessageToUS ? localizedString.ToString(CmdletLogHelper.DefaultLoggingCulture) : localizedString); this.WriteCmdletMicroDelayMessage(warningMessage, delayEnforcementResults.DelayInfo.Delay.TotalSeconds); } PowerShellBudgetWrapper powerShellBudgetWrapper = psbudget as PowerShellBudgetWrapper; WorkloadManagementLogger.SetBudgetBalance(powerShellBudgetWrapper.GetInnerBudget().CasTokenBucket.GetBalance().ToString(), null); } }
protected virtual CostHandle StartRunspaceImpl(AuthZPluginUserToken userToken) { IPowerShellBudget budget = this.GetBudget(userToken, true, true); if (budget != null) { ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Start budget tracking for ActiveRunspaces, key {0}", this.CreateKey(userToken)); return(budget.StartActiveRunspace()); } ExTraceGlobals.PublicPluginAPITracer.TraceError <string>(0L, "Try to start budget tracking for ActiveRunspaces, key {0} But the budget doesn't exist.", this.CreateKey(userToken)); return(null); }
internal IThrottlingPolicy GetThrottlingPolicy() { using (IPowerShellBudget powerShellBudget = this.CreateBudget(BudgetType.PowerShell)) { if (powerShellBudget != null) { return(powerShellBudget.ThrottlingPolicy); } } if (this.UserEntry is MiniRecipient) { return((this.UserEntry as MiniRecipient).ReadThrottlingPolicy()); } return((this.UserEntry as ADUser).ReadThrottlingPolicy()); }
// Token: 0x06001493 RID: 5267 RVA: 0x0004CD60 File Offset: 0x0004AF60 internal CostHandle StartCmdlet(AuthZPluginUserToken userToken) { if (!this.ShouldThrottling(userToken)) { return(null); } lock (base.InstanceLock) { IPowerShellBudget budget = base.GetBudget(userToken, true, true); if (budget != null) { ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Start budget tracking for Cmdlet, key {0}", this.CreateKey(userToken)); return(budget.StartCmdlet(null)); } ExTraceGlobals.PublicPluginAPITracer.TraceError <string>(0L, "Try to start budget tracking for Cmdlet, key {0} But the budget doesn't exist.", this.CreateKey(userToken)); } return(null); }
internal bool CheckOverBudget(AuthZPluginUserToken userToken, CostType costType, out OverBudgetException exception) { exception = null; if (!this.ShouldThrottling(userToken)) { return(false); } lock (this.instanceLock) { IPowerShellBudget budget = this.GetBudget(userToken, false, false); if (budget != null) { return(budget.TryCheckOverBudget(costType, out exception)); } ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Try to check overbudget for key {0}. But the budget doesn't exist.", this.CreateKey(userToken)); } return(false); }
internal string GetWSManBudgetUsage(AuthZPluginUserToken userToken) { string result; lock (this.instanceLock) { IPowerShellBudget budget = this.GetBudget(userToken, false, false); if (budget == null) { result = null; } else { result = budget.GetWSManBudgetUsage(); } } return(result); }
internal virtual IPowerShellBudget CreateBudget(BudgetType budgetType) { IPowerShellBudget result = null; if (this.DelegatedPrincipal != null) { ExTraceGlobals.PublicPluginAPITracer.TraceDebug <BudgetType, string>(0L, "Create Budge {0} for AuthZPluginUserToken {1} using DelegatedPrincipal.", budgetType, this.UserName); result = PowerShellBudget.Acquire(new DelegatedPrincipalBudgetKey(this.DelegatedPrincipal, budgetType)); } else { ExTraceGlobals.PublicPluginAPITracer.TraceDebug <BudgetType, string>(0L, "Create Budge {0} for AuthZPluginUserToken {1} using UserEntry.", budgetType, this.UserName); if (budgetType == BudgetType.WSManTenant) { return(PowerShellBudget.Acquire(new TenantBudgetKey(this.OrgId, budgetType))); } SecurityIdentifier securityIdentifier = (SecurityIdentifier)this.UserEntry[IADSecurityPrincipalSchema.Sid]; if (securityIdentifier != null) { ADObjectId rootOrgId; if (this.OrgId == null || this.OrgId.Equals(OrganizationId.ForestWideOrgId)) { rootOrgId = ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest(); } else { rootOrgId = ADSystemConfigurationSession.GetRootOrgContainerId(this.OrgId.PartitionId.ForestFQDN, null, null); } result = PowerShellBudget.Acquire(securityIdentifier, budgetType, ADSessionSettings.FromOrganizationIdWithoutRbacScopes(rootOrgId, this.OrgId, this.OrgId, true)); } else { ExTraceGlobals.PublicPluginAPITracer.TraceDebug <string>(0L, "Sid is null, return null budget for AuthZPluginUserToken {0}.", this.UserName); } } return(result); }
private void ThrottleRequest(HttpContext context) { ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[ThrottlingHttpModule::ThrottleRequest] Enter"); WinRMInfo winRMInfo = context.Items["X-RemotePS-WinRMInfo"] as WinRMInfo; if (winRMInfo == null) { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[ThrottlingHttpModule::ThrottleRequest] WinRMInfo = null."); return; } string action = winRMInfo.Action; if (string.IsNullOrEmpty(action)) { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[ThrottlingHttpModule::ThrottleRequest] WinRMInfo.Action = null."); return; } if (!action.EndsWith(":Command", StringComparison.OrdinalIgnoreCase) && !action.Equals("Command", StringComparison.OrdinalIgnoreCase)) { ExTraceGlobals.HttpModuleTracer.TraceDebug <string>((long)this.GetHashCode(), "[ThrottlingHttpModule::ThrottleRequest] Not Command Request. WinRMInfo.Action = {0}.", action); return; } IPowerShellBudget powerShellBudget = null; OverBudgetException ex = null; try { try { using (new MonitoredScope("ThrottlingHttpModule", "GetBudget", HttpModuleHelper.HttpPerfMonitors)) { powerShellBudget = this.GetBudget(context); } if (powerShellBudget == null) { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[ThrottlingHttpModule::ThrottleRequest] budget = null."); return; } using (new MonitoredScope("ThrottlingHttpModule", "CheckBudgetAndStartCmdlet", HttpModuleHelper.HttpPerfMonitors)) { powerShellBudget.StartCmdlet(null); powerShellBudget.TryCheckOverBudget(CostType.CMDLET, out ex); } } finally { if (powerShellBudget != null) { powerShellBudget.Dispose(); } } if (ex != null) { string windowsLiveId = context.CurrentUserToken().WindowsLiveId; if (windowsLiveId != null) { FailFastUserCache.Instance.AddUserToCache(windowsLiveId, BlockedType.NewRequest, TimeSpan.Zero); HttpLogger.SafeAppendColumn(RpsCommonMetadata.ContributeToFailFast, "AuthZ-UserSelf", LoggerHelper.GetContributeToFailFastValue("User", windowsLiveId, BlockedType.NewRequest.ToString(), -1.0)); } HttpModuleHelper.EndPowerShellRequestWithFriendlyError(context, FailureCategory.AuthZ, ex.GetType().Name, Strings.ErrorOperationTarpitting(ex.BackoffTime / 1000) + string.Format("{2}Policy: {0}; {2}Snapshot: {1}", ex.ThrottlingPolicyDN, ex.Snapshot, Environment.NewLine), "ThrottlingHttpModule", false); } } catch (Exception ex2) { if (!(ex2 is ThreadAbortException)) { HttpLogger.SafeAppendGenericError("ThrottlingHttpModule", ex2, new Func <Exception, bool>(KnownException.IsUnhandledException)); ExTraceGlobals.HttpModuleTracer.TraceError <Exception>((long)this.GetHashCode(), "[ThrottlingHttpModule::ThrottleRequest] Get un-Excpected Exception. {0}", ex2); } } }
internal static bool RevertExpiredThrottlingPolicyIfNeeded(IPowerShellBudget budget) { if (budget == null) { return(false); } bool result; using (new MonitoredScope("PowerShellThrottlingPolicyUpdater", "RevertExpiredThrottlingPolicyIfNeeded", AuthZLogHelper.AuthZPerfMonitors)) { ThrottlingPolicy throttlingPolicy = null; try { throttlingPolicy = ((EffectiveThrottlingPolicy)budget.ThrottlingPolicy).ThrottlingPolicy; Match match = Regex.Match(throttlingPolicy.Name, "^\\[(?<expiredtime>[0-9]{4}(-[0-9]{2}){2}T([0-9]{2}:){2}[0-9]{2})\\](?<orginalname>.+)", RegexOptions.Compiled); DateTime t; if (!match.Success) { result = false; } else if (!DateTime.TryParse(match.Groups["expiredtime"].Value, out t)) { AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Unrecognized time format in throttling policy '{0}'.", throttlingPolicy.Name)); result = false; } else if (t > DateTime.UtcNow) { AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Throttlling policy '{0}' is not expired yet.", throttlingPolicy.Name)); result = false; } else { IConfigurationSession configuationSession = PowerShellThrottlingPolicyUpdater.GetConfiguationSession(throttlingPolicy.OrganizationId); ThrottlingPolicy writableThrottlingPolicy = PowerShellThrottlingPolicyUpdater.GetWritableThrottlingPolicy(configuationSession, throttlingPolicy); if (writableThrottlingPolicy == null || writableThrottlingPolicy.Name != throttlingPolicy.Name) { AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Throttlling policy '{0}' is updated and don't need to be expired.", throttlingPolicy.Name)); result = false; } else { string arg; if (PowerShellThrottlingPolicyUpdater.RevertBackupThrottlingSettings(writableThrottlingPolicy, out arg)) { writableThrottlingPolicy.Name = match.Groups["orginalname"].Value; configuationSession.Save(writableThrottlingPolicy); AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Revert throttling policy '{0}' to name: {1} and restore backup throttling value: {2}.", throttlingPolicy.Name, writableThrottlingPolicy.Name, arg)); } else { PowerShellThrottlingPolicyUpdater.ClearThrottlingPolicyAssoicate(PowerShellThrottlingPolicyUpdater.GetRecipientSession(throttlingPolicy.OrganizationId), throttlingPolicy); configuationSession.Delete(writableThrottlingPolicy); AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Delete throttling policy '{0}' and clear associates with it.", throttlingPolicy.Name)); } result = true; } } } catch (TransientException arg2) { AuthZLogger.SafeAppendGenericInfo("PowerShellThrottlingPolicyUpdater", string.Format("Occur transient exception on revert throttling policy '{0}': {1}", (throttlingPolicy != null) ? throttlingPolicy.Name : string.Empty, arg2)); result = false; } catch (Exception ex) { AuthZLogger.SafeAppendGenericError("PowerShellThrottlingPolicyUpdater", string.Format("Error on revert throttling policy '{0}': {1}", (throttlingPolicy != null) ? throttlingPolicy.Name : string.Empty, ex), KnownException.IsUnhandledException(ex)); result = false; } } return(result); }