Example #1
0
        public Server(MainForm form)
        {
            this.form = form;

            try {
                database = new Database(this);

                gameServers = database.GetAllGameServers();
                LinkProcesses(gameServers);

                registrationAutomation = new RegistrationAutomation(this);

                form.InitializeGameServerPanel(gameServers);

                socketListener = new SocketListener(this, 33333); // 33333
                socketListener.SocketMessageReceived += OnMessageReceive;

                performanceMonitor = new PerformanceMonitor();
                performanceMonitor.OnPerformanceTick += OnPerformanceTick;

                string path = AppDomain.CurrentDomain.BaseDirectory + @"\exceptions.txt";
                if(!File.Exists(path)) {
                    File.CreateText(path);
                }

                AppDomain.CurrentDomain.UnhandledException += UnhandledException;
            }
            catch (Exception ex) {
                form.Output("INIT ERROR: " + ex.Message);
            }
        }
Example #2
0
        public void DbCommandLogger_PerformanceMonitorNotify_Demo()
        {
            // Normally this would be a singleton across all scope
            PerformanceMonitor perfMonitor = new PerformanceMonitor();
            perfMonitor.Description = "Demonstration of Cyclops PerfMon";

            // Wire up the notification to perf monitor
            DbCommandLogger.PerformanceMonitorNotify += (sender, p) =>
                                                           {
                                                               // Convert Cyclops point to consuming solutions perf capture tool..in this case a Kraken library
                                                               var perfPoint = new PerformancePoint(p.CommandText, p.Start, p.End - p.Start);

                                                               perfMonitor.LogPoint(perfPoint);
                                                           };

            // Do some work
            var customerRepo = CustomerRepositoryTest.GetCustomerRepository();
            for (int i = 0; i < 10; i++)
            {
                var customer = CustomerRepositoryTests.GetUnpersistedCustomer();
                customer.FirstName = i.ToString();
                customerRepo.Save(customer);
            }

            // Emit to logs from in perf mon so we can direct to a specific log file via namespace
            perfMonitor.EmitSummary();

            // Tear down
            DbCommandLogger.PerformanceMonitorNotify = null;
        }
        public void Check(PerformanceMonitor pm, int cpuThreshold, int memoryThreshold)
        {
            if (_measureMode == MeasureMode.HighCpu || _measureMode == MeasureMode.Both)
            {
                var cpuUsage = pm.GetCurrentCpuUsage();
                Console.WriteLine("CPU usage: {0}%", cpuUsage);

                if (cpuUsage >= cpuThreshold)
                {
                    _highCpuDuration++;
                }
                else
                {
                    _highCpuDuration = 0;
                }
            }

            if (_measureMode == MeasureMode.HighCpu || _measureMode == MeasureMode.Both)
            {
                var memoryUsage = pm.GetCurrentMemoryUsage();
                Console.WriteLine("Memory usage: {0}%", memoryUsage);

                if (memoryUsage >= memoryThreshold)
                {
                    _highMemoryDuration++;
                }
                else
                {
                    _highMemoryDuration = 0;
                }
            }

            BeepOnHighUsage();
        }
        public void ResetMonitor()
        {
            long defaultTotal = 100;

            if (Monitor != null)
            {
                defaultTotal = Monitor.Total;
            }

            Monitor = new PerformanceMonitor(defaultTotal);
        }
Example #5
0
        public BasicGameHost()
        {
            InputMonitor = new PerformanceMonitor(InputClock)
            {
                HandleGC = false
            };
            UpdateMonitor = new PerformanceMonitor(UpdateClock);
            DrawMonitor   = new PerformanceMonitor(DrawClock);

            Environment.CurrentDirectory = Path.GetDirectoryName(FullPath);
        }
Example #6
0
        /// <summary>
        /// The main constructor. It expects an `ISnippets` instance that takes care
        /// of compiling and keeping track of the code Snippets provided by users.
        /// </summary>
        public IQSharpEngine(
            IShellServer shell,
            IOptions <KernelContext> context,
            ILogger <IQSharpEngine> logger,
            IServiceProvider services,
            IConfigurationSource configurationSource,
            PerformanceMonitor performanceMonitor,
            IShellRouter shellRouter,
            IEventService eventService,
            IMagicSymbolResolver magicSymbolResolver,
            IReferences references
            ) : base(shell, shellRouter, context, logger, services)
        {
            this.performanceMonitor = performanceMonitor;
            performanceMonitor.Start();

            this.Snippets        = services.GetService <ISnippets>();
            this.SymbolsResolver = services.GetService <ISymbolResolver>();
            this.MagicResolver   = magicSymbolResolver;

            RegisterDisplayEncoder(new IQSharpSymbolToHtmlResultEncoder());
            RegisterDisplayEncoder(new IQSharpSymbolToTextResultEncoder());
            RegisterDisplayEncoder(new TaskStatusToTextEncoder());
            RegisterDisplayEncoder(new StateVectorToHtmlResultEncoder(configurationSource));
            RegisterDisplayEncoder(new StateVectorToTextResultEncoder(configurationSource));
            RegisterDisplayEncoder(new DataTableToHtmlEncoder());
            RegisterDisplayEncoder(new DataTableToTextEncoder());
            RegisterDisplayEncoder(new DisplayableExceptionToHtmlEncoder());
            RegisterDisplayEncoder(new DisplayableExceptionToTextEncoder());
            RegisterDisplayEncoder(new DisplayableHtmlElementEncoder());

            RegisterJsonEncoder(
                JsonConverters.AllConverters
                .Concat(AzureClient.JsonConverters.AllConverters)
                .ToArray());

            RegisterSymbolResolver(this.SymbolsResolver);
            RegisterSymbolResolver(this.MagicResolver);

            RegisterPackageLoadedEvent(services, logger, references);

            // Handle new shell messages.
            shellRouter.RegisterHandlers <IQSharpEngine>();

            // Report performance after completing startup.
            performanceMonitor.Report();
            logger.LogInformation(
                "IQ# engine started successfully as process {Process}.",
                Process.GetCurrentProcess().Id
                );


            eventService?.TriggerServiceInitialized <IExecutionEngine>(this);
        }
Example #7
0
        private void ExecutePerformanceStudy(string testConfigurationFileName, bool shouldPersist)
        {
            PerformanceMonitor performanceMonitor = new PerformanceMonitor(InstanceToTrack.Global);
            // int maxPossibleCops = int.MaxValue / 100;
            int maxPossibleCops = 1000;

            ZppConfiguration.CacheManager.ReadInTestConfiguration(testConfigurationFileName);
            TestConfiguration testConfiguration =
                ZppConfiguration.CacheManager.GetTestConfiguration();
            int customerOrderCount = ZppConfiguration.CacheManager.GetTestConfiguration()
                                     .CustomerOrderPartQuantity;
            int customerOrderCountOriginal = customerOrderCount;
            int elapsedMinutes             = 0;
            int elapsedSeconds             = 0;
            int maxTime = 5;
            int cycles  = testConfiguration.SimulationMaximumDuration /
                          testConfiguration.SimulationInterval;

            string performanceLogLastCycles = "[";

            // n cycles here each cycle create & plan configured CustomerOrderPart
            while (customerOrderCount <= maxPossibleCops && elapsedMinutes < 5)
            {
                InitThisTest(testConfigurationFileName);

                IZppSimulator zppSimulator = new ZppSimulator.impl.ZppSimulator();
                performanceMonitor.Start();

                zppSimulator.StartPerformanceStudy(shouldPersist);
                performanceMonitor.Stop();
                if (performanceLogLastCycles.Length > 1)
                {
                    performanceLogLastCycles += ",";
                }
                performanceLogLastCycles += "{" + performanceMonitor.ToString();
                long currentMemoryUsage = Process.GetCurrentProcess().WorkingSet64;
                performanceLogLastCycles +=
                    $"\"CurrentMemoryUsage\": \"{currentMemoryUsage}\"" +
                    Environment.NewLine;
                performanceLogLastCycles += "}" + Environment.NewLine;

                customerOrderCount += customerOrderCountOriginal;
                testConfiguration.CustomerOrderPartQuantity = customerOrderCount;
            }
            // just for correct log name
            customerOrderCount -= customerOrderCountOriginal;
            testConfiguration.CustomerOrderPartQuantity = customerOrderCount;

            performanceLogLastCycles += "]";
            string logType = $"_{testConfiguration.Name}_cycles_{cycles}_COs_{testConfiguration.CustomerOrderPartQuantity}_lastCycles";

            ;
            DebuggingTools.WritePerformanceLog(performanceLogLastCycles, logType);
        }
        public void AppendComment()
        {
            var comment = "this is my comment";

            using (var perf = new PerformanceMonitor())
            {
                Assert.IsNull(perf.Content, "Content should be null");
                perf.Append(comment);
                Assert.AreEqual <string>(comment, perf.Content);
            }
        }
Example #9
0
        /// <summary>
        /// Loads test player statistics data
        /// </summary>
        private void LoadTestPlayerStatistic()
        {
            using (var perfScope = new PerformanceMonitor("ReportCreatorTests.LoadTestPlayerStatistic"))
            {
                playerStatisticDictionary = new Dictionary <string, List <Playerstatistic> >();

                PlayerStatisticsFiles.ForEach(file =>
                {
                    playerStatisticDictionary.Add(file, DataServiceHelper.GetPlayerStatisticFromFile(file));
                });
            }
        }
Example #10
0
        public DeviceContext(IntPtr handle, int backBufferWidth, int backBufferHeight, bool fullScreen, bool verticalSync)
        {
            PerformanceMonitor = new PerformanceMonitor();

            _formHandle            = handle;
            PresentationParameters = new PresentParameters()
            {
                BackBufferFormat       = Format.X8R8G8B8,
                BackBufferCount        = 1,
                BackBufferWidth        = backBufferWidth,
                BackBufferHeight       = backBufferHeight,
                MultiSampleType        = MultisampleType.None,
                SwapEffect             = SwapEffect.Discard,
                EnableAutoDepthStencil = true,
                AutoDepthStencilFormat = Format.D24S8,
                PresentFlags           = PresentFlags.DiscardDepthStencil,
                PresentationInterval   = PresentInterval.Immediate,
                Windowed           = !fullScreen,
                DeviceWindowHandle = _formHandle
            };

            try
            {
                Direct3D library = new Direct3D();

                if (library.AdapterCount == 0)
                {
                    throw new Exception("Unable to find an appropriate Direct3D adapter.");
                }

                AdapterDetails     adapterDetails     = library.GetAdapterIdentifier(0);
                AdapterInformation adapterInformation = library.Adapters[0];

                _device   = new Device(library, 0, DeviceType.Hardware, _formHandle, CreateFlags.HardwareVertexProcessing, PresentationParameters);
                _viewport = _device.Viewport;

                _capabilities = _device.Capabilities;

                Tracer.Info("Adapter: {0}", adapterDetails.DeviceName);
                Tracer.Info("Driver: {0}, v{1}", adapterDetails.Driver, adapterDetails.DriverVersion);
                Tracer.Info("Max Texture Size: {0}x{1}", _capabilities.MaxTextureWidth, _capabilities.MaxTextureHeight);
                Tracer.Info("Max Texture Repeat: {0}", _capabilities.MaxTextureRepeat);
                Tracer.Info("Max Texture Aspect Ratio: {0}", _capabilities.MaxTextureAspectRatio);
                Tracer.Info("Texture Size Options: {0}", _capabilities.TextureCaps);
            }
            catch (Exception e)
            {
                Tracer.Error(e);
                return;
            }

            _vertexDeclarationBuilder = new VertexDeclarationBuilder(this);
        }
Example #11
0
        static Program()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            s_mainWindow          = new MainWindow();
            s_singleInstanceMutex = InterprocessLock.GetNamedMutex();
            s_clients             = new Lazy <IHubConnectionContext <dynamic> >(() => GlobalHost.ConnectionManager.GetHubContext <DataHub>().Clients);
            Global             = MainWindow.Model.Global;
            PerformanceMonitor = new PerformanceMonitor();
            MainWindow.CheckPhasorTypesAndMappings();
        }
        public void HandleEndRequest_Stopwatch_Tests()
        {
            // setup for tests
            HttpContextBase    context = new MockHttpContext();
            PerformanceMonitor pm      = new PerformanceMonitor();

            pm.HandleBeginRequest(context);
            pm.HandleEndRequest(context);

            // Stopwatch tests
            Post_Stopwatch_Tests(context, "request_timer");
        }
        public void HandlePostRequestHandler_Stopwatch_Tests()
        {
            // setup for tests
            HttpContextBase    context = new MockHttpContext();
            PerformanceMonitor pm      = new PerformanceMonitor();

            pm.HandlePreRequestHandler(context);
            pm.HandlePostRequestHandler(context);

            // Stopwatch tests
            Post_Stopwatch_Tests(context, "handler_timer");
        }
        public void HandleBeginRequest_HttpFilter_Tests()
        {
            // setup for tests
            HttpContextBase    context = new MockHttpContext();
            PerformanceMonitor pm      = new PerformanceMonitor();

            pm.HandleBeginRequest(context);

            // HttpFilter tests
            Assert.IsNotNull(context.Response.Filter);
            Assert.IsTrue(context.Response.Filter.GetType() == typeof(MonitoringFilter));
        }
Example #15
0
 public void AppendStringFormatComment()
 {
     using (PerformanceMonitor perf = new PerformanceMonitor())
     {
         string comment = "this is my comment";
         Assert.IsNull(perf.Content, "Content should be null");
         perf.Append("{0}:{0}", comment);
         Assert.AreEqual <string>(comment + ':' + comment, perf.Content);
         Thread.Sleep(5);
         Assert.IsTrue(0 < perf.Duration.Ticks, "Duration In Ticks should be set");
     }
 }
Example #16
0
        public void PerformanceMonitorGetsDataFromRegistry()
        {
            // ARRANGE
            var perfMon = new PerformanceMonitor();

            // ACT
            byte[] data = perfMon.GetData("230");
            perfMon.Close();

            // ASSERT
            Assert.IsTrue(data.Length > 0);
        }
 void Awake()
 {
     if (performanceMonitor == null)
     {
         performanceMonitor = GameObject.Find("PerformanceMonitor").GetComponent <PerformanceMonitor>();
     }
     for (int i = 0; i < numberOfSpawn; i++)
     {
         Instantiate(spawnedObject, new Vector2(Random.Range(-10f, 10f), Random.Range(-5.5f, 5.5f)), transform.rotation);
         //Instantiate(spawnedObject, new Vector3(Random.Range(100f, 1000f), Random.Range(-5.5f, 5.5f), 5f), transform.rotation);
         performanceMonitor.Increase();
     }
 }
Example #18
0
        public GameThread(Action onNewFrame, string threadName)
        {
            this.onNewFrame = onNewFrame;
            Thread          = new Thread(runWork)
            {
                Name         = threadName,
                IsBackground = true,
            };

            Clock     = new ThrottledFrameClock();
            Monitor   = new PerformanceMonitor(Clock, Thread, StatisticsCounters);
            Scheduler = new Scheduler(null, Clock);
        }
Example #19
0
        public IEnumerable <MessageDisplay> SelectMessages(LogQuery query)
        {
            Contract.Requires <ArgumentNullException>(null != query);
            Contract.Requires <ArgumentOutOfRangeException>(Guid.Empty != query.ApplicationIdentifier, "Application Identifier is empty.");

            Contract.Ensures(Contract.Result <IEnumerable <MessageDisplay> >() != null);

            using (new PerformanceMonitor())
            {
                query.Initialize();
                var start = query.From.Value;
                var end   = query.To.Value;

                var list = new List <MessageDisplay>();

                if (query.IsUnique)
                {
                    var item = this.messageTable.Get <MessageDisplay, MessageData>(query.PartitionKey, query.RowKey);
                    if (null != item)
                    {
                        list.Add(item);
                    }

                    return(list);
                }
                else if (start < DateTime.UtcNow.AddHours(-6))
                {
                    var history = this.Get <MessageDisplay>(Message21DaysFormat.FormatWithCulture(query.PartitionKey));

                    if (null != history)
                    {
                        list.AddRange(history.Items);
                        start = history.MaximumDate.HasValue ? history.MaximumDate.Value : start;
                    }
                }

                if (start < end)
                {
                    using (var perf = new PerformanceMonitor())
                    {
                        perf.Append("Pulling from table storage.");
                        var results = this.messageTable.Query <MessageData>(query);
                        var temp    = results.AsParallel().ToList().Select(d => d.Convert());
                        perf.Append(" {0} pulled from table.", temp.Count());
                        list.AddRange(temp);
                    }
                }

                return(query.Filter <MessageDisplay>(list));
            }
        }
Example #20
0
        private async Task Process(string[] files)
        {
            var monitor = new PerformanceMonitor(files.Length);

            using (Observable.Interval(TimeSpan.FromSeconds(30)).Subscribe(item => log.LogInformation(monitor.ToString())))
            {
                var inputBlock = new BufferBlock <ProcessingChunk <string> >(new DataflowBlockOptions {
                    BoundedCapacity = 1000000
                });
                var deserializeBlock = new TransformBlock <ProcessingChunk <string>, ProcessingChunk <TweetDTO> >(
                    json => new ProcessingChunk <TweetDTO>(json.FileName, json.ChunkId, json.TotalChunks, jsonConvert.DeserializeObject <TweetDTO>(json.Data)),
                    new ExecutionDataflowBlockOptions
                {
                    BoundedCapacity        = 2,
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                });
                var outputBlock = new ActionBlock <ProcessingChunk <TweetDTO> >(
                    Deserialized,
                    new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                });

                inputBlock.LinkTo(deserializeBlock, new DataflowLinkOptions {
                    PropagateCompletion = true
                });
                deserializeBlock.LinkTo(outputBlock, new DataflowLinkOptions {
                    PropagateCompletion = true
                });

                foreach (var file in files)
                {
                    try
                    {
                        var data = fileLoader.Load(file);
                        for (var i = 0; i < data.Length; i++)
                        {
                            await inputBlock.SendAsync(new ProcessingChunk <string>(file, i, data.Length, data[i])).ConfigureAwait(false);
                        }

                        monitor.Increment();
                    }
                    catch (Exception ex)
                    {
                        log.LogError(ex, "Failed");
                    }
                }

                inputBlock.Complete();
                await Task.WhenAll(inputBlock.Completion, outputBlock.Completion).ConfigureAwait(false);
            }
        }
Example #21
0
        protected override Task Execute(CancellationToken token)
        {
            log.LogInformation("Starting twitter monitoring...");
            SetupWords();
            RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
            var cleanup = new MessageCleanup();
            var monitor = new PerformanceMonitor(100000);
            var cred    = auth.Authenticate();

            using (Observable.Interval(TimeSpan.FromSeconds(30)).Subscribe(item => log.LogInformation(monitor.ToString())))
                using (var streamWriter = new StreamWriter(config.Out, true, new UTF8Encoding(false)))
                    using (var csvDataTarget = new CsvWriter(streamWriter))
                    {
                        Auth.ExecuteOperationWithCredentials(
                            cred,
                            () =>
                        {
                            var enrichments = Enrichment().ToArray();
                            foreach (var enrichment in enrichments)
                            {
                                enrichment.Discovery.BatchSize = 5;
                                enrichment.Discovery.AddProcessed(enrichments.SelectMany(p => p.Discovery.Processed).ToArray());
                                enrichment.Discovery.Process()
                                .ToObservable()
                                .ObserveOn(TaskPoolScheduler.Default)
                                .Select(
                                    x =>
                                {
                                    var text = cleanup.Cleanup(x.Message.Text).Replace("\r\n", " ");
                                    if (!CanInclude(text, enrichment.Type))
                                    {
                                        return(x);
                                    }

                                    text = Regex.Replace(text, @"[^\u0000-\u007F]+", string.Empty);
                                    csvDataTarget.WriteField(x.Message.Id);
                                    csvDataTarget.WriteField(x.Topic);
                                    csvDataTarget.WriteField(enrichment.Type);
                                    csvDataTarget.WriteField(text);
                                    csvDataTarget.NextRecord();
                                    streamWriter.Flush();
                                    monitor.Increment();
                                    return(x);
                                })
                                .Wait();
                            }
                        });
                    }

            return(Task.CompletedTask);
        }
Example #22
0
        public virtual ObservableCollection <ReportIndicators> Create(List <Playerstatistic> statistics, CancellationToken cancellationToken, bool forceRefresh = false)
        {
            using (var perfomance = new PerformanceMonitor($"Report.{GetType().Name} build time", LogProvider.Log.IsAdvanced, this))
            {
                var report = new ObservableCollection <ReportIndicators>();

                if (statistics == null || !statistics.Any())
                {
                    return(report);
                }

                var chunkSize = GetChunkSize(statistics);

                var splittedStatistic = new Queue <List <Playerstatistic> >(statistics.ToList().SplitList(chunkSize));

                var runningTasks = new List <Task>();

                var chunkedIndicators = new BlockingCollection <T>();

                while (splittedStatistic.Count > 0)
                {
                    while (runningTasks.Count < maxThreads && splittedStatistic.Count > 0)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        var statisticChunk = splittedStatistic.Dequeue();

                        runningTasks.Add(Task.Run(() => ProcessChunkedStatistic(statisticChunk, chunkedIndicators, cancellationToken)));
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    var completedTask = Task.WhenAny(runningTasks).Result;

                    runningTasks.Remove(completedTask);
                }

                Task.WhenAll(runningTasks).Wait();

                report.AddRange(OrderResult(CombineChunkedIndicators(chunkedIndicators, cancellationToken)));

                return(report);
            }
        }
Example #23
0
        public void TournamentsAreImportedForEachPlayer(string tournamentNumber, int expectedCount)
        {
            using (var perfScope = new PerformanceMonitor("TournamentsAreImportedForEachPlayer"))
            {
                using (var session = ModelEntities.OpenStatelessSession())
                {
                    var tournaments = session.Query <Tournaments>()
                                      .Where(x => x.Tourneynumber == tournamentNumber)
                                      .ToList();

                    Assert.That(tournaments.Count, Is.EqualTo(expectedCount));
                }
            }
        }
Example #24
0
        public void IDCTPerformanceTest()
        {
            var source = new float[]
            {
                560, -196, -150, -80, 0, 0, 0, 0,
                -210, -60, -35, 0, 0, 0, 0, 0,
                -140, -32, -40, 0, 0, 0, 0, 0,
                -70, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0
            };

            const int iterations = 100000;
            const int runs       = 5;
            var       naivePerf  = new PerformanceMonitor("Naive", runs);
            var       nvidiaPerf = new PerformanceMonitor("NVidia", runs);
            var       dct        = new DCT(20);

            var naive  = new byte[8][];
            var nvidia = new byte[8][];

            for (int i = 0; i < 8; i++)
            {
                naive[i]  = new byte[8];
                nvidia[i] = new byte[8];
            }

            for (int run = 0; run < runs; run++)
            {
                naivePerf.Start();
                for (int i = 0; i < iterations; i++)
                {
                    dct.DoIDCT_Naive(source, naive);
                }
                naivePerf.Stop();

                nvidiaPerf.Start();
                for (int i = 0; i < iterations; i++)
                {
                    dct.DoIDCT_NVidia(source, nvidia);
                }
                nvidiaPerf.Stop();
            }

            Assert.IsTrue(nvidiaPerf.AverageCompletionTimeInMs < naivePerf.AverageCompletionTimeInMs,
                          "The NVidia IDCT took {0:0.00} ms, while the naive IDCT took {1:0.00}", nvidiaPerf.AverageCompletionTimeInMs, naivePerf.AverageCompletionTimeInMs);
        }
Example #25
0
        public override void run(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine(Help);
            }
            else
            {
                ChunkerModel model = (new ChunkerModelLoader()).load(new File(args[0]));

                ChunkerME chunker = new ChunkerME(model, ChunkerME.DEFAULT_BEAM_SIZE);

                ObjectStream <string> lineStream = new PlainTextByLineStream(new InputStreamReader(Console.OpenStandardInput));

                PerformanceMonitor perfMon = new PerformanceMonitor(System.err, "sent");
                perfMon.start();

                try
                {
                    string line;
                    while ((line = lineStream.read()) != null)
                    {
                        POSSample posSample;
                        try
                        {
                            posSample = POSSample.parse(line);
                        }
                        catch (InvalidFormatException)
                        {
                            Console.Error.WriteLine("Invalid format:");
                            Console.Error.WriteLine(line);
                            continue;
                        }

                        string[] chunks = chunker.chunk(posSample.Sentence, posSample.Tags);

                        Console.WriteLine((new ChunkSample(posSample.Sentence, posSample.Tags, chunks)).nicePrint());

                        perfMon.incrementCounter();
                    }
                }
                catch (IOException e)
                {
                    CmdLineUtil.handleStdinIoError(e);
                }

                perfMon.stopAndPrintFinalResult();
            }
        }
Example #26
0
    // OnEnable
    void OnEnable()
    {
        currentState = InGameMenuState.None;
        nextState    = InGameMenuState.None;

        Screen.showCursor = true;

        if (Player.main != null)
        {
            Player.main.crossHair.enabled = false;
        }

        // Try to free up some RAM
        PerformanceMonitor.FreeRAM();
    }
Example #27
0
        private static double GetSystemStatistic_ThreadCount(object source, string arguments)
        {
            double             statistic = double.NaN;
            PerformanceMonitor perfMon   = source as PerformanceMonitor;

            if ((object)perfMon != null)
            {
                if ((object)perfMon.ThreadCount != null)
                {
                    statistic = perfMon.ThreadCount.LastValue;
                }
            }

            return(statistic);
        }
Example #28
0
        private static double GetSystemStatistic_AverageThreadingContentionRate(object source, string arguments)
        {
            double             statistic = double.NaN;
            PerformanceMonitor perfMon   = source as PerformanceMonitor;

            if ((object)perfMon != null)
            {
                if ((object)perfMon.ThreadingContentionRate != null)
                {
                    statistic = perfMon.ThreadingContentionRate.AverageValue;
                }
            }

            return(statistic);
        }
Example #29
0
        private static double GetSystemStatistic_IPDataReceiveRate(object source, string arguments)
        {
            double             statistic = double.NaN;
            PerformanceMonitor perfMon   = source as PerformanceMonitor;

            if ((object)perfMon != null)
            {
                if ((object)perfMon.IPDataReceiveRate != null)
                {
                    statistic = perfMon.IPDataReceiveRate.LastValue;
                }
            }

            return(statistic);
        }
Example #30
0
        private static double GetSystemStatistic_AverageMemoryUsage(object source, string arguments)
        {
            double             statistic = double.NaN;
            PerformanceMonitor perfMon   = source as PerformanceMonitor;

            if ((object)perfMon != null)
            {
                if ((object)perfMon.MemoryUsage != null)
                {
                    statistic = perfMon.MemoryUsage.AverageValue;
                }
            }

            return(statistic);
        }
Example #31
0
        private void Update(bool reset = false)
        {
            var stage           = AtkStage.GetSingleton();
            var loadedUnitsList = &stage->RaptureAtkUnitManager->AtkUnitManager.AllLoadedUnitsList;
            var addonList       = &loadedUnitsList->AtkUnitEntries;

            #if DEBUG
            PerformanceMonitor.Begin();
            #endif
            for (var i = 0; i < loadedUnitsList->Count; i++)
            {
                var addon = addonList[i];
                var name  = Helper.Common.PtrToUTF8(new IntPtr(addon->Name));

                if (name != null && name.StartsWith("JobHud"))
                {
                    if (reset || Config.ShowInDuty && Service.Condition[ConditionFlag.BoundByDuty])
                    {
                        if (addon->UldManager.NodeListCount == 0)
                        {
                            addon->UldManager.UpdateDrawNodeList();
                        }
                    }
                    else if (Config.ShowInCombat && Service.Condition[ConditionFlag.InCombat])
                    {
                        outOfCombatTimer.Restart();
                        if (addon->UldManager.NodeListCount == 0)
                        {
                            addon->UldManager.UpdateDrawNodeList();
                        }
                    }
                    else if (Config.ShowInCombat && outOfCombatTimer.ElapsedMilliseconds < Config.CombatBuffer * 1000)
                    {
                        if (addon->UldManager.NodeListCount == 0)
                        {
                            addon->UldManager.UpdateDrawNodeList();
                        }
                    }
                    else
                    {
                        addon->UldManager.NodeListCount = 0;
                    }
                }
            }
            #if DEBUG
            PerformanceMonitor.End();
            #endif
        }
Example #32
0
        public void TournamentsTableSizeIsImported(string tournamentNumber, string playerName, int tableSize)
        {
            using (var perfScope = new PerformanceMonitor("TournamentsTableSizeIsImported"))
            {
                using (var session = ModelEntities.OpenStatelessSession())
                {
                    var tournament = session.Query <Tournaments>()
                                     .SingleOrDefault(x => x.Tourneynumber == tournamentNumber && x.Player.Playername == playerName);

                    Assert.IsNotNull(tournament, $"Tournament data for '{playerName}' has not been found in tournament '{tournamentNumber}'");

                    Assert.That(tournament.Tablesize, Is.EqualTo(tableSize),
                                $"Tournament table size doesn't match for '{playerName}' in tournament '{tournamentNumber}' [{(EnumPokerSites)tournament.SiteId}]");
                }
            }
        }
Example #33
0
 public PhotonesProgram(
     GameState initialGameState,
     Action <PhotonesProgram, BeardedUpdateEventArgs> afterFrame = null
     )
     : base((int)WIDTH, (int)HEIGHT, GraphicsMode.Default, "photones",
            GameWindowFlags.Default, DisplayDevice.Default, MAJOR, MINOR,
            GraphicsContextFlags.Default)
 {
     Console.WriteLine(DisplayDevice.Default.ToString());
     Console.WriteLine(GL.GetString(StringName.Renderer));
     Console.WriteLine(GL.GetString(StringName.Version));
     _performanceMonitor = new PerformanceMonitor();
     _gameStatistics     = new GameStatistics();
     _afterFrame         = afterFrame;
     _gameState          = initialGameState;
 }
Example #34
0
        //
        // http://msdn.microsoft.com/en-us/library/5e3s61wf(v=vs.90).aspx
        //
        private static void Sample_CreatingPerformanceCounter()
        {
            var performanceMonitor = new PerformanceMonitor();
            performanceMonitor.AddCounter("CustomInstance");
            using (var counter = new PerformanceCounter(PerformanceMonitor.pcCategory, "CustomInstance", readOnly: false))
            {
                string command;
                do
                {
                    counter.Increment();
                    Console.Write("enter command: ");
                    command = Console.ReadLine();
                } while (command != "");
            }

            Console.WriteLine("press any key...");
            Console.ReadKey();
        }
        public void Check(PerformanceMonitor pm, int cpuThreshold, int memoryThreshold)
        {
            if (_measureMode == MeasureMode.HighCpu || _measureMode == MeasureMode.Both)
            {
                var cpuUsage = pm.GetCurrentCpuUsage();
                Console.WriteLine("CPU usage: {0}%", cpuUsage);

                if (cpuUsage >= cpuThreshold)
                {
                    Beeper.HighCpuBeep();
                }
            }

            if (_measureMode == MeasureMode.HighMemory || _measureMode == MeasureMode.Both)
            {
                var memoryUsage = pm.GetCurrentMemoryUsage();
                Console.WriteLine("Memory usage: {0}%", memoryUsage);

                if (memoryUsage >= memoryThreshold)
                {
                    Beeper.HighMemoryBeep();
                }
            }
        }
Example #36
0
        /// <summary>
        /// Initializes the bootstrap with the configuration, config resolver and log factory.
        /// </summary>
        /// <param name="serverConfigResolver">The server config resolver.</param>
        /// <param name="logFactory">The log factory.</param>
        /// <returns></returns>
        public virtual bool Initialize(Func<IServerConfig, IServerConfig> serverConfigResolver, ILogFactory logFactory)
        {
            if (m_Initialized)
                throw new Exception("The server had been initialized already, you cannot initialize it again!");

            if (logFactory != null && !string.IsNullOrEmpty(m_Config.LogFactory))
            {
                throw new ArgumentException("You cannot pass in a logFactory parameter, if you have configured a root log factory.", "logFactory");
            }

            IEnumerable<WorkItemFactoryInfo> workItemFactories;

            using (var factoryInfoLoader = GetWorkItemFactoryInfoLoader(m_Config, logFactory))
            {
                var bootstrapLogFactory = factoryInfoLoader.GetBootstrapLogFactory();

                logFactory = bootstrapLogFactory.ExportFactory.CreateExport<ILogFactory>();

                LogFactory = logFactory;
                m_GlobalLog = logFactory.GetLog(this.GetType().Name);

                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                try
                {
                    workItemFactories = factoryInfoLoader.LoadResult(serverConfigResolver);
                }
                catch (Exception e)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error(e);

                    return false;
                }
            }

            m_AppServers = new List<IWorkItem>(m_Config.Servers.Count());

            IWorkItem serverManager = null;

            //Initialize servers
            foreach (var factoryInfo in workItemFactories)
            {
                IWorkItem appServer = InitializeAndSetupWorkItem(factoryInfo);

                if (appServer == null)
                    return false;

                if (factoryInfo.IsServerManager)
                    serverManager = appServer;
                else if (!(appServer is IsolationAppServer))//No isolation
                {
                    //In isolation mode, cannot check whether is server manager in the factory info loader
                    if (TypeValidator.IsServerManagerType(appServer.GetType()))
                        serverManager = appServer;
                }

                m_AppServers.Add(appServer);
            }

            if (serverManager != null)
                m_ServerManager = serverManager;

            if (!m_Config.DisablePerformanceDataCollector)
            {
                m_PerfMonitor = new PerformanceMonitor(m_Config, m_AppServers, serverManager, logFactory);

                if (m_GlobalLog.IsDebugEnabled)
                    m_GlobalLog.Debug("The PerformanceMonitor has been initialized!");
            }

            if (m_GlobalLog.IsDebugEnabled)
                m_GlobalLog.Debug("The Bootstrap has been initialized!");

            try
            {
                RegisterRemotingService();
            }
            catch (Exception e)
            {
                if (m_GlobalLog.IsErrorEnabled)
                    m_GlobalLog.Error("Failed to register remoting access service!", e);

                return false;
            }

            m_Initialized = true;

            return true;
        }
Example #37
0
        public void EnablePerformanceCounters()
        {
            if(wasStarted)
                throw new InvalidOperationException("Performance counters cannot be enabled after the queue has been started.");

            monitor = new PerformanceMonitor(this);
        }
Example #38
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultBootstrap"/> class.
        /// </summary>
        /// <param name="rootConfig">The root config.</param>
        /// <param name="appServers">The app servers.</param>
        /// <param name="logFactory">The log factory.</param>
        public DefaultBootstrap(IRootConfig rootConfig, IEnumerable<IWorkItem> appServers, ILogFactory logFactory)
        {
            if (rootConfig == null)
                throw new ArgumentNullException("rootConfig");

            if (appServers == null)
                throw new ArgumentNullException("appServers");

            if(!appServers.Any())
                throw new ArgumentException("appServers must have one item at least", "appServers");

            if (logFactory == null)
                throw new ArgumentNullException("logFactory");

            m_RootConfig = rootConfig;

            SetDefaultCulture(rootConfig);

            m_AppServers = appServers.ToList();

            m_GlobalLog = logFactory.GetLog(this.GetType().Name);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            if (!rootConfig.DisablePerformanceDataCollector)
            {
                m_PerfMonitor = new PerformanceMonitor(rootConfig, m_AppServers, null, logFactory);

                if (m_GlobalLog.IsDebugEnabled)
                    m_GlobalLog.Debug("The PerformanceMonitor has been initialized!");
            }

            if (m_GlobalLog.IsDebugEnabled)
                m_GlobalLog.Debug("The Bootstrap has been initialized!");

            m_Initialized = true;
        }
Example #39
0
        /// <summary>
        /// Initializes the bootstrap with the configuration, config resolver and log factory.
        /// </summary>
        /// <param name="serverConfigResolver">The server config resolver.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <returns></returns>
        public virtual bool Initialize(Func<IServerConfig, IServerConfig> serverConfigResolver, ILoggerFactory loggerFactory)
        {
            if (m_Initialized)
                throw new Exception("The server had been initialized already, you cannot initialize it again!");

            if (loggerFactory != null && !string.IsNullOrEmpty(m_Config.LoggerFactory))
            {
                throw new ArgumentException("You cannot pass in a logFactory parameter, if you have configured a root log factory.", "loggerFactory");
            }

            if(loggerFactory == null)
            {
                loggerFactory = GetBootstrapLoggerFactory(m_Config.LoggerFactory);
            }

            m_GlobalLog = loggerFactory.GetCurrentClassLogger();

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            m_AppServers = new List<IManagedApp>(m_Config.Servers.Count());

            IManagedApp serverManager = null;

            //Initialize servers
            foreach (var config in m_Config.Servers)
            {
                var serverConfig = config;

                if (serverConfigResolver != null)
                    serverConfig = serverConfigResolver(config);

                IManagedApp appServer;

                try
                {
                    var serverType = serverConfig.ServerType;

                    if(string.IsNullOrEmpty(serverType) && !string.IsNullOrEmpty(serverConfig.ServerTypeName))
                    {
                        var serverTypeProvider = m_Config.ServerTypes.FirstOrDefault(
                            t => t.Name.Equals(serverConfig.ServerTypeName, StringComparison.OrdinalIgnoreCase));

                        if (serverTypeProvider != null)
                            serverType = serverTypeProvider.Type;
                    }

                    if (string.IsNullOrEmpty(serverType))
                        throw new Exception("No server type configured or the configured server type was not found.");

                    appServer = CreateWorkItemInstance(serverType);

                    var serverMetadata = appServer.GetAppServerMetadata();

                    if (serverMetadata.IsServerManager)
                        serverManager = appServer;

                    if (m_GlobalLog.IsDebugEnabled)
                        m_GlobalLog.DebugFormat("The server instance {0} has been created!", serverConfig.Name);
                }
                catch (Exception e)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error(string.Format("Failed to create server instance {0}!", serverConfig.Name), e);
                    return false;
                }

                var exceptionSource = appServer as IExceptionSource;

                if(exceptionSource != null)
                    exceptionSource.ExceptionThrown += new EventHandler<ErrorEventArgs>(exceptionSource_ExceptionThrown);


                var setupResult = false;

                try
                {
                    setupResult = SetupWorkItemInstance(appServer, serverConfig);

                    if (m_GlobalLog.IsDebugEnabled)
                        m_GlobalLog.DebugFormat("The server instance {0} has been initialized!", appServer.Name);
                }
                catch (Exception e)
                {
                    m_GlobalLog.Error(e);
                    setupResult = false;
                }

                if (!setupResult)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error("Failed to setup server instance!");
                    return false;
                }

                m_AppServers.Add(appServer);
            }

            if (!m_Config.DisablePerformanceDataCollector)
            {
                m_PerfMonitor = new PerformanceMonitor(m_Config, m_AppServers, serverManager, LoggerFactory);

                if (m_GlobalLog.IsDebugEnabled)
                    m_GlobalLog.Debug("The PerformanceMonitor has been initialized!");
            }

            if (m_GlobalLog.IsDebugEnabled)
                m_GlobalLog.Debug("The Bootstrap has been initialized!");

            try
            {
                RegisterRemotingService();
            }
            catch (Exception e)
            {
                if (m_GlobalLog.IsErrorEnabled)
                    m_GlobalLog.Error("Failed to register remoting access service!", e);

                return false;
            }

            m_Initialized = true;

            return true;
        }
Example #40
0
        /// <include file='docs/MySqlConnection.xml' path='docs/Open/*'/>
        public override void Open()
        {
            if (State == ConnectionState.Open)
            Throw(new InvalidOperationException(Resources.ConnectionAlreadyOpen));

            #if !CF && !RT
              // start up our interceptors
              exceptionInterceptor = new ExceptionInterceptor(this);
              commandInterceptor = new CommandInterceptor(this);
            #endif

              SetState(ConnectionState.Connecting, true);

              AssertPermissions();

            #if !CF && !RT
              // if we are auto enlisting in a current transaction, then we will be
              // treating the connection as pooled
              if (Settings.AutoEnlist && Transaction.Current != null)
              {
            driver = DriverTransactionManager.GetDriverInTransaction(Transaction.Current);
            if (driver != null &&
              (driver.IsInActiveUse ||
              !driver.Settings.EquivalentTo(this.Settings)))
              Throw(new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported));
              }
            #endif

              try
              {
            MySqlConnectionStringBuilder currentSettings = Settings;
            #if !CF

            // Load balancing
            if (ReplicationManager.IsReplicationGroup(Settings.Server))
            {
              if (driver == null)
              {
            ReplicationManager.GetNewConnection(Settings.Server, false, this);
            return;
              }
              else
            currentSettings = driver.Settings;
            }
            #endif

            if (Settings.Pooling)
            {
              MySqlPool pool = MySqlPoolManager.GetPool(currentSettings);
              if (driver == null || !driver.IsOpen)
            driver = pool.GetConnection();
              procedureCache = pool.ProcedureCache;

            }
            else
            {
              if (driver == null || !driver.IsOpen)
            driver = Driver.Create(currentSettings);
              procedureCache = new ProcedureCache((int)Settings.ProcedureCacheSize);
            }
              }
              catch (Exception ex)
              {
            SetState(ConnectionState.Closed, true);
            throw;
              }

              // if the user is using old syntax, let them know
              if (driver.Settings.UseOldSyntax)
            MySqlTrace.LogWarning(ServerThread,
              "You are using old syntax that will be removed in future versions");

              SetState(ConnectionState.Open, false);
              driver.Configure(this);

              if (!(driver.SupportsPasswordExpiration && driver.IsPasswordExpired))
              {
            if (Settings.Database != null && Settings.Database != String.Empty)
              ChangeDatabase(Settings.Database);
              }

              // setup our schema provider
              schemaProvider = new ISSchemaProvider(this);

            #if !CF
              perfMonitor = new PerformanceMonitor(this);
            #endif

              // if we are opening up inside a current transaction, then autoenlist
              // TODO: control this with a connection string option
            #if !MONO && !CF && !RT
              if (Transaction.Current != null && Settings.AutoEnlist)
            EnlistTransaction(Transaction.Current);
            #endif

              hasBeenOpen = true;
              SetState(ConnectionState.Open, true);
        }
    /// <include file='docs/MySqlConnection.xml' path='docs/Open/*'/>
    public override void Open()
    {
      if (State == ConnectionState.Open)
        Throw(new InvalidOperationException(Resources.ConnectionAlreadyOpen));

#if !CF
      // start up our interceptors
      exceptionInterceptor = new ExceptionInterceptor(this);
      commandInterceptor = new CommandInterceptor(this);
#endif

      SetState(ConnectionState.Connecting, true);      

#if !CF
      // Security Asserts can only be done when the assemblies 
      // are put in the GAC as documented in 
      // http://msdn.microsoft.com/en-us/library/ff648665.aspx
      if (this.Settings.IncludeSecurityAsserts)
      {
        PermissionDemand();
        MySqlSecurityPermission.CreatePermissionSet(true).Assert(); 
      }
      // if we are auto enlisting in a current transaction, then we will be
      // treating the connection as pooled
      if (settings.AutoEnlist && Transaction.Current != null)
      {
        driver = DriverTransactionManager.GetDriverInTransaction(Transaction.Current);
        if (driver != null &&
          (driver.IsInActiveUse ||
          !driver.Settings.EquivalentTo(this.Settings)))
          Throw(new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported));
      }
#endif

      try
      {
        if (settings.Pooling)
        {
          MySqlPool pool = MySqlPoolManager.GetPool(settings);
          if (driver == null || !driver.IsOpen)
            driver = pool.GetConnection();
          procedureCache = pool.ProcedureCache;

        }
        else
        {
          if (driver == null || !driver.IsOpen)
            driver = Driver.Create(settings);
          procedureCache = new ProcedureCache((int)settings.ProcedureCacheSize);
        }
      }
      catch (Exception ex)
      {
        SetState(ConnectionState.Closed, true);
        throw;
      }

      // if the user is using old syntax, let them know
      if (driver.Settings.UseOldSyntax)
        MySqlTrace.LogWarning(ServerThread,
          "You are using old syntax that will be removed in future versions");

      SetState(ConnectionState.Open, false);
      driver.Configure(this);
      if (settings.Database != null && settings.Database != String.Empty)
        ChangeDatabase(settings.Database);

      // setup our schema provider
      schemaProvider = new ISSchemaProvider(this);
#if !CF
      perfMonitor = new PerformanceMonitor(this);
#endif

      // if we are opening up inside a current transaction, then autoenlist
      // TODO: control this with a connection string option
#if !MONO && !CF
      if (Transaction.Current != null && settings.AutoEnlist)
        EnlistTransaction(Transaction.Current);
#endif

      hasBeenOpen = true;
      SetState(ConnectionState.Open, true);
    }
Example #42
0
        public void OnStart(string[] args)
        {
            // Ensure required components are present.
            if (m_parentService == null)
                throw new InvalidOperationException("ParentService property of ServiceHelper component is not set");

            if (m_remotingServer == null)
                throw new InvalidOperationException("RemotingServer property of ServiceHelper component is not set");

            OnServiceStarting(args);

            lock (m_clientRequestHandlers)
            {
                m_clientRequestHandlers.Add(new ClientRequestHandler("Clients", "Displays list of clients connected to the service", ShowClients));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Settings", "Displays queryable service settings from config file", ShowSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Processes", "Displays list of service or system processes", ShowProcesses));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Schedules", "Displays list of process schedules defined in the service", ShowSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandler("History", "Displays list of requests received from the clients", ShowRequestHistory));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Help", "Displays list of commands supported by the service", ShowRequestHelp));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Status", "Displays the current service status", ShowServiceStatus));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Start", "Start a service or system process", StartProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Abort", "Aborts a service or system process", AbortProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandler("ReloadCryptoCache", "Reloads local cryptography cache", ReloadCryptoCache));
                m_clientRequestHandlers.Add(new ClientRequestHandler("UpdateSettings", "Updates service setting in the config file", UpdateSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandler("ReloadSettings", "Reloads services settings from the config file", ReloadSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Reschedule", "Reschedules a process defined in the service", RescheduleProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Unschedule", "Unschedules a process defined in the service", UnscheduleProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandler("SaveSchedules", "Saves process schedules to the config file", SaveSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandler("LoadSchedules", "Loads process schedules from the config file", LoadSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Version", "Displays current service version", ShowVersion));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Time", "Displays current system time", ShowTime));

                // Enable telnet support if requested.
                if (m_supportTelnetSessions)
                {
                    m_clientRequestHandlers.Add(new ClientRequestHandler("Telnet", "Allows for a telnet session to the service server", RemoteTelnetSession, false));
                }

                // Enable health monitoring if requested.
                if (m_monitorServiceHealth)
                {
                    m_performanceMonitor = new PerformanceMonitor(m_healthMonitorInterval * 1000.0D, true);
                    m_clientRequestHandlers.Add(new ClientRequestHandler("Health", "Displays a report of resource utilization for the service", ShowHealthReport));
                    m_clientRequestHandlers.Add(new ClientRequestHandler("ResetHealthMonitor", "Resets the system resource utilization monitor", ResetHealthMonitor));
                }
            }

            // Add internal components as service components by default.
            lock (m_serviceComponents)
            {
                m_serviceComponents.Add(m_processScheduler);
                m_serviceComponents.Add(m_statusLog);
                m_serviceComponents.Add(m_errorLogger);
                m_serviceComponents.Add(m_errorLogger.ErrorLog);
                m_serviceComponents.Add(m_remotingServer);
                m_serviceComponents.Add(m_statusUpdateQueue);
            }

            // Open log file if file logging is enabled.
            if (m_logStatusUpdates)
                m_statusLog.Open();

            // Start all of the core components.
            m_statusUpdateQueue.Start();
            m_processScheduler.Start();
            m_remotingServer.Start();

            m_enabled = true;
            OnServiceStarted();
        }
Example #43
0
        private void ResetPerfMoniter()
        {
            if (m_PerfMonitor != null)
            {
                m_PerfMonitor.Stop();
                m_PerfMonitor.Dispose();
                m_PerfMonitor = null;
            }

            m_PerfMonitor = new PerformanceMonitor(m_Config, m_AppServers, m_ServerManager, LogFactory);
            m_PerfMonitor.Start();

            if (m_GlobalLog.IsDebugEnabled)
                m_GlobalLog.Debug("The PerformanceMonitor has been reset for new server has been added!");
        }
        /// <summary>
        /// Initializes the bootstrap with the configuration, config resolver and log factory.
        /// </summary>
        /// <param name="serverConfigResolver">The server config resolver.</param>
        /// <param name="logFactory">The log factory.</param>
        /// <returns></returns>
        public virtual bool Initialize(Func<IServerConfig, IServerConfig> serverConfigResolver, ILogFactory logFactory)
        {
            if (m_Initialized)
                throw new Exception("The server had been initialized already, you cannot initialize it again!");

            if (logFactory != null && !string.IsNullOrEmpty(m_Config.LogFactory))
            {
                throw new ArgumentException("You cannot pass in a logFactory parameter, if you have configured a root log factory.", "logFactory");
            }

            IEnumerable<WorkItemFactoryInfo> workItemFactories;

            using (var factoryInfoLoader = GetWorkItemFactoryInfoLoader(m_Config, logFactory))
            {
                var bootstrapLogFactory = factoryInfoLoader.GetBootstrapLogFactory();

                logFactory = bootstrapLogFactory.ExportFactory.CreateExport<ILogFactory>();

                LogFactory = logFactory;
                m_GlobalLog = logFactory.GetLog(this.GetType().Name);

                try
                {
                    workItemFactories = factoryInfoLoader.LoadResult(serverConfigResolver);
                }
                catch (Exception e)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error(e);

                    return false;
                }
            }

            m_AppServers = new List<IWorkItem>(m_Config.Servers.Count());
            //Initialize servers
            foreach (var factoryInfo in workItemFactories)
            {
                IWorkItem appServer;

                try
                {
                    appServer = CreateWorkItemInstance(factoryInfo.ServerType);

                    if (m_GlobalLog.IsDebugEnabled)
                        m_GlobalLog.DebugFormat("The server instance {0} has been created!", factoryInfo.Config.Name);
                }
                catch (Exception e)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error(string.Format("Failed to create server instance {0}!", factoryInfo.Config.Name), e);
                    return false;
                }


                var setupResult = false;

                try
                {
                    setupResult = SetupWorkItemInstance(appServer, factoryInfo);

                    if (m_GlobalLog.IsDebugEnabled)
                        m_GlobalLog.DebugFormat("The server instance {0} has been initialized!", appServer.Name);
                }
                catch (Exception e)
                {
                    m_GlobalLog.Error(e);
                    setupResult = false;
                }

                if (!setupResult)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error("Failed to setup server instance!");
                    return false;
                }

                m_AppServers.Add(appServer);
            }

            if (!m_Config.DisablePerformanceDataCollector)
            {
                m_PerfMonitor = new PerformanceMonitor(m_Config, m_AppServers, logFactory);

                if (m_GlobalLog.IsDebugEnabled)
                    m_GlobalLog.Debug("The PerformanceMonitor has been initialized!");
            }

            if (m_GlobalLog.IsDebugEnabled)
                m_GlobalLog.Debug("The Bootstrap has been initialized!");

            m_Initialized = true;

            return true;
        }
Example #45
0
        public void OnStart(string[] args)
        {
            // Ensure required components are present.
            if (m_parentService == null)
                throw new InvalidOperationException("ParentService property of ServiceHelper component is not set.");

            if (m_remotingServer == null)
                throw new InvalidOperationException("RemotingServer property of ServiceHelper component is not set.");

            OnServiceStarting(args);

            m_clientRequestHandlers.Add(new ClientRequestHandler("Clients", "Displays list of clients connected to the service", ShowClients));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Settings", "Displays queryable service settings from config file", ShowSettings));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Processes", "Displays list of service or system processes", ShowProcesses));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Schedules", "Displays list of process schedules defined in the service", ShowSchedules));
            m_clientRequestHandlers.Add(new ClientRequestHandler("History", "Displays list of requests received from the clients", ShowRequestHistory));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Help", "Displays list of commands supported by the service", ShowRequestHelp));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Status", "Displays the current service status", ShowServiceStatus));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Start", "Start a service or system process", StartProcess));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Abort", "Aborts a service or system process", AbortProcess));
            m_clientRequestHandlers.Add(new ClientRequestHandler("UpdateSettings", "Updates service setting in the config file", UpdateSettings));
            m_clientRequestHandlers.Add(new ClientRequestHandler("ReloadSettings", "Reloads services settings from the config file", ReloadSettings));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Reschedule", "Reschedules a process defined in the service", RescheduleProcess));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Unschedule", "Unschedules a process defined in the service", UnscheduleProcess));
            m_clientRequestHandlers.Add(new ClientRequestHandler("SaveSchedules", "Saves process schedules to the config file", SaveSchedules));
            m_clientRequestHandlers.Add(new ClientRequestHandler("LoadSchedules", "Loads process schedules from the config file", LoadSchedules));
            m_clientRequestHandlers.Add(new ClientRequestHandler("Telnet", "Allows for a telnet session to the service server", RemoteTelnetSession, false));

            // Define "Health" command only if monitoring service health is enabled.
            if (m_monitorServiceHealth)
            {
                m_clientRequestHandlers.Add(new ClientRequestHandler("Health", "Displays a report of resource utilization for the service", ShowHealthReport));
                m_performanceMonitor = new PerformanceMonitor();
            }

            // Add internal components as service components by default.
            m_serviceComponents.Add(m_processScheduler);
            m_serviceComponents.Add(m_statusLog);
            m_serviceComponents.Add(m_errorLogger);
            m_serviceComponents.Add(m_errorLogger.ErrorLog);
            m_serviceComponents.Add(m_remotingServer);

            // Initialize all service components when service has started.
            Initialize();

            // Open log file if file logging is enabled.
            if (m_logStatusUpdates)
                m_statusLog.Open();

            // Start the scheduler if it is not running.
            if (!m_processScheduler.IsRunning)
                m_processScheduler.Start();

            // Start the remoting server if it is not running.
            if (m_remotingServer.CurrentState == ServerState.NotRunning)
                m_remotingServer.Start();

            OnServiceStarted();
        }
        private void ResetHealthMonitor(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Resets the system resource utilization monitor.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       ResetHealthMonitor -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -?".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.AppendLine();

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, helpMessage.ToString());
            }
            else
            {
                try
                {
                    // Dispose existing performance monitor
                    if ((object)m_performanceMonitor != null)
                        m_performanceMonitor.Dispose();

                    // Recreate the performance monitor
                    m_performanceMonitor = new PerformanceMonitor(m_healthMonitorInterval * 1000.0D);

                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "System health monitor successfully reset.\r\n\r\n");
                }
                catch (Exception ex)
                {
                    LogException(ex);
                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to reset system health monitor: {0}\r\n\r\n", ex.Message);
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultBootstrap"/> class.
        /// </summary>
        /// <param name="rootConfig">The root config.</param>
        /// <param name="appServers">The app servers.</param>
        /// <param name="logFactory">The log factory.</param>
        public DefaultBootstrap(IRootConfig rootConfig, IEnumerable<IWorkItem> appServers, ILogFactory logFactory)
        {
            if (rootConfig == null)
                throw new ArgumentNullException("rootConfig");

            if (appServers == null)
                throw new ArgumentNullException("appServers");

            if(!appServers.Any())
                throw new ArgumentException("appServers must have one item at least", "appServers");

            if (logFactory == null)
                throw new ArgumentNullException("logFactory");

            m_RootConfig = rootConfig;

            m_AppServers = appServers.ToList();

            m_GlobalLog = logFactory.GetLog(this.GetType().Name);

            if (!rootConfig.DisablePerformanceDataCollector)
            {
                m_PerfMonitor = new PerformanceMonitor(rootConfig, m_AppServers, logFactory);
                m_PerfMonitor.Collected += new EventHandler<PermformanceDataEventArgs>(m_PerfMonitor_Collected);
            }

            m_Initialized = true;
        }
Example #48
0
        public void OnStart(string[] args)
        {
            if (m_service != null)
            {
                // Notify service event consumers of pending service start
                if (ServiceStarting != null)
                    ServiceStarting(this, new EventArgs<object>(args));

                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Clients", "Displays list of clients connected to the service", ShowClients));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Settings", "Displays queryable service settings from config file", ShowSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Processes", "Displays list of service or system processes", ShowProcesses));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Schedules", "Displays list of process schedules defined in the service", ShowSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("History", "Displays list of requests received from the clients", ShowRequestHistory));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Help", "Displays list of commands supported by the service", ShowRequestHelp));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Status", "Displays the current service status", ShowServiceStatus));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Start", "Start a service or system process", StartProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Abort", "Aborts a service or system process", AbortProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("UpdateSettings", "Updates service setting in the config file", UpdateSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("ReloadSettings", "Reloads services settings from the config file", ReloadSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Reschedule", "Reschedules a process defined in the service", RescheduleProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Unschedule", "Unschedules a process defined in the service", UnscheduleProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("SaveSchedules", "Saves process schedules to the config file", SaveSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("LoadSchedules", "Loads process schedules from the config file", LoadSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Command", "Allows for a telnet-like remote command session", RemoteCommandSession, false));

                // Define "Health" command only if monitoring service health is enabled
                if (m_monitorServiceHealth)
                {
                    m_clientRequestHandlers.Add(new ClientRequestHandlerInfo("Health", "Displays a report of resource utilization for the service", ShowHealthReport));
                    m_performanceMonitor = new PerformanceMonitor();
                }

                // Add scheduler, status log and remoting server as service components by default
                m_serviceComponents.Add(m_scheduler);
                m_serviceComponents.Add(m_statusLog);
                m_serviceComponents.Add(m_remotingServer);

                // JRC: Disabled override of remoting server handshake operations since ServiceHelper doesn't
                // own remoting server - consumer does - and they may have specially defined transport options
                //if (m_remotingServer != null)
                //{
                //    m_remotingServer.Handshake = true;
                //    m_remotingServer.HandshakePassphrase = Name;
                //}

                // Open the status log
                if (m_logStatusUpdates)
                    m_statusLog.Open();

                // Notify all service components of service started
                foreach (IServiceComponent component in m_serviceComponents)
                {
                    if (component != null)
                        component.ServiceStateChanged(ServiceState.Started);
                }

                // Notify all remote clients that might possibly be connected at of service start (not likely)
                SendServiceStateChangedResponse(ServiceState.Started);

                // Notify service event consumers that service has started
                if (ServiceStarted != null)
                    ServiceStarted(this, EventArgs.Empty);
            }
            else
            {
                throw new InvalidOperationException("Service cannot be started. The Service property of ServiceHelper is not set.");
            }
        }
Example #49
0
		/// <summary>
		/// Releases the unmanaged resources used by an instance of the <see cref="ServiceHelper" /> class and optionally releases the managed resources.
		/// </summary>
		/// <param name="disposing"><strong>true</strong> to release both managed and unmanaged resources; <strong>false</strong> to release only unmanaged resources.</param>
		protected override void Dispose(bool disposing)
		{
			if (!m_disposed)
			{
			    try
			    {			
				    if (disposing)
				    {
				        SaveSettings();

                        if (m_statusLog != null)
                        {
			                m_statusLog.LogException -= m_statusLog_LogException;
				            m_statusLog.Dispose();
                        }
                        m_statusLog = null;

                        if (m_scheduler != null)
                        {
			                m_scheduler.ScheduleDue -= m_scheduler_ScheduleDue;
				            m_scheduler.Dispose();
                        }
                        m_scheduler = null;

                        if (m_errorLogger != null)
                        {
				            m_errorLogger.Dispose();
                        }
                        m_errorLogger = null;

                        if (m_performanceMonitor != null)
			            {
				            m_performanceMonitor.Dispose();
			            }
                        m_performanceMonitor = null;

                        if (m_remoteCommandProcess != null)
                        {
                            m_remoteCommandProcess.ErrorDataReceived -= m_remoteCommandProcess_ErrorDataReceived;
                            m_remoteCommandProcess.OutputDataReceived -= m_remoteCommandProcess_OutputDataReceived;

                            if (!m_remoteCommandProcess.HasExited)
                                m_remoteCommandProcess.Kill();

                            m_remoteCommandProcess.Dispose();
                        }
                        m_remoteCommandProcess = null;

                        // Service processes are created and owned by remoting server, so we dispose them
                        if (m_processes != null)
                        {
                            foreach (ServiceProcess process in m_processes)
	                        {
                        		process.Dispose(); 
	                        }

                            m_processes.Clear();
                        }
                        m_processes = null;

                        // Detach any remoting server events, we don't own this component so we don't dispose it
                        RemotingServer = null;
				    }
                }
			    finally
			    {
			    	base.Dispose(disposing);    // Call base class Dispose().
				    m_disposed = true;          // Prevent duplicate dispose.
			    }
			}
		}
Example #50
0
        /// <include file='docs/MySqlConnection.xml' path='docs/Open/*'/>
        public override void Open()
        {
            if (State == ConnectionState.Open)
                throw new InvalidOperationException(Resources.ConnectionAlreadyOpen);

            SetState(ConnectionState.Connecting, true);

#if !CF
                // if we are auto enlisting in a current transaction, then we will be
                // treating the connection as pooled
                if (settings.AutoEnlist && Transaction.Current != null)
                {
                    driver = DriverTransactionManager.GetDriverInTransaction(Transaction.Current);
                    if (driver != null &&
                        (driver.IsInActiveUse ||
                        !driver.Settings.EquivalentTo(this.Settings)))
                        throw new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported);
                }
#endif

            try
            {
                if (settings.Pooling)
                {
                    MySqlPool pool = MySqlPoolManager.GetPool(settings);
                    if (driver == null)
                        driver = pool.GetConnection();
                    procedureCache = pool.ProcedureCache;
                }
                else
                {
                    if (driver == null)
                        driver = Driver.Create(settings);
                    procedureCache = new ProcedureCache((int) settings.ProcedureCacheSize);
                }
            }
            catch (Exception)
            {
                SetState(ConnectionState.Closed, true);
                throw;
            }

            // if the user is using old syntax, let them know
            if (driver.Settings.UseOldSyntax)
                Logger.LogWarning("You are using old syntax that will be removed in future versions");

            SetState(ConnectionState.Open, false);
            driver.Configure(this);
            if (settings.Database != null && settings.Database != String.Empty)
                ChangeDatabase(settings.Database);

            // setup our schema provider
            if (driver.Version.isAtLeast(5, 0, 0))
                schemaProvider = new ISSchemaProvider(this);
            else
                schemaProvider = new SchemaProvider(this);
#if !CF
            perfMonitor = new PerformanceMonitor(this);
#endif

            // if we are opening up inside a current transaction, then autoenlist
            // TODO: control this with a connection string option
#if !MONO && !CF
            if (Transaction.Current != null && settings.AutoEnlist)
                EnlistTransaction(Transaction.Current);
#endif

            hasBeenOpen = true;
			SetState(ConnectionState.Open, true);
		}
        public void OnStart(string[] args)
        {
            // Ensure required components are present.
            if ((object)m_parentService == null)
                throw new InvalidOperationException("ParentService property of ServiceHelper component is not set");

            if ((object)m_remotingServer == null)
                throw new InvalidOperationException("RemotingServer property of ServiceHelper component is not set");

            // Open log file if file logging is enabled.
            // Make sure to do this before calling OnServiceStarting
            // in case messages need to be logged by the handler.
            if (m_logStatusUpdates)
                m_statusLog.Open();

            OnServiceStarting(args);

            lock (m_clientRequestHandlers)
            {
                m_clientRequestHandlers.Add(new ClientRequestHandler("Clients", "Displays list of clients connected to the service", ShowClients));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Settings", "Displays queryable service settings from config file", ShowSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Processes", "Displays list of service or system processes", ShowProcesses));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Schedules", "Displays list of process schedules defined in the service", ShowSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandler("History", "Displays list of requests received from the clients", ShowRequestHistory));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Help", "Displays list of commands supported by the service", ShowRequestHelp, new[] { "?" }));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Status", "Displays the current service status", ShowServiceStatus, new[] { "stat" }));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Start", "Start a service or system process", StartProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Abort", "Aborts a service or system process", AbortProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandler("ReloadCryptoCache", "Reloads local cryptography cache", ReloadCryptoCache));
                m_clientRequestHandlers.Add(new ClientRequestHandler("UpdateSettings", "Updates service setting in the config file", UpdateSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandler("ReloadSettings", "Reloads services settings from the config file", ReloadSettings));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Reschedule", "Reschedules a process defined in the service", RescheduleProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Unschedule", "Unschedules a process defined in the service", UnscheduleProcess));
                m_clientRequestHandlers.Add(new ClientRequestHandler("SaveSchedules", "Saves process schedules to the config file", SaveSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandler("LoadSchedules", "Loads process schedules from the config file", LoadSchedules));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Filter", "Filters status messages coming from the service", UpdateClientFilter));

                // Enable file management commands if configured
                if (m_supportFileManagementCommands)
                {
                    m_clientRequestHandlers.Add(new ClientRequestHandler("Files", "Manages files on the server", ManageFiles));
                    m_clientRequestHandlers.Add(new ClientRequestHandler("Transfer", "Transfers files to and from the server", TransferFile));
                }

                m_clientRequestHandlers.Add(new ClientRequestHandler("Version", "Displays current service version", ShowVersion, new[] { "ver" }));
                m_clientRequestHandlers.Add(new ClientRequestHandler("Time", "Displays current system time", ShowTime));
                m_clientRequestHandlers.Add(new ClientRequestHandler("User", "Displays current user information", ShowUser, new[] { "whoami" }));

                // Enable telnet support if configured
                if (m_supportTelnetSessions)
                    m_clientRequestHandlers.Add(new ClientRequestHandler("Telnet", "Allows for a telnet session to the service server", RemoteTelnetSession, false));

                // Enable health monitoring if configured
                if (m_monitorServiceHealth)
                {
                    try
                    {
                        m_performanceMonitor = new PerformanceMonitor(m_healthMonitorInterval * 1000.0D);
                        m_clientRequestHandlers.Add(new ClientRequestHandler("Health", "Displays a report of resource utilization for the service", ShowHealthReport));
                        m_clientRequestHandlers.Add(new ClientRequestHandler("ResetHealthMonitor", "Resets the system resource utilization monitor", ResetHealthMonitor));
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        string message = $"Unable to start health monitor due to exception: {ex.Message}";
                        LogException(new InvalidOperationException(message, ex));
                        UpdateStatus(UpdateType.Warning, "{0} Is the service account a member of the \"Performance Log Users\" group?", message);
                    }
                }
            }

            // Add internal components as service components by default.
            lock (m_serviceComponents)
            {
                m_serviceComponents.Add(m_processScheduler);
                m_serviceComponents.Add(m_statusLog);
                m_serviceComponents.Add(m_errorLogger);
                m_serviceComponents.Add(m_errorLogger.ErrorLog);
                m_serviceComponents.Add(m_remotingServer);
            }

            // Start all of the core components.
            m_processScheduler.Start();
            m_remotingServer.Start();

            m_enabled = true;
            OnServiceStarted();
        }