private void AssignTimeout(long ticks, TimeoutAction timeoutAction) { _timeoutAction = timeoutAction; // Add Heartbeat.Interval since this can be called right before the next heartbeat. Interlocked.Exchange(ref _timeoutTimestamp, _lastTimestamp + ticks + Heartbeat.Interval.Ticks); }
public List <string> Read(string terminators = "\r\n\0") { Logger.Debug("Read start"); using (semaphore.UseOnce()) { Logger.Debug("Read acquired semaphore"); int read; try { using (TimeoutAction.Set(timeout, () => { Close(); Logger.Debug("Read timeout expired"); })) read = socket.Receive(parser.Buffer, parser.Offset, parser.BufferLength, SocketFlags.None); Logger.Debug("Read completed"); } catch (Exception ex) { Logger.Warning("{ex}", ex); Close(); throw new ConnectionLostException("Socket error", ex); } if (read == 0) { Logger.Warning("Read recv returned zero bytes"); Close(); throw new ConnectionLostException("Recv returned zero bytes"); } return(parser.Parse(read, terminators).ToList()); } }
public void TestTimeoutStartWithArg() { ManualResetEvent h = new ManualResetEvent(false); TimeoutAction.Start(TimeSpan.FromMilliseconds(1), delegate(ManualResetEvent mre) { mre.Set(); }, h); Assert.IsTrue(h.WaitOne(1000, false)); }
private void AssignTimeout(long milliseconds, TimeoutAction timeoutAction) { _timeoutAction = timeoutAction; // Add KestrelThread.HeartbeatMilliseconds extra milliseconds since this can be called right before the next heartbeat. Interlocked.Exchange(ref _timeoutTimestamp, _lastTimestamp + milliseconds + KestrelThread.HeartbeatMilliseconds); }
public void TestTimeoutStartWithErrorHandler() { ManualResetEvent h = new ManualResetEvent(false); TimeoutAction.Start(TimeSpan.FromMilliseconds(1), delegate { throw new ApplicationException(); }, delegate(Exception err) { h.Set(); }); Assert.IsTrue(h.WaitOne(1000, false)); }
public void Should_execute_after_timeout() { var sw = Stopwatch.StartNew(); using (TimeoutAction.Set(100, () => sw.Stop())) Thread.Sleep(2000); sw.ElapsedMilliseconds.Should().BeInRange(0, 150); }
public void TestTimeoutOccursForDispose() { bool called = false; TimeoutAction action = new TimeoutAction(TimeSpan.FromHours(1), delegate { called = true; }); Assert.AreEqual(false, called); action.Dispose(); Assert.AreEqual(true, called); }
public void TestTimeoutStartWithArgAndErrorHandler() { ManualResetEvent h1 = new ManualResetEvent(false); ManualResetEvent h2 = new ManualResetEvent(false); TimeoutAction.Start(TimeSpan.FromMilliseconds(1), delegate(ManualResetEvent mre) { mre.Set(); throw new ApplicationException(); }, h1, delegate(Exception err) { h2.Set(); }); Assert.IsTrue(h1.WaitOne(1000, false)); Assert.IsTrue(h2.WaitOne(1000, false)); }
public void TestTimeoutCalledOnce() { int callCount = 0; TimeoutAction action = new TimeoutAction(TimeSpan.FromHours(1), delegate { callCount++; }); Assert.AreEqual(0, callCount); action.Dispose(); Assert.AreEqual(1, callCount); action.Dispose(); Assert.AreEqual(1, callCount); }
public void TestTimeoutFiresOnUnload() { ManualResetEvent h = new ManualResetEvent(false); TimeoutAction action = new TimeoutAction(TimeSpan.FromDays(1), delegate { h.Set(); }); MethodInvoker delete = (MethodInvoker)Delegate.CreateDelegate(typeof(MethodInvoker), action, "Finalize", true, true); Assert.IsFalse(h.WaitOne(0, false)); delete(); Assert.IsTrue(h.WaitOne(0, false)); }
/// <summary> /// Retries action until either it returns true or the timeout time elapses. /// </summary> protected static void RetryUntilTimeout(TimeSpan timeout, TimeoutAction action) { DateTime due = DateTime.UtcNow + timeout; do { if (action()) return; } while (DateTime.UtcNow < due); throw new TimeoutException("The operation has timed out"); }
private void ShowOctopus() { isOctopusAlived = true; SpawnOctopus(); ShowOctopusLegs(); octopusWaitingTimeoutAction = new TimeoutAction(5f, () => { ShowOctopusInc(); HideOctopus(); }); timer.RegisterTimeout(octopusWaitingTimeoutAction); }
/// <summary> /// Retries action until either it returns true or the timeout time elapses. /// </summary> protected static void RetryUntilTimeout(TimeSpan timeout, TimeoutAction action) { DateTime due = DateTime.UtcNow + timeout; do { if (action()) { return; } }while (DateTime.UtcNow < due); throw new TimeoutException("The operation has timed out"); }
public bool Update() { if (!IsActive) { return(false); } if (TimeElapsed()) { TimeoutAction.Invoke(); TimeOutCount++; ResetTimeout(); } return(true); }
protected virtual Task Connect(string host, int port, int timeout = DefaultConnectTimeout) { Logger.Information("Connect with {host}:{port} timeout {timeout}", host, port, timeout); ThrowIfNotReady(); return(Task.Run(() => { Logger.Debug("Connect task started"); using (sendReceiveSemaphore.UseOnce()) { Logger.Debug("Connect task acquired semaphore"); var client = new Socket(SocketType.Stream, ProtocolType.Tcp); using (TimeoutAction.Set(timeout, () => { client.CloseForce(); Logger.Debug("Timeout expired"); })) client.ConnectAsync(host, port).Wait(timeout + 100); Logger.Debug("Connect task socket connected"); stream = new ByteStream(client, receiveTimeout); Logger.Debug("Connect task completed"); } })); }
public async void Start() { //需要阻止重复调用Start。 if (isRunning) { return; } isRunning = true; Contract.Requires(_timeSpan != null); Contract.Requires(TimeoutAction != null); _source = new CancellationTokenSource(); _token = _source.Token; waitingTask = Task.Delay(_timeSpan, _token); await waitingTask; if (!_token.IsCancellationRequested) { TimeoutAction?.Invoke(); } }
public void Send(string data) { try { logger.Debug($"Send {data}"); semaphore.Wait(); logger.Debug($"Send acquired semaphore"); using (TimeoutAction.Set(timeout, () => { Close(); logger.Debug($"Send timeout expired"); })) socket.Send(Encoding.ASCII.GetBytes(data)); logger.Debug($"Send completed"); } catch (Exception ex) { logger.Warn(ex); Close(); throw new ConnectionLostException("Could not send", ex); } finally { semaphore.Release(); } }
public void ResetTimeout(long ticks, TimeoutAction timeoutAction) { AssignTimeout(ticks, timeoutAction); }
public void SetTimeout(long ticks, TimeoutAction timeoutAction) { Debug.Assert(_timeoutTimestamp == long.MaxValue, "Concurrent timeouts are not supported"); AssignTimeout(ticks, timeoutAction); }
public void SetTimeout(long ticks, TimeoutAction timeoutAction) { }
void ITimeoutControl.ResetTimeout(long ticks, TimeoutAction timeoutAction) { }
public static Int32 RunCommand(String command, String server, String remoteWorkingDirectory, long timeoutMills, bool killProcessOnTimeout, TimeoutAction actionOnTimeout, Action <string, string> callback, string callbackLabel, bool isDryRun) { return(RunCommand(command, server, remoteWorkingDirectory, null, null, null, timeoutMills, killProcessOnTimeout, actionOnTimeout, callback, callbackLabel, isDryRun)); }
public static Int32 RunCommand(String command, String server, String remoteWorkingDirectory, String runAsDomain, String runAsUser, String runAsPassword, long timeoutMills, bool killProcessOnTimeout, TimeoutAction actionOnTimeout, Action <string, string> callback, string callbackLabel, bool isDryRun) { if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Inside RunCommand"); } Int32 exitStatus = 0; String rwd = config.Default.DefaultRemoteWorkingDirectory; if (string.IsNullOrWhiteSpace(rwd)) { rwd = @"C:\Temp"; } String rwdUnc = Utils.GetServerLongPath(server, rwd); String rwdWin = Utils.GetServerLongPathWindows(server, rwd); if (callback != null) { // Blank Out Any Plain Text Passwords string myCmd = command; if (command.ToLower().Contains("winrs ")) { myCmd = Regex.Replace(myCmd, @"\s-p:[^\s\\]*", @" -p:********"); } if (command.ToLower().Contains("pscp ") || command.ToLower().Contains("plink ")) { myCmd = Regex.Replace(myCmd, @"\s-pw [^\s\\]*", @" -pw ********"); } callback(callbackLabel, "Starting Command : " + myCmd); } if (!isDryRun) { try { if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Setting / Creating Working Directory"); } // Create the Remote Working Directory Using Defaults If None Is Passed In if (remoteWorkingDirectory == null) { Utils.CreateDirectory(rwdUnc); } else { rwd = remoteWorkingDirectory; rwdUnc = Utils.GetServerLongPath(server, remoteWorkingDirectory); rwdWin = Utils.GetServerLongPathWindows(server, remoteWorkingDirectory); } // Create the process using (ManagementClass process = new ManagementClass("Win32_Process")) { if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Getting Management Scope"); } ManagementScope scope = GetManagementScope(server, runAsDomain, runAsUser, runAsPassword); if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Setting Process Management Scope"); } process.Scope = scope; if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Getting Process Method Parameters"); } ManagementBaseObject inParams = process.GetMethodParameters("Create"); if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Creating Random Logfile Name"); } String stdOutErrFile = System.IO.Path.GetRandomFileName(); stdOutErrFile = stdOutErrFile.Replace(".", "") + ".log"; if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Setting Process Method Parameters"); } inParams["CurrentDirectory"] = rwd; inParams["CommandLine"] = @"cmd.exe /c " + command + @" 1> " + stdOutErrFile + @" 2>&1"; if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Calling InvokeMethod"); } ManagementBaseObject mbo = process.InvokeMethod("Create", inParams, null); if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Called InvokeMethod, Checking ReturnValue"); } UInt32 exitCode = (uint)mbo["ReturnValue"]; UInt32 processId = 0; if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Return Value = [" + exitCode + "]"); } if (exitCode == 0) { processId = (uint)mbo["ProcessId"]; if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Got ProcessId [" + processId + "]"); } String uncOutFile = rwdUnc + @"\" + stdOutErrFile; String winUncOutFile = rwdWin + @"\" + stdOutErrFile; if (server == null || "localhost".Equals(server.ToLower()) || "127.0.0.1".Equals(server.ToLower())) { uncOutFile = rwd + @"\" + stdOutErrFile; winUncOutFile = rwd + @"\" + stdOutErrFile; } // Start Tailing Output Log if (config.Default.DebugMode) { callback(callbackLabel, "DEBUG >> Starting LogTrailer On File [" + winUncOutFile + "]"); } LogTailer tailer = new LogTailer(winUncOutFile, callback, callbackLabel); tailer.Start(); // Wait For Process To Finish or Timeout To Be Reached ManagementEventWatcher w = new ManagementEventWatcher(scope, new WqlEventQuery("select * from Win32_ProcessStopTrace where ProcessId=" + processId)); if (timeoutMills > 0) { w.Options.Timeout = new TimeSpan(0, 0, 0, 0, (int)timeoutMills); } try { ManagementBaseObject mboEvent = w.WaitForNextEvent(); UInt32 uExitStatus = (UInt32)mboEvent.Properties["ExitStatus"].Value; exitStatus = unchecked ((int)uExitStatus); } catch (ManagementException ex) { if (ex.Message.Contains("Timed out")) { StringBuilder rc = new StringBuilder(); String processName = @"cmd.exe"; String timeoutMessage = "TIMEOUT : Process [" + processName + "] With Id [" + processId + "] Failed To Stop In [" + timeoutMills + "] Milliseconds."; if (killProcessOnTimeout) { String queryStr = String.Format("SELECT * FROM Win32_Process Where Name = '{0}' AND ProcessId = '{1}'", processName, processId); ObjectQuery Query = new ObjectQuery(queryStr); ManagementObjectSearcher Searcher = new ManagementObjectSearcher(scope, Query); foreach (ManagementObject thisProcess in Searcher.Get()) { rc.Append(KillProcess(scope, thisProcess)); } using (StringReader procStr = new StringReader(rc.ToString())) { String procLine; while ((procLine = procStr.ReadLine()) != null) { if (callback != null) { callback(callbackLabel, procLine); } else { Console.WriteLine(procLine); } } } timeoutMessage = "TIMEOUT : Process [" + processName + "] With Id [" + processId + "] Failed To Stop In [" + timeoutMills + "] Milliseconds And Was Remotely Termintated."; } tailer.Stop(60, true); throw new Exception(timeoutMessage); } else { tailer.Stop(60, true); throw ex; } } // Process Completed. Give up to 10 minutes for remote execution logs to be processed. tailer.Stop(600, true); } else { if (callback != null) { callback(callbackLabel, "Return Value : " + exitCode); callback(callbackLabel, mbo.GetText(TextFormat.Mof)); } } } } catch (Exception e) { if (callback != null) { String errorMsg = e.Message; if (errorMsg.StartsWith("TIMEOUT")) { callback(callbackLabel, e.Message); } else { callback(callbackLabel, "Error Occured In WMIUtils.RunCommand : "); callback(callbackLabel, e.Message); callback(callbackLabel, e.StackTrace); throw e; } } if (actionOnTimeout == TimeoutAction.Error) { throw e; } } } else { callback?.Invoke(callbackLabel, "Dry Run Flag Set. Execution Skipped"); } if (callback != null) { callback(callbackLabel, "Command Completed. Exit Code = " + exitStatus); } return(exitStatus); }
public BlockConsensusContext(ECPoint my_pubkey) { this.my_pubkey = my_pubkey; Reset(); this.action_request = new TimeoutAction(CreateResponse, TimeSpan.FromSeconds(Blockchain.SecondsPerBlock), () => NoncePieces.Count > Miners.Length * (2.0 / 3.0), () => NoncePieces.Count == Miners.Length - 1); }
public TimeoutActionEventArgs(CommandType command, TimeoutAction action = TimeoutAction.Wait) { Command = command; Action = action; }
private async Task <bool> AttemptAuthenticationAsync() { await this.profileData.LoadAsync(); if (this.profileData.Account == null) { return(false); } this.apiClient.Credentials = this.profileData.Account; // Check network status. if (NetworkStatusManager.Current.CurrentConnectionType != NetworkConnectionType.Disconnected || NetworkStatusManager.Current.CurrentConnectionType != NetworkConnectionType.Unknown) { var profile = await this.TestApiEndpointAsync(); if (profile == null) { // Attempt refresh token exchange. var exchangeErrored = false; try { await this.apiClient.ExchangeRefreshTokenAsync(); } catch (ApiException aex) { EventLogger.Current.WriteWarning(aex.ToString()); exchangeErrored = true; } catch (Exception ex) { #if DEBUG System.Diagnostics.Debug.WriteLine(ex.ToString()); #endif exchangeErrored = true; } if (exchangeErrored) { await this.apiClient.LogOutAsync(); return(false); } profile = await TimeoutAction.ExecuteAsync(this.TestApiEndpointAsync()); if (profile == null) { await this.apiClient.LogOutAsync(); await this.profileData.ClearAsync(); await MessageDialogManager.Current.ShowAsync( "Profile error", "There seems to be an issue getting your MVP profile."); return(false); } await this.profileData.SetProfileAsync(profile); } else { await this.profileData.SetProfileAsync(profile); } } await this.profileData.SetAccountAsync(this.apiClient.Credentials); return(true); }
public async Task <StateResponse> Command(CommandConversation conversation, Func <TimeoutAction> timeoutCallback, bool restartKeepaliveOnSuccess = true, int timeoutMs = CommandTimeoutMs) { if (m_runningCommand != null) { CommandType commandType = conversation.RequestData.Command; Log.Info("A command is already running: {commandType}", commandType); throw new InvalidOperationException($"A command is already running {commandType}"); } m_cancellationTokenSource.Cancel(); var retry = false; StateResponse result = null; while (true) { try { if (retry || m_runningCommand == null) { retry = false; m_runningCommand = m_coreLink.Request(conversation, timeoutMs); } result = await m_runningCommand.ConfigureAwait(false); } catch (TaskTimeoutException <StateResponse> ex) { TimeoutAction timeoutAction = timeoutCallback(); Log.Info("Command {command} timed out, {action} requested", conversation.RequestData.Command, timeoutAction); if (timeoutAction == TimeoutAction.Cancel) { break; } if (timeoutAction == TimeoutAction.Retry) { retry = true; } if (timeoutAction == TimeoutAction.Wait) { m_runningCommand = ex.OriginalTask.TimeoutAfter(CommandTimeoutMs); } continue; } catch (Exception ex) { Log.Error(ex, "Request failed"); m_runningCommand = null; RestartStateChecking(); throw; } Log.Debug("Successful command {command}", conversation.RequestData.Command); break; } m_runningCommand = null; if (restartKeepaliveOnSuccess) { RestartStateChecking(); } return(result); }
public virtual void RunScript(List <RemoteCommand> commands, bool isDryRun) { if (_wfp.RunAs != null && _wfp.RunUsing == RunUsingProtocolType.WMI) { foreach (RemoteCommand command in commands) { command.args = BuildRunAsCommand(_wfp.Servers[0], command.command + " " + command.args, _wfp.RunAs.Protocol); command.command = "winrs"; } } long timeoutValue = 0; bool killProcess = false; TimeoutAction actionOnTimeout = TimeoutAction.Continue; if (_wfp.Timeout != null) { timeoutValue = _wfp.Timeout.Value; if (!(String.IsNullOrWhiteSpace(_wfp.Timeout.KillProcess))) { try { killProcess = Boolean.Parse(_wfp.Timeout.KillProcess); } catch (Exception) { } } if (killProcess) { actionOnTimeout = TimeoutAction.Error; // Set Default Action When Kill Specified to "Error" } if (!(String.IsNullOrWhiteSpace(_wfp.Timeout.ActionOnTimeout))) { try { actionOnTimeout = ((TimeoutAction)Enum.Parse(typeof(TimeoutAction), _wfp.Timeout.ActionOnTimeout)); } catch (Exception) { } } } bool errorOccured = false; if (_wfp.RunUsing == RunUsingProtocolType.WMI) { Parallel.ForEach(commands, command => { Int32 exitCode = WMIUtil.RunCommand(command.command + " " + command.args, command.server, _wfp.WorkingDir, timeoutValue, killProcess, actionOnTimeout, OnStepProgress, command.callbackLabel, isDryRun); if (!(IsValidExitCode(exitCode))) { OnStepProgress(command.server, "ERROR - Invalid Exit Code [" + exitCode + "] Was Returned."); errorOccured = true; } } ); } else if (_wfp.RunUsing == RunUsingProtocolType.ProcessStart) { Parallel.ForEach(commands, command => { Int32 exitCode = LocalProcessUtil.RunCommand(command.command, command.args, _wfp.WorkingDir, timeoutValue, actionOnTimeout, OnStepProgress, command.callbackLabel, isDryRun); if (!(IsValidExitCode(exitCode))) { OnStepProgress(command.server, "ERROR - Invalid Exit Code [" + exitCode + "] Was Returned."); errorOccured = true; } } ); } else { throw new Exception("Protocol [" + _wfp.RunUsing + "] Is Not Yet Implemented."); } if (errorOccured) { throw new Exception("Invalid Exit Codes Returned."); } }
private void OnLoaded(object sender, RoutedEventArgs e) { _progressThread = new TimeoutAction(DrawProgressBar, 25); PatcherService.RegisterControl(this); }
private void OnDispatcherShutdownStarted(object sender, EventArgs e) { _progressThread.Dispose(); _progressThread = null; PatcherService.UnregisterControl(this); }
public FormVideoTalkViewModel( IDeviceDataService _dataService, IDialogService dialogService) { this._dialogService = dialogService; this._dataService = _dataService; VideoTalkService.Instance.ReceivedIncomingCallEvent += _videoTalkService_ReceivedIncomingCallEvent; VideoTalkService.Instance.AcceptedIncomingCallEvent += _videoTalkService_AcceptedIncomingCallEvent; VideoTalkService.Instance.ReceivedNewVideoMessageEvent += _videoTalkService_ReceivedNewVideoMessageEvent; VideoTalkService.Instance.VideoMessageHasBeenReadEvent += _videoTalkService_VideoMessageHasBeenReadEvent; VideoTalkService.Instance.ReceivedHangUpEvent += _videoTalkService_ReceivedHangUpEvent; VideoTalkService.Instance.ReceivedOutgoingCallTimeoutEvent += _videoTalkService_ReceivedOutgoingCallTimeoutEvent; //this._videoTalkService = videoTalkService; this._RingTimeoutAction = new TimeoutAction(() => { CallState callState; lock (m_SyncRoot) { callState = this.CallState; } switch (callState) { case CallState.ReceivedIncomingCall: Application.Current.Dispatcher.Invoke(() => { this.HangUpCommand.Execute(null); }); break; case CallState.Calling: Application.Current.Dispatcher.Invoke(() => { this.HangUpCommand.Execute(null); Messenger.Default.Send(new ReceivedOutgoingCallTimeoutEvent()); }); break; } }); this._TalkTimeoutAction = new TimeoutAction(() => { CallState callState; lock (m_SyncRoot) { callState = this.CallState; } switch (callState) { case CallState.AcceptedIncomingCall: Application.Current.Dispatcher.Invoke(() => { this.HangUpCommand.Execute(null); }); break; case CallState.WatchingLiveVideo: Application.Current.Dispatcher.Invoke(() => { this.StopWatchLiveVideoCommand.Execute(null); }); break; } }); }