private static void Transfer(Socket socket) { int txDataLen = random.Next(maxDataLen); int rxDataLen; TransferHeaders(socket, txDataLen, out rxDataLen); // System.Console.WriteLine ("txDataLen="+txDataLen+" rxDataLen="+rxDataLen); socket.Blocking = false; socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); // Disable the Nagle algorithm for send coalescing. int txPos = 0; int rxPos = 0; while (txPos < txDataLen || rxPos < rxDataLen) { // System.Console.WriteLine ("txPos="+txPos+"/"+txDataLen+" rxPos="+rxPos+"/"+rxDataLen); int txReqLen = Math.Min(txDataLen - txPos, 1 + random.Next(maxBlockLen)); int txTrLen = Send(socket, txReqLen); txPos += txTrLen; int rxReqLen = Math.Min(rxDataLen - rxPos, maxBlockLen); int rxTrLen = Receive(socket, rxReqLen); rxPos += rxTrLen; if (random.Next(1000) == 0) { Thread.Sleep(50); } else if ((txTrLen < txReqLen && rxTrLen < rxReqLen) || random.Next(50) == 0) { Thread.Sleep(1); } } socket.Shutdown(SocketShutdown.Both); }
/// <summary> /// Calls a function with no return value, retrying if necessary. /// </summary> public static void callVoidFunction(Action fn) { int numTries = 20; int intervalMS = 50; // We will try to call the function a number of times... for (int i = 0; i < numTries; ++i) { try { // We call the function passed in, and return // if it succeeds... fn(); return; } catch (COMException ex) { if ((uint)ex.ErrorCode == 0x8001010a) // RPC_E_SERVERCALL_RETRYLATER: The message filter indicated that the application is busy. { // Server is busy - we sleep for a short while, and then try again... Thread.Sleep(intervalMS); } else { throw ex; } } } throw new Exception(String.Format("'callVoidFunction' failed to call function after {0} tries.", numTries)); }
private static void LaunchAndVerifyDebug(VisualStudioApp app, int port, string textInResponse) { EndToEndLog("Building"); app.Dte.Solution.SolutionBuild.Build(true); EndToEndLog("Starting debugging"); if (!System.Threading.Tasks.Task.Run(() => app.Dte.Debugger.Go(false)).Wait(TimeSpan.FromSeconds(10))) { Assert.Fail("Run was interrupted by dialog"); } EndToEndLog("Debugging started"); string text = string.Empty; int retries; try { for (retries = 100; retries > 0 && (app.Dte.Debugger.CurrentMode != EnvDTE.dbgDebugMode.dbgRunMode || !IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().Any(p => p.Port == port)); --retries) { Thread.Sleep(300); } if (retries > 0) { EndToEndLog("Active at http://localhost:{0}/", port); } else { EndToEndLog("Timed out waiting for http://localhost:{0}/", port); } text = WebDownloadUtility.GetString(new Uri(string.Format("http://localhost:{0}/", port))); } finally { app.Dte.Debugger.Stop(); } EndToEndLog("Response from http://localhost:{0}/", port); EndToEndLog(text); Assert.IsTrue(text.Contains(textInResponse), text); for (retries = 20; retries > 0 && (app.Dte.Debugger.CurrentMode != EnvDTE.dbgDebugMode.dbgRunMode || !IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().All(p => p.Port != port)); --retries) { Thread.Sleep(500); } if (retries > 0) { EndToEndLog("Debugging stopped"); } else { EndToEndLog("Timed out waiting for debugging to stop"); } }
private void ff(Tracer.Tracer tracer) { tracer.StartTrace(); f(tracer); f(tracer); f(tracer); Thread.Sleep(100); tracer.StopTrace(); }
internal static void WaitForMode(VisualStudioApp app, dbgDebugMode mode) { for (int i = 0; i < 30 && app.Dte.Debugger.CurrentMode != mode; i++) { Thread.Sleep(1000); } Assert.AreEqual(mode, app.Dte.Debugger.CurrentMode); }
private static void WaitForMode(dbgDebugMode mode) { for (int i = 0; i < 300 && VsIdeTestHostContext.Dte.Debugger.CurrentMode != mode; i++) { Thread.Sleep(100); } Assert.AreEqual(VsIdeTestHostContext.Dte.Debugger.CurrentMode, mode); }
private static void WaitForDebugOutput(Predicate <string> condition) { for (int i = 0; i < 50 && !condition(GetOutputWindowDebugPaneText()); i++) { Thread.Sleep(100); } Assert.IsTrue(condition(GetOutputWindowDebugPaneText())); }
/// <summary> /// Start experimental instance of Visual Studio. This will be killed on cleanup, except if a debugger is attached (in which case it can reuse the existing instance). /// </summary> private static (DTE, Process, bool) InitDTE() { bool killVisualStudioProcessDuringTearDown; var visualStudioPath = VSLocator.VisualStudioPath; Process process; // First, we try to check if an existing instance was launched var searcher = new ManagementObjectSearcher($"select CommandLine,ProcessId from Win32_Process where ExecutablePath='{visualStudioPath.Replace(@"\", @"\\")}' and CommandLine like '% /RootSuffix Exp'"); var retObjectCollection = searcher.Get(); var result = retObjectCollection.Cast <ManagementObject>().FirstOrDefault(); if (result != null) { var processId = (uint)result["ProcessId"]; process = Process.GetProcessById((int)processId); killVisualStudioProcessDuringTearDown = false; } else { var psi = new ProcessStartInfo { FileName = visualStudioPath, WorkingDirectory = Path.GetDirectoryName(visualStudioPath), Arguments = StartArguments, UseShellExecute = false, }; process = Process.Start(psi); if (process == null) { throw new InvalidOperationException("Could not start Visual Studio instance"); } // Since we are the one starting it, let's close it when we are done // (except if a debugger is attached, we assume developer want to iterate several time on it and will exit Visual Studio himself) killVisualStudioProcessDuringTearDown = !Debugger.IsAttached; } // Wait for 60 sec for (int i = 0; i < 60; ++i) { if (process.HasExited) { throw new InvalidOperationException($"Visual Studio process {process.Id} exited before we could connect to it"); } var matchingDte = VisualStudioDTE.GetDTEByProcess(process.Id); if (matchingDte != null) { return(matchingDte, process, killVisualStudioProcessDuringTearDown); } Thread.Sleep(1000); } throw new InvalidOperationException($"Could not find the Visual Studio DTE for process {process.Id}, or it didn't start in time"); }
public void Test3() { Tracer.Tracer tracer = new Tracer.Tracer(); Thread thread = new Thread(new ParameterizedThreadStart(f1)); thread.Start(tracer); ff(tracer); Thread.Sleep(100); Assert.AreEqual(2, tracer.GetTraceResult().Threads.Length); }
/// IDispose pattern lets us clean up our stuff! protected override void Dispose(bool disposing) { if (Ticker != null && Ticker.IsAlive) { Thread.Sleep(TickPeriod + TickPeriod); if (Ticker.IsAlive) { Logging.WriteLine("WARNING: Force aborting Ticker thread"); Ticker.Abort(); } } base.Dispose(disposing); // Clean up singleton instance PrivateInstance = null; CommandLineEditor = null; StartupProjectSelector = null; BatchBuilder = null; QuickBuilder = null; if (CompileSingleFile != null) { CompileSingleFile.Dispose(); CompileSingleFile = null; } // No longer want solution events if (SolutionEventsHandle != 0) { SolutionManager.UnadviseSolutionEvents(SolutionEventsHandle); SolutionEventsHandle = 0; } SolutionManager = null; // No longer want selection events if (SelectionEventsHandle != 0) { SelectionManager.UnadviseSelectionEvents(SelectionEventsHandle); SelectionEventsHandle = 0; } SelectionManager = null; // No longer want update solution events if (UpdateSolutionEventsHandle != 0) { SolutionBuildManager.UnadviseUpdateSolutionEvents(UpdateSolutionEventsHandle); UpdateSolutionEventsHandle = 0; } SolutionBuildManager = null; Logging.WriteLine("Closing UnrealVS extension"); Logging.Close(); }
public static void ReplaceExisting() { Log.Always("Attempting to replace another beagrepd."); do { ShutdownRequest request = new ShutdownRequest(); Logger.Log.Info("Sending Shutdown"); request.Send(); // Give it a second to shut down the messaging server Thread.Sleep(1000); } while (!StartServer()); }
private static string WaitForDebugOutput(VisualStudioApp app, Predicate <string> condition) { var uiThread = app.ServiceProvider.GetUIThread(); var text = uiThread.Invoke(() => app.GetOutputWindowText("Debug")); for (int i = 0; i < 50 && !condition(text); i++) { Thread.Sleep(100); text = uiThread.Invoke(() => app.GetOutputWindowText("Debug")); } Assert.IsTrue(condition(text)); return(text); }
public static ErrorItems Build() { Dte.ExecuteCommand("Build.BuildSelection", String.Empty); // Wait for the build to be completed while (Dte.Solution.SolutionBuild.BuildState != vsBuildState.vsBuildStateDone) { SystemThread.Sleep(100); } var errors = GetErrors(); return(errors); }
void playSound(int freq, int duration) { var sampleRate = 8000; var generatedSnd = genTone(sampleRate, freq, (duration * sampleRate) / 1000); AudioTrack audioTrack = new AudioTrack(Stream.Music, sampleRate, ChannelConfiguration.Mono, Encoding.Pcm16bit, generatedSnd.Length, AudioTrackMode.Stream); audioTrack.Play(); audioTrack.Write(generatedSnd, 0, generatedSnd.Length); while (audioTrack.PlayState == PlayState.Playing) { Thread.Sleep(10); } audioTrack.Stop(); }
public ITreeNode WaitForItemRemoved(params string[] path) { ITreeNode item = null; for (int i = 0; i < 400; i++) { item = FindItem(path); if (item == null) { break; } Thread.Sleep(25); } return(item); }
public void WebProjectCreateVirtualEnvOnNew() { using (var app = new VisualStudioApp()) { var t = Task.Run(() => app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.FlaskWebProjectTemplate, TestData.GetTempPath(), "WebProjectCreateVirtualEnvOnNew", suppressUI: false )); using (var dlg = new AutomationDialog(app, AutomationElement.FromHandle(app.WaitForDialog(t)))) { // Create a virtual environment dlg.ClickButtonAndClose("CommandLink_1000", nameIsAutomationId: true); } using (var dlg = new AutomationDialog(app, AutomationElement.FromHandle(app.WaitForDialog(t)))) { dlg.ClickButtonByAutomationId("Create"); dlg.ClickButtonAndClose("Close", nameIsAutomationId: true); } var project = TaskExt.WaitAndUnwrapExceptions(t); var provider = project.Properties.Item("InterpreterFactoryProvider").Value as MSBuildProjectInterpreterFactoryProvider; for (int retries = 20; retries > 0; --retries) { if (provider.IsProjectSpecific(provider.ActiveInterpreter)) { break; } Thread.Sleep(1000); } Assert.IsTrue(provider.IsProjectSpecific(provider.ActiveInterpreter), "Did not have virtualenv"); for (int retries = 60; retries > 0; --retries) { if (InterpreterExt.FindModules(provider.ActiveInterpreter, "flask").Any()) { break; } Thread.Sleep(1000); } AssertUtil.ContainsExactly( InterpreterExt.FindModules(provider.ActiveInterpreter, "flask"), "flask" ); } }
public static void LoggedIn(string Username, string Password, object obj, EventArgs args) { client = new TextTestClient(); client.LogInAndConnect(Username, Password); while (client.IsConnectedAndLoggedIn() == false) { Thread.Sleep(0); } playerOps = new PlayerOperations(); myWin = new Window("HistMMorpg Client"); //Create a label and put some text in it. tableLayout = new Table(5, 5, false); northEast = new Button("North East"); northWest = new Button("North West"); east = new Button("East"); west = new Button("West"); southEast = new Button("South East"); southWest = new Button("South West"); siege = new Button("Siege"); hire = new Button("Hire"); SetUpDirectionalButtonClicks(); SetUpOperationButtonClicks(); //Add the label to the form tableLayout.Attach(northEast, 0, 1, 0, 1); tableLayout.Attach(northWest, 1, 2, 0, 1); tableLayout.Attach(east, 0, 1, 1, 2); tableLayout.Attach(west, 1, 2, 1, 2); tableLayout.Attach(siege, 2, 3, 1, 2); tableLayout.Attach(southEast, 0, 1, 2, 3); tableLayout.Attach(southWest, 1, 2, 2, 3); tableLayout.Attach(hire, 2, 3, 0, 1); myWin.Add(tableLayout); /*ProtoPlayerCharacter player = playerOps.Profile (client); * profileTable = new ProfileTable (player.playerID, player.firstName + " " + player.familyName, player.ownedFiefs, player.location, player.armyID, Convert.ToString( player.purse)); * tableLayout.Attach (profileTable.getProfileLayout (), 3, 4, 1, 2); * ProtoFief fiefData = playerOps.FiefDetails (client); * fiefTable = new FiefTable (fiefData.fiefID, fiefData.owner, Convert.ToString (fiefData.industry), * fiefData.charactersInFief, fiefData.armies); * tableLayout.Attach (fiefTable.getProfileTable (), 3, 4, 2, 3);*/ //ProfileClickEvent (null, null); //FiefClickEvent (null, null); //Show Everything FiefClickEvent(obj, args); ProfileClickEvent(obj, args); myWin.ShowAll(); }
public void WebProjectCreateVirtualEnvOnNew() { using (var app = new PythonVisualStudioApp()) { var t = Task.Run(() => app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.FlaskWebProjectTemplate, TestData.GetTempPath(), "WebProjectCreateVirtualEnvOnNew", suppressUI: false )); using (var dlg = new AutomationDialog(app, AutomationElement.FromHandle(app.WaitForDialog(t)))) { // Create a virtual environment dlg.ClickButtonAndClose("CommandLink_1000", nameIsAutomationId: true); } using (var dlg = new AutomationDialog(app, AutomationElement.FromHandle(app.WaitForDialog(t)))) { dlg.ClickButtonByAutomationId("Create"); dlg.ClickButtonAndClose("Close", nameIsAutomationId: true); } var project = t.WaitAndUnwrapExceptions(); var contextProvider = app.ComponentModel.GetService <VsProjectContextProvider>(); for (int retries = 20; retries > 0; --retries) { if (contextProvider.IsProjectSpecific(project.GetPythonProject().ActiveInterpreter.Configuration)) { break; } Thread.Sleep(1000); } Assert.IsTrue(contextProvider.IsProjectSpecific(project.GetPythonProject().ActiveInterpreter.Configuration), "Did not have virtualenv"); for (int retries = 60; retries > 0; --retries) { if (project.GetPythonProject().ActiveInterpreter.FindModules("flask").Any()) { break; } Thread.Sleep(1000); } AssertUtil.ContainsExactly(project.GetPythonProject().ActiveInterpreter.FindModules("flask"), "flask"); } }
public void WebProjectInstallOnNew() { using (var app = new PythonVisualStudioApp()) { TaskExt.WaitAndUnwrapExceptions( Pip.Uninstall(app.ServiceProvider, app.InterpreterService.DefaultInterpreter, "bottle", false) ); var t = Task.Run(() => app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.BottleWebProjectTemplate, TestData.GetTempPath(), "WebProjectInstallOnNew", suppressUI: false )); using (var dlg = new AutomationDialog(app, AutomationElement.FromHandle(app.WaitForDialog(t)))) { // Install to active environment dlg.ClickButtonAndClose("CommandLink_1001", nameIsAutomationId: true); } var project = TaskExt.WaitAndUnwrapExceptions(t); var provider = project.Properties.Item("InterpreterFactoryProvider").Value as MSBuildProjectInterpreterFactoryProvider; Assert.AreSame(app.InterpreterService.DefaultInterpreter, provider.ActiveInterpreter); for (int retries = 60; retries > 0; --retries) { if (InterpreterExt.FindModules(provider.ActiveInterpreter, "bottle").Any()) { break; } Thread.Sleep(1000); } AssertUtil.ContainsExactly( InterpreterExt.FindModules(provider.ActiveInterpreter, "bottle"), "bottle" ); TaskExt.WaitAndUnwrapExceptions( Pip.Uninstall(app.ServiceProvider, app.InterpreterService.DefaultInterpreter, "bottle", false) ); } }
public void StartD2DInfo() { { try { //var d2dinfo = new UnixEndPoint("/tmp/d2dinfo"); //var d2dinfo = "songdebugmessage"; var d2dinfo = "linkstate"; //"d2dsignal"; server = new Socket(AddressFamily.Unix, SocketType.Stream, 0); server.Bind(new AbstractUnixEndPoint(d2dinfo)); server.Listen(50); Task.Run(() => { while (server != null) { try { var socket = server.Accept(); Thread.Sleep(1); byte[] buffer = new byte[100]; var readlen = 0; do { readlen = socket.Receive(buffer); if ((readlen > 4) && (readlen >= (4 + buffer[3]))) { Log.Info(TAG, "Got " + ASCIIEncoding.ASCII.GetString(buffer, 4, buffer[3])); } } while (readlen > 0); socket.Close(); } catch (Exception ex) { Log.Warn(TAG, ex.ToString()); Thread.Sleep(1000); } } }); } catch (Exception ex) { Log.Warn(TAG, ex.ToString()); } } }
/// <inheritdoc /> public void BringToFront() { Protect(() => { // Inspired from FxCop GUI implementation. Window window = dte.MainWindow; IntPtr hWnd = (IntPtr)window.HWnd; if (NativeMethods.IsIconic(hWnd)) { NativeMethods.ShowWindowAsync(hWnd, NativeConstants.SW_RESTORE); } NativeMethods.SetForegroundWindow(hWnd); Thread.Sleep(50); window.Activate(); window.Visible = true; }); }
/// <summary> /// Invokes specified invoker inside a loop with try-catch/everything and retries until reaches timeout or until each of the following is true: /// - The invoker does not throw exception. /// - If the additional condition delegate is specified, it must return true. /// </summary> /// <param name="invoker">The method to invoke</param> /// <param name="stopCondition">If specified, to break from the loop, it must be true. The condition delegate must not throw.</param> /// <param name="timeout">Timeout to stop retries after.</param> /// <returns>True on success, false on timeout.</returns> private bool InvokeWithRetry(MethodInvoker invoker, BoolMethodInvoker stopCondition, TimeSpan timeout) { Debug.Assert(invoker != null); Stopwatch timer = Stopwatch.StartNew(); bool hasTimedOut = true; try { do { bool isExceptionThrown = false; try { invoker.Invoke(); } catch { isExceptionThrown = true; } // If there was no exception, also check for stop condition. // Note: condition.Invoke() must not throw. If it throws, we also throw from here. if (!isExceptionThrown && (stopCondition == null || stopCondition.Invoke())) { hasTimedOut = false; break; } Thread.Sleep(RegistrySettings.BaseSleepDuration); // This is to prevent 100% CPU consumption. } while (timer.Elapsed < timeout); } finally { timer.Stop(); } return(!hasTimedOut); }
private static void LogMemoryUsage() { while (!Shutdown.ShutdownRequested) { SystemInformation.LogMemoryUsage(); int vm_rss = SystemInformation.VmRss; if (arg_heap_shot && arg_heap_shot_snapshots) { MaybeSendSigprof(vm_rss, GC.GetTotalMemory(false)); } if (vm_rss > 300 * 1024) { Logger.Log.Debug("VmRss too large --- shutting down"); Shutdown.BeginShutdown(); } Thread.Sleep(5000); } }
/// <summary> /// Tick loop on worker thread /// </summary> private void TickAsyncMain() { try { while (true) { if (bCancelTicker != 0) { return; } ThreadHelper.Generic.BeginInvoke(Tick); if (bCancelTicker != 0) { return; } Thread.Sleep(TickPeriod); } } catch (ThreadAbortException) { } }
/// <summary> /// Creates the application and starts it, returning the an instance (child of <see cref="Form"/>). /// </summary> public static ApplicationSimulator Create() { ApplicationSimulator instace_holder = null; var holder = new ManualResetEvent(false); var t = new Thread(() => Application.Run( instace_holder = new ApplicationSimulator(inst => { instace_holder = (ApplicationSimulator)inst; holder.Set(); } ))); t.SetApartmentState(ApartmentState.STA); t.IsBackground = true; t.Start(); _rewait: try { holder.WaitOne(); //wait for init. } catch { Thread.Sleep(5); goto _rewait; } return(instace_holder); }
/// <summary> /// Calls a function, retrying if necessary. /// </summary><remarks> /// DTE functions call into an instance of Visual Studio running in /// a separate process using COM interop. These calls can fail if /// Visual Studio is busy, and in these cases we get a COM exception. /// /// This function will retry calling the function if this happens, and /// will only fail if it has retried 20 times without success. /// /// You pass in the function - or property - to call usually as a /// lambda. For example, to get the projects.Count property you would /// call: /// /// int count = dteCall[int](() => (projects.Count)); /// /// (Note: replace the [] above with angle-brackets to specify the /// return type.) /// </remarks> public static T call <T>(Func <T> fn) { int numTries = 20; int intervalMS = 50; // We will try to call the function a number of times... for (int i = 0; i < numTries; ++i) { try { // We call the function passed in and return the result... return(fn()); } catch (COMException) { // We've caught a COM exception, which is most likely // a Server is Busy exception. So we sleep for a short // while, and then try again... Thread.Sleep(intervalMS); } } throw new Exception(String.Format("'call' failed to call function after {0} tries.", numTries)); }
private void AddNewDtoFileToProject(string fileName, string templateCode, List <string> nugetPackages = null) { nugetPackages = nugetPackages ?? new List <string>(); var project = VSIXUtils.GetSelectedProject() ?? VSIXUtils.GetSelectObject <ProjectItem>().ContainingProject; var path = VSIXUtils.GetSelectedProjectPath() ?? VSIXUtils.GetSelectedFolderPath(); string fullPath = Path.Combine(path, fileName); File.WriteAllText(fullPath, templateCode); try { // HACK avoid VS2015 Update 2 seems to detect file in use semi regularly. Thread.Sleep(50); var newDtoFile = project.ProjectItems.AddFromFile(fullPath); newDtoFile.Open(EnvDteConstants.vsViewKindCode); newDtoFile.Save(); } catch (Exception) {} try { foreach (var nugetPackage in nugetPackages) { AddNuGetDependencyIfMissing(project, nugetPackage); } } catch (Exception) {} try { project.Save(); } catch (Exception) {} }
public void ShowCallStackOnCodeMap(VisualStudioApp app, DotNotWaitOnNormalExit optionSetter) { var project = OpenDebuggerProjectAndBreak(app, "SteppingTest3.py", 2); app.Dte.ExecuteCommand("Debug.ShowCallStackonCodeMap"); // Got the CodeMap Graph displaying, but it may not have finished processing app.WaitForInputIdle(); var dgmlKind = "{295A0962-5A59-4F4F-9E12-6BC670C15C3B}"; Document dgmlDoc = null; for (int i = 1; i <= app.Dte.Documents.Count; i++) { var doc = app.Dte.Documents.Item(i); if (doc.Kind == dgmlKind) { dgmlDoc = doc; break; } } Assert.IsNotNull(dgmlDoc, "Could not find dgml document"); var dgmlFile = Path.GetTempFileName(); try { // Save to a temp file. If the code map is not ready, it // may have template xml but no data in it, so give it // some more time and try again. string fileText = string.Empty; for (int i = 0; i < 10; i++) { dgmlDoc.Save(dgmlFile); fileText = File.ReadAllText(dgmlFile); if (fileText.Contains("SteppingTest3")) { break; } Thread.Sleep(250); } // These are the lines of interest in the DGML File. If these match, the correct content should be displayed in the code map. List <string> LinesToMatch = new List <string>() { @"<Node Id=""\(Name=f @1 IsUnresolved=True\)"" Category=""CodeSchema_CallStackUnresolvedMethod"" Label=""f"">", @"<Node Id=""@2"" Category=""CodeSchema_CallStackUnresolvedMethod"" Label=""SteppingTest3 module"">", @"<Node Id=""ExternalCodeRootNode"" Category=""ExternalCallStackEntry"" Label=""External Code"">", @"<Link Source=""@2"" Target=""\(Name=f @1 IsUnresolved=True\)"" Category=""CallStackDirectCall"">", @"<Alias n=""1"" Uri=""Assembly=SteppingTest3"" />", @"<Alias n=""2"" Id=""\(Name="SteppingTest3 module" @1 IsUnresolved=True\)"" />" }; foreach (var line in LinesToMatch) { Assert.IsTrue(System.Text.RegularExpressions.Regex.IsMatch(fileText, line), "Expected:\r\n{0}\r\nsActual:\r\n{1}", line, fileText); } } finally { File.Delete(dgmlFile); } }
private static void MemoryAndIdleMonitorWorker() { int vmrss_original = SystemInformation.VmRss; const double max_idle_time = 30; // minutes const double threshold = 5.0; const int max_request_count = 0; int last_vmrss = 0; while (!Shutdown.ShutdownRequested) { double idle_time; idle_time = (DateTime.Now - last_activity).TotalMinutes; if (idle_time > max_idle_time && RemoteIndexerExecutor.Count > 0) { Logger.Log.Debug("No activity for {0:0.0} minutes, shutting down", idle_time); Shutdown.BeginShutdown(); return; } // Check resident memory usage int vmrss = SystemInformation.VmRss; double size = vmrss / (double)vmrss_original; if (last_vmrss != 0 && vmrss != last_vmrss) { Logger.Log.Debug("Helper Size: VmRSS={0:0.0} MB, size={1:0.00}, {2:0.0}%", vmrss / 1024.0, size, 100.0 * (size - 1) / (threshold - 1)); double increase = vmrss / (double)last_vmrss; if (heap_shot && increase > 1.20) { Log.Debug("Large memory increase detected. Sending SIGPROF to ourself."); Mono.Unix.Native.Syscall.kill(System.Diagnostics.Process.GetCurrentProcess().Id, Mono.Unix.Native.Signum.SIGPROF); } } last_vmrss = vmrss; if (size > threshold || (max_request_count > 0 && RemoteIndexerExecutor.Count > max_request_count)) { if (RemoteIndexerExecutor.Count > 0) { Logger.Log.Debug("Process too big, shutting down!"); Shutdown.BeginShutdown(); return; } else { // Paranoia: don't shut down if we haven't done anything yet Logger.Log.Debug("Deferring shutdown until we've actually done something."); Thread.Sleep(1000); } } else { Thread.Sleep(3000); } } }
public static bool StartupProcess() { // Profile our initialization Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // Fire up our server if (!StartServer()) { if (!arg_replace) { Logger.Log.Error("Could not set up the listener for beagrep requests. " + "There is probably another beagrepd instance running. " + "Use --replace to replace the running service"); Environment.Exit(1); } ReplaceExisting(); } // Set up out-of-process indexing LuceneQueryable.IndexerHook = new LuceneQueryable.IndexerCreator(RemoteIndexer.NewRemoteIndexer); Config config = Conf.Get(Conf.Names.DaemonConfig); // Initialize synchronization to keep the indexes local if PathFinder.StorageDir // is on a non-block device, or if BEAGREP_SYNCHRONIZE_LOCALLY is set if ((!SystemInformation.IsPathOnBlockDevice(PathFinder.StorageDir) && config.GetOption(Conf.Names.IndexSynchronization, true)) || Environment.GetEnvironmentVariable("BEAGREP_SYNCHRONIZE_LOCALLY") != null) { IndexSynchronization.Initialize(); } // Start the query driver. Logger.Log.Debug("Starting QueryDriver"); QueryDriver.Start(); // Start our battery monitor so we can shut down the // scheduler if needed. BatteryMonitor.Init(); bool initially_on_battery = !BatteryMonitor.UsingAC && !config.GetOption(Conf.Names.IndexOnBattery, false); // Start the Global Scheduler thread if (!arg_disable_scheduler) { if (!initially_on_battery) { Logger.Log.Debug("Starting Scheduler thread"); Scheduler.Global.Start(); } else { Log.Debug("Beagrep started on battery, not starting scheduler thread"); } } // Start our Inotify threads Inotify.Start(); // Test if the FileAdvise stuff is working: This will print a // warning if not. The actual advice calls will fail silently. FileAdvise.TestAdvise(); #if ENABLE_AVAHI zeroconf = new Beagrep.Daemon.Network.Zeroconf(); #endif Conf.WatchForUpdates(); stopwatch.Stop(); Logger.Log.Debug("Daemon initialization finished after {0}", stopwatch); SystemInformation.LogMemoryUsage(); if (arg_indexing_test_mode) { Thread.Sleep(1000); // Ugly paranoia: wait a second for the backends to settle. Logger.Log.Debug("Running in indexing test mode"); Scheduler.Global.EmptyQueueEvent += OnEmptySchedulerQueue; Scheduler.Global.Add(null); // pulse the scheduler } return(false); }