util.{hh,cc}: Split out current-process.{hh,cc}

Change-Id: I77095b9d37e85310075bada7a076ccd482c28e47
This commit is contained in:
Tom Hubrecht 2024-05-28 13:36:02 +02:00
parent 9a52e4688c
commit 2473e1253d
14 changed files with 157 additions and 113 deletions

View file

@ -6,6 +6,7 @@
#include "signals.hh"
#include "loggers.hh"
#include "progress-bar.hh"
#include "current-process.hh"
#include <algorithm>
#include <cctype>

View file

@ -6,7 +6,6 @@
#include "builtins/buildenv.hh"
#include "path-references.hh"
#include "finally.hh"
#include "util.hh"
#include "archive.hh"
#include "compression.hh"
#include "daemon.hh"

View file

@ -5,6 +5,7 @@
#include "args.hh"
#include "abstract-setting-to-json.hh"
#include "compute-levels.hh"
#include "current-process.hh"
#include <algorithm>
#include <map>

View file

@ -1,3 +1,4 @@
#include "current-process.hh"
#include "environment-variables.hh"
#include "ssh.hh"
#include "finally.hh"

View file

@ -0,0 +1,109 @@
#include "current-process.hh"
#include "file-system.hh"
#include "logging.hh"
#include "signals.hh"
#include "util.hh"
#ifdef __APPLE__
# include <mach-o/dyld.h>
#endif
#if __linux__
# include <sys/resource.h>
#endif
#include <sys/mount.h>
#include <cgroup.hh>
namespace nix {
unsigned int getMaxCPU()
{
#if __linux__
try {
auto cgroupFS = getCgroupFS();
if (!cgroupFS) return 0;
auto cgroups = getCgroups("/proc/self/cgroup");
auto cgroup = cgroups[""];
if (cgroup == "") return 0;
auto cpuFile = *cgroupFS + "/" + cgroup + "/cpu.max";
auto cpuMax = readFile(cpuFile);
auto cpuMaxParts = tokenizeString<std::vector<std::string>>(cpuMax, " \n");
if (cpuMaxParts.size() != 2) {
return 0;
}
auto quota = cpuMaxParts[0];
auto period = cpuMaxParts[1];
if (quota != "max")
return std::ceil(std::stoi(quota) / std::stof(period));
} catch (Error &) { ignoreException(lvlDebug); }
#endif
return 0;
}
rlim_t savedStackSize = 0;
void setStackSize(rlim_t stackSize)
{
struct rlimit limit;
if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur < stackSize) {
savedStackSize = limit.rlim_cur;
limit.rlim_cur = std::min(stackSize, limit.rlim_max);
if (setrlimit(RLIMIT_STACK, &limit) != 0) {
logger->log(
lvlError,
HintFmt(
"Failed to increase stack size from %1% to %2% (maximum allowed stack size: %3%): %4%",
savedStackSize,
stackSize,
limit.rlim_max,
std::strerror(errno)
).str()
);
}
}
}
void restoreProcessContext(bool restoreMounts)
{
restoreSignals();
if (restoreMounts) {
restoreMountNamespace();
}
if (savedStackSize) {
struct rlimit limit;
if (getrlimit(RLIMIT_STACK, &limit) == 0) {
limit.rlim_cur = savedStackSize;
setrlimit(RLIMIT_STACK, &limit);
}
}
}
std::optional<Path> getSelfExe()
{
static auto cached = []() -> std::optional<Path>
{
#if __linux__
return readLink("/proc/self/exe");
#elif __APPLE__
char buf[1024];
uint32_t size = sizeof(buf);
if (_NSGetExecutablePath(buf, &size) == 0)
return buf;
else
return std::nullopt;
#else
return std::nullopt;
#endif
}();
return cached;
}
}

View file

@ -0,0 +1,37 @@
#pragma once
///@file
#include <optional>
#include <sys/resource.h>
#include "types.hh"
namespace nix {
/**
* If cgroups are active, attempt to calculate the number of CPUs available.
* If cgroups are unavailable or if cpu.max is set to "max", return 0.
*/
unsigned int getMaxCPU();
/**
* Change the stack size.
*/
void setStackSize(rlim_t stackSize);
/**
* Restore the original inherited Unix process context (such as signal
* masks, stack size).
* See startSignalHandlerThread(), saveSignalMask().
*/
void restoreProcessContext(bool restoreMounts = true);
/**
* @return the path of the current executable.
*/
std::optional<Path> getSelfExe();
}

View file

@ -6,6 +6,7 @@ libutil_sources = files(
'compression.cc',
'compute-levels.cc',
'config.cc',
'current-process.cc',
'english.cc',
'environment-variables.cc',
'error.cc',
@ -56,6 +57,7 @@ libutil_headers = files(
'compute-levels.hh',
'config-impl.hh',
'config.hh',
'current-process.hh',
'english.hh',
'environment-variables.hh',
'error.hh',

View file

@ -1,3 +1,4 @@
#include "current-process.hh"
#include "environment-variables.hh"
#include "finally.hh"
#include "logging.hh"

View file

@ -1,5 +1,6 @@
#include "util.hh"
#include "processes.hh"
#include "current-process.hh"
#include "sync.hh"
#include "finally.hh"
@ -148,59 +149,11 @@ Path createNixStateDir()
}
std::optional<Path> getSelfExe()
{
static auto cached = []() -> std::optional<Path>
{
#if __linux__
return readLink("/proc/self/exe");
#elif __APPLE__
char buf[1024];
uint32_t size = sizeof(buf);
if (_NSGetExecutablePath(buf, &size) == 0)
return buf;
else
return std::nullopt;
#else
return std::nullopt;
#endif
}();
return cached;
}
//////////////////////////////////////////////////////////////////////
unsigned int getMaxCPU()
{
#if __linux__
try {
auto cgroupFS = getCgroupFS();
if (!cgroupFS) return 0;
auto cgroups = getCgroups("/proc/self/cgroup");
auto cgroup = cgroups[""];
if (cgroup == "") return 0;
auto cpuFile = *cgroupFS + "/" + cgroup + "/cpu.max";
auto cpuMax = readFile(cpuFile);
auto cpuMaxParts = tokenizeString<std::vector<std::string>>(cpuMax, " \n");
if (cpuMaxParts.size() != 2) {
return 0;
}
auto quota = cpuMaxParts[0];
auto period = cpuMaxParts[1];
if (quota != "max")
return std::ceil(std::stoi(quota) / std::stof(period));
} catch (Error &) { ignoreException(lvlDebug); }
#endif
return 0;
}
//////////////////////////////////////////////////////////////////////
@ -454,28 +407,6 @@ std::pair<std::string_view, std::string_view> getLine(std::string_view s)
//////////////////////////////////////////////////////////////////////
rlim_t savedStackSize = 0;
void setStackSize(rlim_t stackSize)
{
struct rlimit limit;
if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur < stackSize) {
savedStackSize = limit.rlim_cur;
limit.rlim_cur = std::min(stackSize, limit.rlim_max);
if (setrlimit(RLIMIT_STACK, &limit) != 0) {
logger->log(
lvlError,
HintFmt(
"Failed to increase stack size from %1% to %2% (maximum allowed stack size: %3%): %4%",
savedStackSize,
stackSize,
limit.rlim_max,
std::strerror(errno)
).str()
);
}
}
}
#if __linux__
static AutoCloseFD fdSavedMountNamespace;
@ -528,22 +459,6 @@ void unshareFilesystem()
#endif
}
void restoreProcessContext(bool restoreMounts)
{
restoreSignals();
if (restoreMounts) {
restoreMountNamespace();
}
if (savedStackSize) {
struct rlimit limit;
if (getrlimit(RLIMIT_STACK, &limit) == 0) {
limit.rlim_cur = savedStackSize;
setrlimit(RLIMIT_STACK, &limit);
}
}
}
AutoCloseFD createUnixDomainSocket()
{
AutoCloseFD fdSocket{socket(PF_UNIX, SOCK_STREAM

View file

@ -71,11 +71,6 @@ std::vector<Path> getConfigDirs();
*/
Path getDataDir();
/**
* @return the path of the current executable.
*/
std::optional<Path> getSelfExe();
/**
* @return $XDG_STATE_HOME or $HOME/.local/state.
*
@ -91,27 +86,6 @@ Path getStateDir();
Path createNixStateDir();
/**
* If cgroups are active, attempt to calculate the number of CPUs available.
* If cgroups are unavailable or if cpu.max is set to "max", return 0.
*/
unsigned int getMaxCPU();
/**
* Change the stack size.
*/
void setStackSize(rlim_t stackSize);
/**
* Restore the original inherited Unix process context (such as signal
* masks, stack size).
* See startSignalHandlerThread(), saveSignalMask().
*/
void restoreProcessContext(bool restoreMounts = true);
/**
* Save the current mount namespace. Ignored if called more than
* once.

View file

@ -13,6 +13,7 @@
#include "store-api.hh"
#include "local-fs-store.hh"
#include "globals.hh"
#include "current-process.hh"
#include "derivations.hh"
#include "util.hh"
#include "shared.hh"

View file

@ -4,6 +4,7 @@
#include "attr-path.hh"
#include "progress-bar.hh"
#include "editor-for.hh"
#include "current-process.hh"
#include <unistd.h>

View file

@ -3,6 +3,7 @@
#include "args/root.hh"
#include "command.hh"
#include "common-args.hh"
#include "current-process.hh"
#include "eval.hh"
#include "eval-settings.hh"
#include "globals.hh"

View file

@ -10,6 +10,7 @@
#include "progress-bar.hh"
#include "eval.hh"
#include "build/personality.hh"
#include "current-process.hh"
#if __linux__
#include <sys/mount.h>