public static MachineResources GetMachineResources(SmapsReader smapsReader)
        {
            using (var currentProcess = Process.GetCurrentProcess())
            {
                var memInfo     = MemoryInformation.GetMemoryInfo(smapsReader);
                var isLowMemory = LowMemoryNotification.Instance.IsLowMemory(memInfo);
                var workingSet  = PlatformDetails.RunningOnLinux
                    ? MemoryInformation.GetRssMemoryUsage(currentProcess.Id) - memInfo.AvailableWithoutTotalCleanMemory.GetValue(SizeUnit.Bytes)
                    : currentProcess.WorkingSet64;

                var cpuInfo = CpuUsage.Calculate();

                var machineResources = new MachineResources
                {
                    TotalMemory     = memInfo.TotalPhysicalMemory.GetValue(SizeUnit.Bytes),
                    AvailableMemory = memInfo.AvailableMemory.GetValue(SizeUnit.Bytes),
                    AvailableWithoutTotalCleanMemory = memInfo.AvailableWithoutTotalCleanMemory.GetValue(SizeUnit.Bytes),
                    SystemCommitLimit     = memInfo.TotalCommittableMemory.GetValue(SizeUnit.Bytes),
                    CommittedMemory       = memInfo.CurrentCommitCharge.GetValue(SizeUnit.Bytes),
                    ProcessMemoryUsage    = workingSet,
                    IsWindows             = PlatformDetails.RunningOnPosix == false,
                    IsLowMemory           = isLowMemory,
                    LowMemoryThreshold    = LowMemoryNotification.Instance.LowMemoryThreshold.GetValue(SizeUnit.Bytes),
                    CommitChargeThreshold = LowMemoryNotification.Instance.GetCommitChargeThreshold(memInfo).GetValue(SizeUnit.Bytes),
                    MachineCpuUsage       = cpuInfo.MachineCpuUsage,
                    ProcessCpuUsage       = Math.Min(cpuInfo.MachineCpuUsage, cpuInfo.ProcessCpuUsage) // min as sometimes +-1% due to time sampling
                };

                return(machineResources);
            }
        }
Exemplo n.º 2
0
        public Task GetNodeInfo()
        {
            using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    var json = new DynamicJsonValue();
                    using (context.OpenReadTransaction())
                    {
                        json[nameof(NodeInfo.NodeTag)]     = ServerStore.NodeTag;
                        json[nameof(NodeInfo.TopologyId)]  = ServerStore.GetClusterTopology(context).TopologyId;
                        json[nameof(NodeInfo.Certificate)] = ServerStore.Server.Certificate.CertificateForClients;
                        json[nameof(ServerStore.Engine.LastStateChangeReason)] = ServerStore.LastStateChangeReason();
                        json[nameof(NodeInfo.NumberOfCores)] = ProcessorInfo.ProcessorCount;

                        var memoryInformation = MemoryInformation.GetMemoryInfo();
                        json[nameof(NodeInfo.InstalledMemoryInGb)] = memoryInformation.InstalledMemory.GetDoubleValue(SizeUnit.Gigabytes);
                        json[nameof(NodeInfo.UsableMemoryInGb)]    = memoryInformation.TotalPhysicalMemory.GetDoubleValue(SizeUnit.Gigabytes);
                        json[nameof(NodeInfo.BuildInfo)]           = LicenseManager.BuildInfo;
                        json[nameof(NodeInfo.ServerId)]            = ServerStore.GetServerId().ToString();
                        json[nameof(NodeInfo.CurrentState)]        = ServerStore.CurrentRachisState;
                    }
                    context.Write(writer, json);
                    writer.Flush();
                }
            return(Task.CompletedTask);
        }
Exemplo n.º 3
0
        public static void SetWorkingSet(Process process, double ramInGb, Logger logger)
        {
#if SET_WORKING_SET
            var memoryInfo = MemoryInformation.GetMemoryInfoInGb();
            if (memoryInfo.UsableMemory < ramInGb)
            {
                ramInGb = memoryInfo.UsableMemory;
            }

            var maxWorkingSetInBytes = (long)Size.ConvertToBytes(ramInGb, SizeUnit.Gigabytes);
            var minWorkingSetInBytes = process.MinWorkingSet.ToInt64();
            if (minWorkingSetInBytes > maxWorkingSetInBytes)
            {
                minWorkingSetInBytes = maxWorkingSetInBytes;
            }

            if (PlatformDetails.RunningOnPosix == false)
            {
                // windows
                const QuotaLimit flags = QuotaLimit.QUOTA_LIMITS_HARDWS_MAX_DISABLE;
                var result             = SetProcessWorkingSetSizeEx(process.Handle, minWorkingSetInBytes, minWorkingSetInBytes, flags);
                if (result == false)
                {
                    logger.Info($"Failed to set max working set to {ramInGb}, error code: {Marshal.GetLastWin32Error()}");
                }

                return;
            }

            if (PlatformDetails.RunningOnMacOsx)
            {
                // macOS
                process.MinWorkingSet = new IntPtr(minWorkingSetInBytes);
                process.MaxWorkingSet = new IntPtr(maxWorkingSetInBytes);
                return;
            }

            const string groupName = "ravendb";
            var          basePath  = $"/sys/fs/cgroup/memory/{groupName}";
            var          fd        = Syscall.open(basePath, 0, 0);
            if (fd == -1)
            {
                if (Syscall.mkdir(basePath, (ushort)FilePermissions.S_IRWXU) == -1)
                {
                    logger.Info($"Failed to create directory path: {basePath}, error code: {Marshal.GetLastWin32Error()}");
                    return;
                }
            }

            Syscall.close(fd);

            var str = maxWorkingSetInBytes.ToString();
            if (WriteValue($"{basePath}/memory.limit_in_bytes", str, logger) == false)
            {
                return;
            }

            WriteValue($"{basePath}/cgroup.procs", str, logger);
#endif
        }
Exemplo n.º 4
0
        private TestResourceSnapshot GetTestResourceSnapshot(TestStage testStage, IAssemblyInfo assemblyInfo)
        {
            var timeStamp    = DateTime.UtcNow;
            var assemblyName = GetAssemblyShortName(assemblyInfo);
            var cpuUsage     = _metricCacher.GetValue(MetricCacher.Keys.Server.CpuUsage, _cpuUsageCalculator.Calculate);

            var memoryInfo = _metricCacher.GetValue <MemoryInfoResult>(MetricCacher.Keys.Server.MemoryInfoExtended);

            var snapshot = new TestResourceSnapshot
            {
                TotalScratchAllocatedMemory = new Size(MemoryInformation.GetTotalScratchAllocatedMemory(), SizeUnit.Bytes).GetValue(SizeUnit.Megabytes),
                TotalDirtyMemory            = new Size(MemoryInformation.GetDirtyMemoryState().TotalDirtyInBytes, SizeUnit.Bytes).GetValue(SizeUnit.Megabytes),
                IsHighDirty                = MemoryInformation.GetDirtyMemoryState().IsHighDirty,
                TestStage                  = testStage,
                Timestamp                  = timeStamp.ToString("o"),
                AssemblyName               = assemblyName,
                MachineCpuUsage            = (long)cpuUsage.MachineCpuUsage,
                ProcessCpuUsage            = (long)cpuUsage.ProcessCpuUsage,
                ProcessMemoryUsageInMb     = memoryInfo.WorkingSet.GetValue(SizeUnit.Megabytes),
                TotalMemoryInMb            = memoryInfo.TotalPhysicalMemory.GetValue(SizeUnit.Megabytes),
                TotalCommittableMemoryInMb = memoryInfo.TotalCommittableMemory.GetValue(SizeUnit.Megabytes),
                AvailableMemoryInMb        = memoryInfo.AvailableMemory.GetValue(SizeUnit.Megabytes),
                CurrentCommitChargeInMb    = memoryInfo.CurrentCommitCharge.GetValue(SizeUnit.Megabytes),
                SharedCleanMemoryInMb      = memoryInfo.SharedCleanMemory.GetValue(SizeUnit.Megabytes),
                TotalScratchDirtyMemory    = memoryInfo.TotalScratchDirtyMemory.GetValue(SizeUnit.Megabytes)
            };

            return(snapshot);
        }
Exemplo n.º 5
0
    // Update is called once per frame
    void Update()
    {
        if (TimerManager.instance == null)
        {
            return;
        }
        TimerManager.instance.Update();

        if (!GameEngine.instance.cpuNode.gameObject.activeSelf)
        {
            return;
        }

        MemoryInformation memInfo = Rainity.GetMemoryInformation();

        Ramt.text      = Mathf.Round(memInfo.ramUsed / memInfo.ramTotal * 100).ToString() + "%";
        RAM.fillAmount = memInfo.ramUsed / memInfo.ramTotal;
        // DiskInformation diskInfo = Rainity.GetDiskInformation("C:\\");



        if (timer <= 0)
        {
            timer = 1f;
            var cpuUsage = GetCPUPercent() / 1000000f;
            cput.text      = Mathf.Round(cpuUsage).ToString() + "%";
            cpu.fillAmount = cpuUsage / 100;
        }
        timer -= Time.deltaTime;
        //var d = Rainity.GetWeatherInformation();
        // Rainity.GetWallpaperImage();
        //int x = 0;
    }
        public static MachineResources GetMachineResources()
        {
            using (var currentProcess = Process.GetCurrentProcess())
            {
                var workingSet = PlatformDetails.RunningOnLinux == false
                        ? currentProcess.WorkingSet64
                        : MemoryInformation.GetRssMemoryUsage(currentProcess.Id);

                var memoryInfoResult = MemoryInformation.GetMemoryInfo();
                var cpuInfo          = CpuUsage.Calculate();

                var machineResources = new MachineResources
                {
                    TotalMemory        = memoryInfoResult.TotalPhysicalMemory.GetValue(SizeUnit.Bytes),
                    SystemCommitLimit  = memoryInfoResult.TotalCommittableMemory.GetValue(SizeUnit.Bytes),
                    CommitedMemory     = memoryInfoResult.CurrentCommitCharge.GetValue(SizeUnit.Bytes),
                    ProcessMemoryUsage = workingSet,
                    IsProcessMemoryRss = PlatformDetails.RunningOnPosix,
                    MachineCpuUsage    = cpuInfo.MachineCpuUsage,
                    ProcessCpuUsage    = Math.Min(cpuInfo.MachineCpuUsage, cpuInfo.ProcessCpuUsage) // min as sometimes +-1% due to time sampling
                };

                return(machineResources);
            }
        }
        public MemoryReader()
        {
            _processHandle = new IntPtr();

            _memoryInformation = new MemoryInformation();
            _systemInformation = new SystemInformation();
        }
        public static MachineResources GetMachineResources()
        {
            var currentProcess = Process.GetCurrentProcess();
            var workingSet     =
                PlatformDetails.RunningOnPosix == false || PlatformDetails.RunningOnMacOsx
                    ? currentProcess.WorkingSet64
                    : MemoryInformation.GetRssMemoryUsage(currentProcess.Id);
            var memoryInfoResult = MemoryInformation.GetMemoryInfo();
            var installedMemory  = memoryInfoResult.InstalledMemory.GetValue(SizeUnit.Bytes);
            var availableMemory  = memoryInfoResult.AvailableMemory.GetValue(SizeUnit.Bytes);
            var mappedSharedMem  = LowMemoryNotification.GetCurrentProcessMemoryMappedShared();
            var shared           = mappedSharedMem.GetValue(SizeUnit.Bytes);

            var cpuInfo          = CpuUsage.Calculate();
            var machineResources = new MachineResources
            {
                TotalMemory        = installedMemory,
                MachineMemoryUsage = installedMemory - availableMemory,
                ProcessMemoryUsage = workingSet,
                ProcessMemoryExcludingSharedUsage = Math.Max(workingSet - shared, 0),
                MachineCpuUsage = cpuInfo.MachineCpuUsage,
                ProcessCpuUsage = cpuInfo.ProcessCpuUsage
            };

            return(machineResources);
        }
Exemplo n.º 9
0
        public override void Print()
        {
            const string asciiHeader = @"       _____                       _____  ____ {0}      |  __ \                     |  __ \|  _ \ {0}      | |__) |__ ___   _____ _ __ | |  | | |_) |{0}      |  _  // _` \ \ / / _ \ '_ \| |  | |  _ < {0}      | | \ \ (_| |\ V /  __/ | | | |__| | |_) |{0}      |_|  \_\__,_| \_/ \___|_| |_|_____/|____/ {0}{0}";

            ConsoleWriteLineWithColor(ConsoleColor.DarkRed, asciiHeader, Environment.NewLine);
            ConsoleWriteLineWithColor(ConsoleColor.Cyan, "      Safe by default, optimized for efficiency");
            _tw.WriteLine();

            const string lineBorder = "+---------------------------------------------------------------+";

            var meminfo = MemoryInformation.GetMemoryInfo();

            ConsoleWriteLineWithColor(ConsoleColor.Yellow, " Build {0}, Version {1}, SemVer {2}, Commit {3}\r\n PID {4}, {5} bits, {6} Cores, Phys Mem {7}, Arch: {8}",
                                      ServerVersion.Build, ServerVersion.Version, ServerVersion.FullVersion, ServerVersion.CommitHash, Process.GetCurrentProcess().Id,
                                      IntPtr.Size * 8, ProcessorInfo.ProcessorCount, meminfo.TotalPhysicalMemory, RuntimeInformation.OSArchitecture);
            ConsoleWriteLineWithColor(ConsoleColor.DarkCyan, " Source Code (git repo): https://github.com/ravendb/ravendb");
            ConsoleWriteWithColor(new ConsoleText {
                Message = " Built with ", ForegroundColor = ConsoleColor.Gray
            },
                                  new ConsoleText {
                Message = "love ", ForegroundColor = ConsoleColor.Red
            },
                                  new ConsoleText {
                Message = "by ", ForegroundColor = ConsoleColor.Gray
            },
                                  new ConsoleText {
                Message = "Hibernating Rhinos ", ForegroundColor = ConsoleColor.Yellow
            },
                                  new ConsoleText {
                Message = "and awesome contributors!", ForegroundColor = ConsoleColor.Gray, IsNewLinePostPended = true
            });
            _tw.WriteLine(lineBorder);
        }
Exemplo n.º 10
0
        private static ProcessMemoryUsage GetProcessMemoryUsage(MemoryInfoResult memoryInfo)
        {
            var workingSetInBytes = memoryInfo.WorkingSet.GetValue(SizeUnit.Bytes);
            var privateMemory     = MemoryInformation.GetManagedMemoryInBytes() + MemoryInformation.GetUnManagedAllocationsInBytes();

            return(new ProcessMemoryUsage(workingSetInBytes, privateMemory));
        }
Exemplo n.º 11
0
        public static bool CanIncreaseMemoryUsageForThread()
        {
            var memoryInfo = MemoryInformation.GetMemoryInformationUsingOneTimeSmapsReader();
            var memoryAssumedFreeOrCheapToFree = memoryInfo.AvailableMemoryForProcessing;
            var allocatedForProcessing         = GetTotalCurrentlyAllocatedForProcessing();

            return(memoryAssumedFreeOrCheapToFree >= allocatedForProcessing);
        }
Exemplo n.º 12
0
        public MemoryConfiguration()
        {
            var memoryInfo = MemoryInformation.GetMemoryInfo();

            LowMemoryLimit = Size.Min(
                new Size(2, SizeUnit.Gigabytes),
                memoryInfo.TotalPhysicalMemory / 10);
        }
Exemplo n.º 13
0
        protected override Gauge32 GetData()
        {
            lock (this)
            {
                var memoryInfo = MemoryInformation.GetMemoryInfo(_smapsReader?.Value, extended: true);

                return(new Gauge32(memoryInfo.WorkingSet.GetValue(SizeUnit.Megabytes)));
            }
        }
Exemplo n.º 14
0
        private static async Task Main(string[] args)
        {
            double cpu = await Stats.GetCurrentCpuUsagePercentageAsync(2);

            MemoryInformation memory = await Stats.GetMemoryInformationAsync(2);

            Console.WriteLine($"CPU: {cpu}%");
            Console.WriteLine($"Memory: {memory.UsedGigabytes}/{memory.TotalGigabytes} ({memory.FreeGigabytes} free)");
        }
Exemplo n.º 15
0
 private void AppMemoryControllerOnDiagnosticUpdate(object sender, MemoryInformation memInfo)
 {
     Dispatcher.BeginInvoke(() =>
     {
         TxtAppMemory.Text      = String.Format("RAM: {0}", memInfo.AppMemoryUsage.ToStringAndSuffix(2));
         TxtAppMemoryLimit.Text = String.Format("MAX: {0}", memInfo.AppMemoryLimit.ToStringAndSuffix(2));
         TxtAppMemoryPeak.Text  = String.Format("PEAK: {0}", memInfo.AppMemoryPeak.ToStringAndSuffix(2));
         TxtDeviceMemory.Text   = String.Format("PHONE: {0}", memInfo.DeviceMemory.ToStringAndSuffix(2));
     });
 }
Exemplo n.º 16
0
        public MemoryConfiguration()
        {
            var memoryInfo = MemoryInformation.GetMemoryInfo();

            LowMemoryLimit = Size.Min(
                new Size(2, SizeUnit.Gigabytes),
                memoryInfo.TotalPhysicalMemory / 10);

            UseRssInsteadOfMemUsage = PlatformDetails.RunningOnDocker;
        }
Exemplo n.º 17
0
        public MemoryConfiguration(RavenConfiguration configuration)
        {
            var memoryInfo = MemoryInformation.GetMemoryInfo();

            // we allow 1 GB by default, or up to 75% of available memory on startup, if less than that is available
            LimitForProcessing = Size.Min(new Size(1024, SizeUnit.Megabytes), memoryInfo.AvailableMemory * 0.75);

            LowMemoryForLinuxDetection = Size.Min(new Size(16, SizeUnit.Megabytes), memoryInfo.AvailableMemory * 0.10);

            MemoryCacheLimit = GetDefaultMemoryCacheLimit(memoryInfo.TotalPhysicalMemory);

            AvailableMemoryForRaisingBatchSizeLimit = Size.Min(new Size(768, SizeUnit.Megabytes), memoryInfo.TotalPhysicalMemory / 2);
        }
        public TransactionMergerConfiguration(bool forceUsing32BitsPager)
        {
            if (IntPtr.Size == sizeof(int) || forceUsing32BitsPager)
            {
                MaxTxSize = new Size(4, SizeUnit.Megabytes);
                return;
            }

            var memoryInfo = MemoryInformation.GetMemoryInfo();

            MaxTxSize = Size.Min(
                new Size(512, SizeUnit.Megabytes),
                memoryInfo.TotalPhysicalMemory / 10);
        }
Exemplo n.º 19
0
        public void Read(string path, string name)
        {
            using (IO.XmlStream s = new BlamLib.IO.XmlStream(path, name, this))
            {
                s.ReadAttribute("game", ref engine);

                foreach (XmlNode n in s.Cursor.ChildNodes)
                {
                    if (n.Name == "memory")
                    {
                        s.SaveCursor(n);
                        MemoryInfo = new MemoryInformation(s);
                        s.RestoreCursor();
                    }
                    else if (n.Name == "fieldTypes")
                    {
                        s.SaveCursor(n);
                        foreach (XmlNode n2 in s.Cursor.ChildNodes)
                        {
                            if (n2.Name != "type")
                            {
                                continue;
                            }

                            s.SaveCursor(n2);
                            fieldTypes.Add(new FieldType(s));
                            s.RestoreCursor();
                        }
                        s.RestoreCursor();
                    }
                    else if (n.Name == "editorMarkup")
                    {
                        s.SaveCursor(n);
                        foreach (XmlNode n2 in s.Cursor.ChildNodes)
                        {
                            if (n2.Name != "entry")
                            {
                                continue;
                            }

                            //s.SaveCursor(n2);
                            // TODO
                            //s.RestoreCursor();
                        }
                        s.RestoreCursor();
                    }
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// 获取内存实体对象信息
        /// </summary>
        /// <returns>返回内存实体对象</returns>
        public static MemoryInformation GetMemoryInformation()
        {
            try
            {
                MemoryInformation memInfor = new MemoryInformation();

                GlobalMemoryStatus(ref memInfor);

                return(memInfor);
            }
            catch (Exception)
            {
                return(new MemoryInformation());
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// 内存利用率函数,返回已使用率,(单位 %,百分百)
        /// </summary>
        /// <returns>返回使用率</returns>
        public static int GetMemoryUsageRate()
        {
            try
            {
                MemoryInformation memInfor = new MemoryInformation();

                GlobalMemoryStatus(ref memInfor);

                return(memInfor.MemoryUtilizationRate.ToString().ToInt());
            }
            catch (Exception)
            {
                return(0);
            }
        }
Exemplo n.º 22
0
        private static MessageDetails OutOfMemoryDetails(Exception exception)
        {
            var memoryInfo = MemoryInformation.GetMemoryInformationUsingOneTimeSmapsReader();

            return(new MessageDetails
            {
                Message = $"Managed memory: {new Size(AbstractLowMemoryMonitor.GetManagedMemoryInBytes(), SizeUnit.Bytes)}, " +
                          $"Unmanaged allocations: {new Size(AbstractLowMemoryMonitor.GetUnmanagedAllocationsInBytes(), SizeUnit.Bytes)}, " +
                          $"Shared clean: {memoryInfo.SharedCleanMemory}, " +
                          $"Working set: {memoryInfo.WorkingSet}, " +
                          $"Available memory: {memoryInfo.AvailableMemory}, " +
                          $"Calculated Available memory: {memoryInfo.AvailableWithoutTotalCleanMemory}, " +
                          $"Total memory: {memoryInfo.TotalPhysicalMemory} {Environment.NewLine}" +
                          $"Error: {exception}"
            });
        }
Exemplo n.º 23
0
    /// <summary>
    /// <para>Gets information about memory and video memory usage.</para>
    /// </summary>
    /// <returns>A Rainity.MemoryInformation structure with all the information received</returns>
    public static MemoryInformation GetMemoryInformation()
    {
        long memTotal  = 0;
        long memUsed   = 0;
        long vMemTotal = 0;
        long vMemUsed  = 0;

        GetMemoryInfo(out memTotal, out memUsed, out vMemTotal, out vMemUsed);
        MemoryInformation memInfo = new MemoryInformation();

        memInfo.ramTotal  = (float)memTotal;
        memInfo.ramUsed   = (float)memUsed;
        memInfo.vRamTotal = (float)vMemTotal;
        memInfo.vRamUsed  = (float)vMemUsed;
        return(memInfo);
    }
Exemplo n.º 24
0
        private static byte *ThrowFailedToAllocate(long size, ThreadStats thread, OutOfMemoryException e)
        {
            long allocated = 0;

            foreach (var threadAllocationsValue in AllThreadStats)
            {
                allocated += threadAllocationsValue.TotalAllocated;
            }
            var managed         = MemoryInformation.GetManagedMemoryInBytes();
            var unmanagedMemory = MemoryInformation.GetUnManagedAllocationsInBytes();

            throw new OutOfMemoryException($"Failed to allocate additional {new Size(size, SizeUnit.Bytes)} " +
                                           $"to already allocated {new Size(thread.TotalAllocated, SizeUnit.Bytes)} by this thread. " +
                                           $"Total allocated by all threads: {new Size(allocated, SizeUnit.Bytes)}, " +
                                           $"Managed memory: {new Size(managed, SizeUnit.Bytes)}, " +
                                           $"Un-managed memory: {new Size(unmanagedMemory, SizeUnit.Bytes)}", e);
        }
Exemplo n.º 25
0
    // Update is called once per frame
    void Update()
    {
        MemoryInformation memInfo = Rainity.GetMemoryInformation();

        ramText.text         = Mathf.Round(memInfo.ramUsed / memInfo.ramTotal * 100).ToString() + "%";
        ramImage.fillAmount  = memInfo.ramUsed / memInfo.ramTotal;
        vramText.text        = Mathf.Round(memInfo.vRamUsed / memInfo.vRamTotal * 100).ToString() + "%";
        vramImage.fillAmount = memInfo.vRamUsed / memInfo.vRamTotal;

        DiskInformation diskInfo = Rainity.GetDiskInformation("C:\\");

        diskText.text        = Mathf.Round((float)diskInfo.bytesFree / (float)diskInfo.bytesTotal * 100).ToString() + "%";
        diskImage.fillAmount = (float)diskInfo.bytesFree / (float)diskInfo.bytesTotal;

        cpuText.text        = Mathf.Round(Rainity.GetCPUUsagePercent()).ToString() + "%";
        cpuImage.fillAmount = Rainity.GetCPUUsagePercent() / 100;
    }
Exemplo n.º 26
0
        /// <summary>
        /// This functions queries the different software / hardware records in order to get their properties
        /// </summary>
        /// <returns>0 if success and -1 if an exception arises</returns>
        public int Run()
        {
            try
            {
                int error = 0;

                // Gather generic system information
                PlatformInformation.GetSystemInfo();

                // Get specific CPU information
                GetCPUInfo();

                // Get memory information
                GetMemoryInfo();

                // Compute memory parameters
                MemoryInformation.GetMemoryInfo(System_Memory);
#if DEBUG
                Console.WriteLine(MemoryInformation.ToString());
#endif

                if (Globals.Enable_File_Output)
                {
                    Tools.SaveData(Globals.Output_Filename, $"{MemoryInformation.ToString()}\n", true);
                }

                // Get video controller information
                GetVideoControllerInfo();

                // Get disk information
                GetDiskDriveInfo();

                // Get disk partitions
                GetDiskPartitionInfo();

                return(error);
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine($"Exception Message: {ex.Message}");
#endif
                return(-1);
            }
        }
Exemplo n.º 27
0
        public LongRunningWork LongRunning(Action <object> action, object state, string name)
        {
            if (_pool.TryDequeue(out var pooled) == false)
            {
                MemoryInformation.AssertNotAboutToRunOutOfMemory(_minimumFreeCommittedMemory);

                pooled = new PooledThread(this);
                var thread = new Thread(pooled.Run)
                {
                    Name         = name,
                    IsBackground = true,
                };

                thread.Start();
            }
            pooled.StartedAt = DateTime.UtcNow;
            return(pooled.SetWorkForThread(action, state, name));
        }
Exemplo n.º 28
0
        public void WhenActualSwapSmallerThenMinSwapConfigured_ShouldRaiseNotification()
        {
            var memoryInfoResult = MemoryInformation.GetMemoryInfo();
            var minSwapConfig    = memoryInfoResult.TotalSwapSize + new Sparrow.Size(130, SizeUnit.Megabytes);
            var customSettings   = new Dictionary <string, string>
            {
                [RavenConfiguration.GetKey(x => x.PerformanceHints.MinSwapSize)] = minSwapConfig.GetValue(SizeUnit.Megabytes).ToString()
            };

            UseNewLocalServer(customSettings);

            using var dis = Server.ServerStore.NotificationCenter.GetStored(out var alerts, postponed: false);
            var alertsList = alerts.ToList();

            var isLowSwapSizeRaised = alertsList.Any(a => a.Json[nameof(AlertRaised.AlertType)].ToString() == AlertType.LowSwapSize.ToString());

            Assert.True(isLowSwapSizeRaised, $"Actual swap {memoryInfoResult.TotalSwapSize}, min swap config {minSwapConfig}, total memory {memoryInfoResult.TotalPhysicalMemory}");
        }
Exemplo n.º 29
0
        public LongRunningWork LongRunning(Action <object> action, object state, string name)
        {
            if (_pool.TryDequeue(out var pooled) == false)
            {
                MemoryInformation.AssertNotAboutToRunOutOfMemory();

                pooled = new PooledThread(this);
                var thread = new Thread(pooled.Run, PlatformDetails.Is32Bits ? 512 * Constants.Size.Kilobyte : 0)
                {
                    Name         = name,
                    IsBackground = true,
                };

                thread.Start();
            }
            pooled.StartedAt = DateTime.UtcNow;
            return(pooled.SetWorkForThread(action, state, name));
        }
Exemplo n.º 30
0
        private MemoryMetrics GetMemoryMetrics()
        {
            var result           = new MemoryMetrics();
            var memoryInfoResult = Server.MetricCacher.GetValue <MemoryInfoResult>(MetricCacher.Keys.Server.MemoryInfoExtended);

            result.InstalledMemoryInMb = memoryInfoResult.InstalledMemory.GetValue(SizeUnit.Megabytes);
            result.PhysicalMemoryInMb  = memoryInfoResult.TotalPhysicalMemory.GetValue(SizeUnit.Megabytes);
            result.AllocatedMemoryInMb = memoryInfoResult.WorkingSet.GetValue(SizeUnit.Megabytes);
            result.LowMemorySeverity   = LowMemoryNotification.Instance.IsLowMemory(memoryInfoResult,
                                                                                    new LowMemoryMonitor(), out _);

            result.TotalSwapSizeInMb       = memoryInfoResult.TotalSwapSize.GetValue(SizeUnit.Megabytes);
            result.TotalSwapUsageInMb      = memoryInfoResult.TotalSwapUsage.GetValue(SizeUnit.Megabytes);
            result.WorkingSetSwapUsageInMb = memoryInfoResult.WorkingSetSwapUsage.GetValue(SizeUnit.Megabytes);

            var totalDirtyInBytes = MemoryInformation.GetDirtyMemoryState().TotalDirtyInBytes;

            result.TotalDirtyInMb = new Size(totalDirtyInBytes, SizeUnit.Bytes).GetValue(SizeUnit.Megabytes);

            return(result);
        }
Exemplo n.º 31
0
		public void Read(string path, string name)
		{
			using (IO.XmlStream s = new BlamLib.IO.XmlStream(path, name, this))
			{
				s.ReadAttribute("game", ref engine);

				foreach (XmlNode n in s.Cursor.ChildNodes)
					if (n.Name == "memory")
					{
						s.SaveCursor(n);
							MemoryInfo = new MemoryInformation(s);
						s.RestoreCursor();
					}
					else if (n.Name == "fieldTypes")
					{
						s.SaveCursor(n);
						foreach (XmlNode n2 in s.Cursor.ChildNodes)
						{
							if (n2.Name != "type") continue;

							s.SaveCursor(n2);
								fieldTypes.Add(new FieldType(s));
							s.RestoreCursor();
						}
						s.RestoreCursor();
					}
					else if(n.Name == "editorMarkup")
					{
						s.SaveCursor(n);
						foreach (XmlNode n2 in s.Cursor.ChildNodes)
						{
							if (n2.Name != "entry") continue;

							//s.SaveCursor(n2);
							// TODO
							//s.RestoreCursor();
						}
						s.RestoreCursor();
					}
			}
		}