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 }
public static void EmptyWorkingSet(Logger logger) { if (PlatformDetails.RunningOnPosix) { return; } using (var process = Process.GetCurrentProcess()) { const QuotaLimit flags = QuotaLimit.QUOTA_LIMITS_HARDWS_MAX_ENABLE; var result = SetProcessWorkingSetSizeEx(process.Handle, -1, -1, flags); if (result == false) { logger.Info($"Failed to empty working set, error code: {Marshal.GetLastWin32Error()}"); } } }
internal static extern bool SetProcessWorkingSetSizeEx(IntPtr pProcess, long dwMinimumWorkingSetSize, long dwMaximumWorkingSetSize, QuotaLimit flags);