From b52f6bee042c087668b812da2ce9462f20671ba3 Mon Sep 17 00:00:00 2001 From: regnat Date: Fri, 18 Sep 2020 16:32:49 +0200 Subject: [PATCH] Make the loggers truly pluggable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove the static list of possible loggers, and instead generate it dynamically from the registered ones. This requires a conceptually small but textually invasive refactoring as to remove some undefined behavior wrt. the orders in which static variables are initialised, we change `nix::config` from a static variable to a function that lazily builds a `Config` object and returns it (the reason for that is that with a static `Config`, we might − and apparantly do in practice − get the list of registered loggers before they are all registered, leading to an incomplete list in the help/man/completion). --- doc/manual/command-ref/conf-file.xml | 2 +- doc/manual/src/figures/user-environments.sxd | Bin 8412 -> 8418 bytes perl/lib/Nix/Store.xs | 6 +- src/build-remote/build-remote.cc | 12 +- src/libexpr/eval-cache.cc | 2 +- src/libexpr/eval.cc | 8 +- src/libexpr/flake/flake.cc | 4 +- src/libexpr/parser.y | 2 +- src/libexpr/primops.cc | 12 +- src/libexpr/primops/context.cc | 2 +- src/libexpr/primops/fetchTree.cc | 2 +- src/libfetchers/cache.cc | 2 +- src/libfetchers/git.cc | 6 +- src/libfetchers/github.cc | 4 +- src/libfetchers/mercurial.cc | 4 +- src/libfetchers/registry.cc | 4 +- src/libmain/common-args.cc | 2 +- src/libmain/shared.cc | 32 ++-- src/libstore/build.cc | 172 +++++++++--------- src/libstore/builtins/fetchurl.cc | 6 +- src/libstore/crypto.cc | 4 +- src/libstore/daemon.cc | 28 +-- src/libstore/derivations.cc | 4 +- src/libstore/filetransfer.cc | 8 +- src/libstore/gc.cc | 10 +- src/libstore/globals.cc | 55 +++--- src/libstore/globals.hh | 20 +- src/libstore/http-binary-cache-store.cc | 2 +- src/libstore/legacy-ssh-store.cc | 10 +- src/libstore/local-store.cc | 34 ++-- src/libstore/local-store.hh | 2 +- src/libstore/machines.cc | 4 +- src/libstore/misc.cc | 2 +- src/libstore/nar-info-disk-cache.cc | 8 +- src/libstore/optimise-store.cc | 2 +- src/libstore/parsed-derivations.cc | 4 +- src/libstore/profiles.cc | 4 +- src/libstore/remote-store.cc | 34 ++-- src/libstore/s3-binary-cache-store.cc | 2 +- src/libstore/ssh-store.cc | 2 +- src/libstore/store-api.cc | 14 +- src/libstore/store-api.hh | 10 +- src/libutil/config.hh | 2 +- src/libutil/loggers.cc | 25 ++- src/libutil/loggers.hh | 17 +- src/nix-build/nix-build.cc | 4 +- src/nix-channel/nix-channel.cc | 10 +- .../nix-collect-garbage.cc | 2 +- src/nix-daemon/nix-daemon.cc | 12 +- src/nix-env/nix-env.cc | 18 +- src/nix-instantiate/nix-instantiate.cc | 4 +- src/nix-store/nix-store.cc | 22 +-- src/nix/bundle.cc | 6 +- src/nix/develop.cc | 4 +- src/nix/doctor.cc | 2 +- src/nix/flake.cc | 8 +- src/nix/installables.cc | 10 +- src/nix/log.cc | 2 +- src/nix/main.cc | 18 +- src/nix/repl.cc | 8 +- src/nix/run.cc | 4 +- src/nix/search.cc | 6 +- src/nix/upgrade-nix.cc | 4 +- .../resolve-system-dependencies.cc | 2 +- 64 files changed, 376 insertions(+), 361 deletions(-) diff --git a/doc/manual/command-ref/conf-file.xml b/doc/manual/command-ref/conf-file.xml index d0f1b09ca81..dc75b3651eb 100644 --- a/doc/manual/command-ref/conf-file.xml +++ b/doc/manual/command-ref/conf-file.xml @@ -613,7 +613,7 @@ password my-password RegisterStoreImplementation to add new store implementations, RegisterCommand to add new subcommands to the nix command, and RegisterSetting to add new - nix config settings. See the constructors for those types for + nix config settings()-> See the constructors for those types for more details. diff --git a/doc/manual/src/figures/user-environments.sxd b/doc/manual/src/figures/user-environments.sxd index bc661b6406fb855dd06436bb8f10986c9c44ffac..48489f69638661edd63019c42d28ae0b56375f20 100644 GIT binary patch delta 26 ecmccP_{ed?Z*dk4O store() if (!_store) { try { loadConfFile(); - settings.lockCPU = false; + settings()->lockCPU = false; _store = openStore(); } catch (Error & e) { croak("%s", e.what()); @@ -355,9 +355,9 @@ void addTempRoot(char * storePath) SV * getBinDir() PPCODE: - XPUSHs(sv_2mortal(newSVpv(settings.nixBinDir.c_str(), 0))); + XPUSHs(sv_2mortal(newSVpv(settings()->nixBinDir.c_str(), 0))); SV * getStoreDir() PPCODE: - XPUSHs(sv_2mortal(newSVpv(settings.nixStore.c_str(), 0))); + XPUSHs(sv_2mortal(newSVpv(settings()->nixStore.c_str(), 0))); diff --git a/src/build-remote/build-remote.cc b/src/build-remote/build-remote.cc index ce51271132c..22668f04751 100644 --- a/src/build-remote/build-remote.cc +++ b/src/build-remote/build-remote.cc @@ -60,14 +60,14 @@ static int _main(int argc, char * * argv) FdSource source(STDIN_FILENO); - /* Read the parent's settings. */ + /* Read the parent's settings()-> */ while (readInt(source)) { auto name = readString(source); auto value = readString(source); - settings.set(name, value); + settings()->set(name, value); } - settings.maxBuildJobs.set("1"); // hack to make tests with local?root= work + settings()->maxBuildJobs.set("1"); // hack to make tests with local?root= work initPlugins(); @@ -104,8 +104,8 @@ static int _main(int argc, char * * argv) auto requiredFeatures = readStrings>(source); auto canBuildLocally = amWilling - && ( neededSystem == settings.thisSystem - || settings.extraPlatforms.get().count(neededSystem) > 0) + && ( neededSystem == settings()->thisSystem + || settings()->extraPlatforms.get().count(neededSystem) > 0) && allSupportedLocally(*store, requiredFeatures); /* Error ignored here, will be caught later */ @@ -265,7 +265,7 @@ static int _main(int argc, char * * argv) signal(SIGALRM, old); } - auto substitute = settings.buildersUseSubstitutes ? Substitute : NoSubstitute; + auto substitute = settings()->buildersUseSubstitutes ? Substitute : NoSubstitute; { Activity act(*logger, lvlTalkative, actUnknown, fmt("copying dependencies to '%s'", storeUri)); diff --git a/src/libexpr/eval-cache.cc b/src/libexpr/eval-cache.cc index 381344b4002..c48e1fc1017 100644 --- a/src/libexpr/eval-cache.cc +++ b/src/libexpr/eval-cache.cc @@ -606,7 +606,7 @@ StorePath AttrCursor::forceDerivation() { auto aDrvPath = getAttr(root->state.sDrvPath, true); auto drvPath = root->state.store->parseStorePath(aDrvPath->getString()); - if (!root->state.store->isValidPath(drvPath) && !settings.readOnlyMode) { + if (!root->state.store->isValidPath(drvPath) && !settings()->readOnlyMode) { /* The eval cache contains 'drvPath', but the actual path has been garbage-collected. So force it to be regenerated. */ aDrvPath->forceValue(); diff --git a/src/libexpr/eval.cc b/src/libexpr/eval.cc index 139067f200b..11ab71145f9 100644 --- a/src/libexpr/eval.cc +++ b/src/libexpr/eval.cc @@ -372,7 +372,7 @@ EvalState::EvalState(const Strings & _searchPath, ref store) } try { - addToSearchPath("nix=" + canonPath(settings.nixDataDir + "/nix/corepkgs", true)); + addToSearchPath("nix=" + canonPath(settings()->nixDataDir + "/nix/corepkgs", true)); } catch (Error &) { } @@ -1820,7 +1820,7 @@ string EvalState::copyPathToStore(PathSet & context, const Path & path) if (i != srcToStore.end()) dstPath = store->printStorePath(i->second); else { - auto p = settings.readOnlyMode + auto p = settings()->readOnlyMode ? store->computeStorePathForPath(std::string(baseNameOf(path)), checkSourcePath(path)).first : store->addToStore(std::string(baseNameOf(path)), checkSourcePath(path), FileIngestionMethod::Recursive, htSHA256, defaultPathFilter, repair); dstPath = store->printStorePath(p); @@ -2073,8 +2073,8 @@ Strings EvalSettings::getDefaultNixPath() Strings res; auto add = [&](const Path & p) { if (pathExists(p)) { res.push_back(p); } }; add(getHome() + "/.nix-defexpr/channels"); - add("nixpkgs=" + settings.nixStateDir + "/nix/profiles/per-user/root/channels/nixpkgs"); - add(settings.nixStateDir + "/nix/profiles/per-user/root/channels"); + add("nixpkgs=" + settings()->nixStateDir + "/nix/profiles/per-user/root/channels/nixpkgs"); + add(settings()->nixStateDir + "/nix/profiles/per-user/root/channels"); return res; } diff --git a/src/libexpr/flake/flake.cc b/src/libexpr/flake/flake.cc index 01f464859e5..eda3b2c9568 100644 --- a/src/libexpr/flake/flake.cc +++ b/src/libexpr/flake/flake.cc @@ -254,7 +254,7 @@ LockedFlake lockFlake( const FlakeRef & topRef, const LockFlags & lockFlags) { - settings.requireExperimentalFeature("flakes"); + settings()->requireExperimentalFeature("flakes"); FlakeCache flakeCache; @@ -481,7 +481,7 @@ LockedFlake lockFlake( if (lockFlags.writeLockFile) { if (auto sourcePath = topRef.input.getSourcePath()) { if (!newLockFile.isImmutable()) { - if (settings.warnDirty) + if (settings()->warnDirty) warn("will not write lock file of flake '%s' because it has a mutable input", topRef); } else { if (!lockFlags.updateLockFile) diff --git a/src/libexpr/parser.y b/src/libexpr/parser.y index 24b21f7da33..aecf484fec8 100644 --- a/src/libexpr/parser.y +++ b/src/libexpr/parser.y @@ -415,7 +415,7 @@ expr_simple new ExprString(data->symbols.create(path))); } | URI { - static bool noURLLiterals = settings.isExperimentalFeatureEnabled("no-url-literals"); + static bool noURLLiterals = settings()->isExperimentalFeatureEnabled("no-url-literals"); if (noURLLiterals) throw ParseError({ .hint = hintfmt("URL literals are disabled"), diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index 7e8526ea135..25f2719bf11 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -906,7 +906,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * * } if (i->name == state.sContentAddressed) { - settings.requireExperimentalFeature("ca-derivations"); + settings()->requireExperimentalFeature("ca-derivations"); contentAddressed = state.forceBool(*i->value, pos); } @@ -1204,7 +1204,7 @@ static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, V .errPos = pos }); auto path2 = state.store->toStorePath(path).first; - if (!settings.readOnlyMode) + if (!settings()->readOnlyMode) state.store->ensurePath(path2); context.insert(state.store->printStorePath(path2)); mkString(v, path, context); @@ -1643,7 +1643,7 @@ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Valu refs.insert(state.store->parseStorePath(path)); } - auto storePath = state.store->printStorePath(settings.readOnlyMode + auto storePath = state.store->printStorePath(settings()->readOnlyMode ? state.store->computeStorePathForText(name, contents, refs) : state.store->addTextToStore(name, contents, refs, state.repair)); @@ -1767,7 +1767,7 @@ static void addPath(EvalState & state, const Pos & pos, const string & name, con expectedStorePath = state.store->makeFixedOutputPath(method, *expectedHash, name); Path dstPath; if (!expectedHash || !state.store->isValidPath(*expectedStorePath)) { - dstPath = state.store->printStorePath(settings.readOnlyMode + dstPath = state.store->printStorePath(settings()->readOnlyMode ? state.store->computeStorePathForPath(name, path, method, htSHA256, filter).first : state.store->addToStore(name, path, method, htSHA256, filter, state.repair)); if (expectedHash && expectedStorePath != state.store->parseStorePath(dstPath)) @@ -3517,7 +3517,7 @@ void EvalState::createBaseEnv() } if (!evalSettings.pureEval) { - mkString(v, settings.thisSystem.get()); + mkString(v, settings()->thisSystem.get()); addConstant("__currentSystem", v); } @@ -3554,7 +3554,7 @@ void EvalState::createBaseEnv() if (RegisterPrimOp::primOps) for (auto & primOp : *RegisterPrimOp::primOps) - if (!primOp.requiredFeature || settings.isExperimentalFeatureEnabled(*primOp.requiredFeature)) + if (!primOp.requiredFeature || settings()->isExperimentalFeatureEnabled(*primOp.requiredFeature)) addPrimOp({ .fun = primOp.fun, .arity = std::max(primOp.args.size(), primOp.arity), diff --git a/src/libexpr/primops/context.cc b/src/libexpr/primops/context.cc index dbb93bae6a2..c1c3e0b847f 100644 --- a/src/libexpr/primops/context.cc +++ b/src/libexpr/primops/context.cc @@ -150,7 +150,7 @@ static void prim_appendContext(EvalState & state, const Pos & pos, Value * * arg .hint = hintfmt("Context key '%s' is not a store path", i.name), .errPos = *i.pos }); - if (!settings.readOnlyMode) + if (!settings()->readOnlyMode) state.store->ensurePath(state.store->parseStorePath(i.name)); state.forceAttrs(*i.value, *i.pos); auto iter = i.value->attrs->find(sPath); diff --git a/src/libexpr/primops/fetchTree.cc b/src/libexpr/primops/fetchTree.cc index 06e8304b8bc..a3b534746e4 100644 --- a/src/libexpr/primops/fetchTree.cc +++ b/src/libexpr/primops/fetchTree.cc @@ -148,7 +148,7 @@ static void fetchTree( static void prim_fetchTree(EvalState & state, const Pos & pos, Value * * args, Value & v) { - settings.requireExperimentalFeature("flakes"); + settings()->requireExperimentalFeature("flakes"); fetchTree(state, pos, args, v, std::nullopt); } diff --git a/src/libfetchers/cache.cc b/src/libfetchers/cache.cc index e1c7f3dee32..f65dcd922a8 100644 --- a/src/libfetchers/cache.cc +++ b/src/libfetchers/cache.cc @@ -105,7 +105,7 @@ struct CacheImpl : Cache inAttrsJson, infoJson, store->printStorePath(storePath)); return Result { - .expired = !immutable && (settings.tarballTtl.get() == 0 || timestamp + settings.tarballTtl < time(0)), + .expired = !immutable && (settings()->tarballTtl.get() == 0 || timestamp + settings()->tarballTtl < time(0)), .infoAttrs = jsonToAttrs(nlohmann::json::parse(infoJson)), .storePath = std::move(storePath) }; diff --git a/src/libfetchers/git.cc b/src/libfetchers/git.cc index 5ca0f852143..ea6184adc0e 100644 --- a/src/libfetchers/git.cc +++ b/src/libfetchers/git.cc @@ -235,10 +235,10 @@ struct GitInputScheme : InputScheme /* This is an unclean working tree. So copy all tracked files. */ - if (!settings.allowDirty) + if (!settings()->allowDirty) throw Error("Git tree '%s' is dirty", actualUrl); - if (settings.warnDirty) + if (settings()->warnDirty) warn("Git tree '%s' is dirty", actualUrl); auto gitOpts = Strings({ "-C", actualUrl, "ls-files", "-z" }); @@ -341,7 +341,7 @@ struct GitInputScheme : InputScheme git fetch to update the local ref to the remote ref. */ struct stat st; doFetch = stat(localRefFile.c_str(), &st) != 0 || - (uint64_t) st.st_mtime + settings.tarballTtl <= (uint64_t) now; + (uint64_t) st.st_mtime + settings()->tarballTtl <= (uint64_t) now; } if (doFetch) { diff --git a/src/libfetchers/github.cc b/src/libfetchers/github.cc index 1cc0c5e2e7c..6e7d17f788b 100644 --- a/src/libfetchers/github.cc +++ b/src/libfetchers/github.cc @@ -184,7 +184,7 @@ struct GitHubInputScheme : GitArchiveInputScheme void addAccessToken(std::string & url) const { - std::string accessToken = settings.githubAccessToken.get(); + std::string accessToken = settings()->githubAccessToken.get(); if (accessToken != "") url += "?access_token=" + accessToken; } @@ -257,7 +257,7 @@ struct GitLabInputScheme : GitArchiveInputScheme input.getRev()->to_string(Base16, false)); /* # FIXME: add privat token auth (`curl --header "PRIVATE-TOKEN: "`) - std::string accessToken = settings.githubAccessToken.get(); + std::string accessToken = settings()->githubAccessToken.get(); if (accessToken != "") url += "?access_token=" + accessToken;*/ diff --git a/src/libfetchers/mercurial.cc b/src/libfetchers/mercurial.cc index 3e76ffc4dd7..2880e854741 100644 --- a/src/libfetchers/mercurial.cc +++ b/src/libfetchers/mercurial.cc @@ -136,10 +136,10 @@ struct MercurialInputScheme : InputScheme /* This is an unclean working tree. So copy all tracked files. */ - if (!settings.allowDirty) + if (!settings()->allowDirty) throw Error("Mercurial tree '%s' is unclean", actualUrl); - if (settings.warnDirty) + if (settings()->warnDirty) warn("Mercurial tree '%s' is unclean", actualUrl); input.attrs.insert_or_assign("ref", chomp(runProgram("hg", true, { "branch", "-R", actualUrl }))); diff --git a/src/libfetchers/registry.cc b/src/libfetchers/registry.cc index 4367ee8103b..c576e99317a 100644 --- a/src/libfetchers/registry.cc +++ b/src/libfetchers/registry.cc @@ -101,7 +101,7 @@ void Registry::remove(const Input & input) static Path getSystemRegistryPath() { - return settings.nixConfDir + "/registry.json"; + return settings()->nixConfDir + "/registry.json"; } static std::shared_ptr getSystemRegistry() @@ -142,7 +142,7 @@ void overrideRegistry( static std::shared_ptr getGlobalRegistry(ref store) { static auto reg = [&]() { - auto path = settings.flakeRegistry.get(); + auto path = settings()->flakeRegistry.get(); if (!hasPrefix(path, "/")) { auto storePath = downloadFile(store, path, "flake-registry.json", false).storePath; diff --git a/src/libmain/common-args.cc b/src/libmain/common-args.cc index 95b1fdb01d7..d86c493c49d 100644 --- a/src/libmain/common-args.cc +++ b/src/libmain/common-args.cc @@ -55,7 +55,7 @@ MixCommonArgs::MixCommonArgs(const string & programName) .description = "maximum number of parallel builds", .labels = Strings{"jobs"}, .handler = {[=](std::string s) { - settings.set("max-jobs", s); + settings()->set("max-jobs", s); }} }); diff --git a/src/libmain/shared.cc b/src/libmain/shared.cc index 22ae51e475c..b847f0abec1 100644 --- a/src/libmain/shared.cc +++ b/src/libmain/shared.cc @@ -77,7 +77,7 @@ void printMissing(ref store, const StorePathSet & willBuild, if (!unknown.empty()) { printMsg(lvl, fmt("don't know how to build these paths%s:", - (settings.readOnlyMode ? " (may be caused by read-only store access)" : ""))); + (settings()->readOnlyMode ? " (may be caused by read-only store access)" : ""))); for (auto & i : unknown) printMsg(lvl, fmt(" %s", store->printStorePath(i))); } @@ -182,33 +182,33 @@ LegacyArgs::LegacyArgs(const std::string & programName, .longName = "no-build-output", .shortName = 'Q', .description = "do not show build output", - .handler = {[&]() {setLogFormat(LogFormat::raw); }}, + .handler = {[&]() {setLogFormat(LogFormat("raw")); }}, }); addFlag({ .longName = "keep-failed", .shortName ='K', .description = "keep temporary directories of failed builds", - .handler = {&(bool&) settings.keepFailed, true}, + .handler = {&(bool&) settings()->keepFailed, true}, }); addFlag({ .longName = "keep-going", .shortName ='k', .description = "keep going after a build fails", - .handler = {&(bool&) settings.keepGoing, true}, + .handler = {&(bool&) settings()->keepGoing, true}, }); addFlag({ .longName = "fallback", .description = "build from source if substitution fails", - .handler = {&(bool&) settings.tryFallback, true}, + .handler = {&(bool&) settings()->tryFallback, true}, }); auto intSettingAlias = [&](char shortName, const std::string & longName, const std::string & description, const std::string & dest) { mkFlag(shortName, longName, description, [=](unsigned int n) { - settings.set(dest, std::to_string(n)); + settings()->set(dest, std::to_string(n)); }); }; @@ -217,7 +217,7 @@ LegacyArgs::LegacyArgs(const std::string & programName, intSettingAlias(0, "timeout", "number of seconds before a build is killed", "timeout"); mkFlag(0, "readonly-mode", "do not write to the Nix store", - &settings.readOnlyMode); + &settings()->readOnlyMode); mkFlag(0, "no-gc-warning", "disable warning about not using '--add-root'", &gcWarning, false); @@ -226,7 +226,7 @@ LegacyArgs::LegacyArgs(const std::string & programName, .longName = "store", .description = "URI of the Nix store to use", .labels = {"store-uri"}, - .handler = {&(std::string&) settings.storeUri}, + .handler = {&(std::string&) settings()->storeUri}, }); } @@ -277,15 +277,15 @@ void printVersion(const string & programName) #if HAVE_SODIUM cfg.push_back("signed-caches"); #endif - std::cout << "System type: " << settings.thisSystem << "\n"; - std::cout << "Additional system types: " << concatStringsSep(", ", settings.extraPlatforms.get()) << "\n"; + std::cout << "System type: " << settings()->thisSystem << "\n"; + std::cout << "Additional system types: " << concatStringsSep(", ", settings()->extraPlatforms.get()) << "\n"; std::cout << "Features: " << concatStringsSep(", ", cfg) << "\n"; - std::cout << "System configuration file: " << settings.nixConfDir + "/nix.conf" << "\n"; + std::cout << "System configuration file: " << settings()->nixConfDir + "/nix.conf" << "\n"; std::cout << "User configuration files: " << - concatStringsSep(":", settings.nixUserConfFiles) + concatStringsSep(":", settings()->nixUserConfFiles) << "\n"; - std::cout << "Store directory: " << settings.nixStore << "\n"; - std::cout << "State directory: " << settings.nixStateDir << "\n"; + std::cout << "Store directory: " << settings()->nixStore << "\n"; + std::cout << "State directory: " << settings()->nixStateDir << "\n"; } throw Exit(); } @@ -294,7 +294,7 @@ void printVersion(const string & programName) void showManPage(const string & name) { restoreSignals(); - setenv("MANPATH", settings.nixManDir.c_str(), 1); + setenv("MANPATH", settings()->nixManDir.c_str(), 1); execlp("man", "man", name.c_str(), nullptr); throw SysError("command 'man %1%' failed", name.c_str()); } @@ -403,3 +403,5 @@ PrintFreed::~PrintFreed() Exit::~Exit() { } } + + diff --git a/src/libstore/build.cc b/src/libstore/build.cc index 6e55f83d5fc..f00a03e6ff0 100644 --- a/src/libstore/build.cc +++ b/src/libstore/build.cc @@ -393,7 +393,7 @@ void Goal::waiteeDone(GoalPtr waitee, ExitCode result) if (result == ecIncompleteClosure) ++nrIncompleteClosure; - if (waitees.empty() || (result == ecFailed && !settings.keepGoing)) { + if (waitees.empty() || (result == ecFailed && !settings()->keepGoing)) { /* If we failed and keepGoing is not set, we remove all remaining waitees. */ @@ -477,8 +477,8 @@ void handleDiffHook( const Path & tryA, const Path & tryB, const Path & drvPath, const Path & tmpDir) { - auto diffHook = settings.diffHook; - if (diffHook != "" && settings.runDiffHook) { + auto diffHook = settings()->diffHook; + if (diffHook != "" && settings()->runDiffHook) { try { RunOptions diffHookOptions(diffHook,{tryA, tryB, drvPath, tmpDir}); diffHookOptions.searchPath = true; @@ -538,18 +538,18 @@ class UserLock UserLock::UserLock() { - assert(settings.buildUsersGroup != ""); - createDirs(settings.nixStateDir + "/userpool"); + assert(settings()->buildUsersGroup != ""); + createDirs(settings()->nixStateDir + "/userpool"); } bool UserLock::findFreeUser() { if (enabled()) return true; /* Get the members of the build-users-group. */ - struct group * gr = getgrnam(settings.buildUsersGroup.get().c_str()); + struct group * gr = getgrnam(settings()->buildUsersGroup.get().c_str()); if (!gr) throw Error("the group '%1%' specified in 'build-users-group' does not exist", - settings.buildUsersGroup); + settings()->buildUsersGroup); gid = gr->gr_gid; /* Copy the result of getgrnam. */ @@ -561,7 +561,7 @@ bool UserLock::findFreeUser() { if (users.empty()) throw Error("the build users group '%1%' has no members", - settings.buildUsersGroup); + settings()->buildUsersGroup); /* Find a user account that isn't currently in use for another build. */ @@ -571,10 +571,10 @@ bool UserLock::findFreeUser() { struct passwd * pw = getpwnam(i.c_str()); if (!pw) throw Error("the user '%1%' in the group '%2%' does not exist", - i, settings.buildUsersGroup); + i, settings()->buildUsersGroup); - fnUserLock = (format("%1%/userpool/%2%") % settings.nixStateDir % pw->pw_uid).str(); + fnUserLock = (format("%1%/userpool/%2%") % settings()->nixStateDir % pw->pw_uid).str(); AutoCloseFD fd = open(fnUserLock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); if (!fd) @@ -588,7 +588,7 @@ bool UserLock::findFreeUser() { /* Sanity check... */ if (uid == getuid() || uid == geteuid()) throw Error("the Nix user should not be a member of '%1%'", - settings.buildUsersGroup); + settings()->buildUsersGroup); #if __linux__ /* Get the list of supplementary groups of this build user. This @@ -646,7 +646,7 @@ struct HookInstance HookInstance::HookInstance() { - debug("starting build hook '%s'", settings.buildHook); + debug("starting build hook '%s'", settings()->buildHook); /* Create a pipe to get the output of the child. */ fromHook.create(); @@ -678,13 +678,13 @@ HookInstance::HookInstance() throw SysError("dupping builder's stdout/stderr"); Strings args = { - std::string(baseNameOf(settings.buildHook.get())), + std::string(baseNameOf(settings()->buildHook.get())), std::to_string(verbosity), }; - execv(settings.buildHook.get().c_str(), stringsToCharPtrs(args).data()); + execv(settings()->buildHook.get().c_str(), stringsToCharPtrs(args).data()); - throw SysError("executing '%s'", settings.buildHook); + throw SysError("executing '%s'", settings()->buildHook); }); pid.setSeparatePG(true); @@ -1243,7 +1243,7 @@ void DerivationGoal::haveDerivation() trace("have derivation"); if (drv->type() == DerivationType::CAFloating) - settings.requireExperimentalFeature("ca-derivations"); + settings()->requireExperimentalFeature("ca-derivations"); retrySubstitution = false; @@ -1274,7 +1274,7 @@ void DerivationGoal::haveDerivation() /* We are first going to try to create the invalid output paths through substitutes. If that doesn't work, we'll build them. */ - if (settings.useSubstitutes && parsedDrv->substitutesAllowed()) + if (settings()->useSubstitutes && parsedDrv->substitutesAllowed()) for (auto & [_, status] : initialOutputs) { if (!status.wanted) continue; if (!status.known) { @@ -1299,7 +1299,7 @@ void DerivationGoal::outputsSubstitutionTried() { trace("all outputs substituted (maybe)"); - if (nrFailed > 0 && nrFailed > nrNoSubstituters + nrIncompleteClosure && !settings.tryFallback) { + if (nrFailed > 0 && nrFailed > nrNoSubstituters + nrIncompleteClosure && !settings()->tryFallback) { done(BuildResult::TransientFailure, fmt("some substitutes for the outputs of derivation '%s' failed (usually happens due to networking issues); try '--fallback' to build derivation from source ", worker.store.printStorePath(drvPath))); @@ -1358,7 +1358,7 @@ void DerivationGoal::gaveUpOnSubstitution() for (auto & i : drv->inputSrcs) { if (worker.store.isValidPath(i)) continue; - if (!settings.useSubstitutes) + if (!settings()->useSubstitutes) throw Error("dependency '%s' of '%s' does not exist, and substitution is disabled", worker.store.printStorePath(i), worker.store.printStorePath(drvPath)); addWaitee(worker.makeSubstitutionGoal(i)); @@ -1495,7 +1495,7 @@ void DerivationGoal::inputsRealised() /* Don't repeat fixed-output derivations since they're already verified by their output hash.*/ - nrRounds = derivationIsFixed(derivationType) ? 1 : settings.buildRepeat + 1; + nrRounds = derivationIsFixed(derivationType) ? 1 : settings()->buildRepeat + 1; /* Okay, try to build. Note that here we don't wait for a build slot to become available, since we don't need one if there is a @@ -1615,7 +1615,7 @@ void DerivationGoal::tryToBuild() derivation prefers to be done locally, do it even if maxBuildJobs is 0. */ unsigned int curBuilds = worker.getNrLocalBuilds(); - if (curBuilds >= settings.maxBuildJobs && !(buildLocally && curBuilds == 0)) { + if (curBuilds >= settings()->maxBuildJobs && !(buildLocally && curBuilds == 0)) { worker.waitForBuildSlot(shared_from_this()); outputLocks.unlock(); return; @@ -1629,7 +1629,7 @@ void DerivationGoal::tryLocalBuild() { /* If `build-users-group' is not empty, then we have to build as one of the members of that group. */ - if (settings.buildUsersGroup != "" && getuid() == 0) { + if (settings()->buildUsersGroup != "" && getuid() == 0) { #if defined(__linux__) || defined(__APPLE__) if (!buildUser) buildUser = std::make_unique(); @@ -1795,9 +1795,9 @@ void DerivationGoal::buildDone() being valid. */ registerOutputs(); - if (settings.postBuildHook != "") { + if (settings()->postBuildHook != "") { Activity act(*logger, lvlInfo, actPostBuildHook, - fmt("running post-build-hook '%s'", settings.postBuildHook), + fmt("running post-build-hook '%s'", settings()->postBuildHook), Logger::Fields{worker.store.printStorePath(drvPath)}); PushActivity pact(act.id); StorePathSet outputPaths; @@ -1809,7 +1809,7 @@ void DerivationGoal::buildDone() hookEnvironment.emplace("DRV_PATH", worker.store.printStorePath(drvPath)); hookEnvironment.emplace("OUT_PATHS", chomp(concatStringsSep(" ", worker.store.printStorePathSet(outputPaths)))); - RunOptions opts(settings.postBuildHook, {}); + RunOptions opts(settings()->postBuildHook, {}); opts.environment = hookEnvironment; struct LogSink : Sink { @@ -1918,7 +1918,7 @@ HookReply DerivationGoal::tryBuildHook() /* Send the request to the hook. */ worker.hook->sink << "try" - << (worker.getNrLocalBuilds() < settings.maxBuildJobs ? 1 : 0) + << (worker.getNrLocalBuilds() < settings()->maxBuildJobs ? 1 : 0) << drv->platform << worker.store.printStorePath(drvPath) << parsedDrv->getRequiredSystemFeatures(); @@ -2095,7 +2095,7 @@ void DerivationGoal::startBuilder() drv->platform, concatStringsSep(", ", parsedDrv->getRequiredSystemFeatures()), worker.store.printStorePath(drvPath), - settings.thisSystem, + settings()->thisSystem, concatStringsSep(", ", worker.store.systemFeatures)); if (drv->isBuiltin()) @@ -2108,7 +2108,7 @@ void DerivationGoal::startBuilder() /* Are we doing a chroot build? */ { auto noChroot = parsedDrv->getBoolAttr("__noChroot"); - if (settings.sandboxMode == smEnabled) { + if (settings()->sandboxMode == smEnabled) { if (noChroot) throw Error("derivation '%s' has '__noChroot' set, " "but that's not allowed when 'sandbox' is 'true'", worker.store.printStorePath(drvPath)); @@ -2119,9 +2119,9 @@ void DerivationGoal::startBuilder() #endif useChroot = true; } - else if (settings.sandboxMode == smDisabled) + else if (settings()->sandboxMode == smDisabled) useChroot = false; - else if (settings.sandboxMode == smRelaxed) + else if (settings()->sandboxMode == smRelaxed) useChroot = !(derivationIsImpure(derivationType)) && !noChroot; } @@ -2238,8 +2238,8 @@ void DerivationGoal::startBuilder() /* Allow a user-configurable set of directories from the host file system. */ - PathSet dirs = settings.sandboxPaths; - PathSet dirs2 = settings.extraSandboxPaths; + PathSet dirs = settings()->sandboxPaths; + PathSet dirs2 = settings()->extraSandboxPaths; dirs.insert(dirs2.begin(), dirs2.end()); dirsInChroot.clear(); @@ -2274,7 +2274,7 @@ void DerivationGoal::startBuilder() dirsInChroot.insert_or_assign(p, p); } - PathSet allowedPaths = settings.allowedImpureHostPrefixes; + PathSet allowedPaths = settings()->allowedImpureHostPrefixes; /* This works like the above, except on a per-derivation level */ auto impurePaths = parsedDrv->getStringsAttr("__impureHostDeps").value_or(Strings()); @@ -2335,7 +2335,7 @@ void DerivationGoal::startBuilder() "root:x:0:0:Nix build user:%3%:/noshell\n" "nixbld:x:%1%:%2%:Nix build user:%3%:/noshell\n" "nobody:x:65534:65534:Nobody:/:/noshell\n", - sandboxUid, sandboxGid, settings.sandboxBuildDir)); + sandboxUid, sandboxGid, settings()->sandboxBuildDir)); /* Declare the build user's group so that programs get a consistent view of the system (e.g., "id -gn"). */ @@ -2377,7 +2377,7 @@ void DerivationGoal::startBuilder() /* If we're repairing, checking or rebuilding part of a multiple-outputs derivation, it's possible that we're - rebuilding a path that is in settings.dirsInChroot + rebuilding a path that is in settings()->dirsInChroot (typically the dependencies of /bin/sh). Throw them out. */ for (auto & i : drv->outputsAndOptPaths(worker.store)) { @@ -2401,9 +2401,9 @@ void DerivationGoal::startBuilder() if (needsHashRewrite() && pathExists(homeDir)) throw Error("home directory '%1%' exists; please remove it to assure purity of builds without sandboxing", homeDir); - if (useChroot && settings.preBuildHook != "" && dynamic_cast(drv.get())) { + if (useChroot && settings()->preBuildHook != "" && dynamic_cast(drv.get())) { printMsg(lvlChatty, format("executing pre-build hook '%1%'") - % settings.preBuildHook); + % settings()->preBuildHook); auto args = useChroot ? Strings({worker.store.printStorePath(drvPath), chrootRootDir}) : Strings({ worker.store.printStorePath(drvPath) }); enum BuildHookState { @@ -2411,7 +2411,7 @@ void DerivationGoal::startBuilder() stExtraChrootDirs }; auto state = stBegin; - auto lines = runProgram(settings.preBuildHook, false, args); + auto lines = runProgram(settings()->preBuildHook, false, args); auto lastPos = std::string::size_type{0}; for (auto nlPos = lines.find('\n'); nlPos != string::npos; nlPos = lines.find('\n', lastPos)) { @@ -2583,7 +2583,7 @@ void DerivationGoal::startBuilder() /* Otherwise exit with EPERM so we can handle this in the parent. This is only done when sandbox-fallback is set to true (the default). */ - if (child == -1 && (errno == EPERM || errno == EINVAL) && settings.sandboxFallback) + if (child == -1 && (errno == EPERM || errno == EINVAL) && settings()->sandboxFallback) _exit(1); if (child == -1) throw SysError("cloning builder process"); @@ -2592,7 +2592,7 @@ void DerivationGoal::startBuilder() }, options); int res = helper.wait(); - if (res != 0 && settings.sandboxFallback) { + if (res != 0 && settings()->sandboxFallback) { useChroot = false; initTmpDir(); goto fallback; @@ -2660,7 +2660,7 @@ void DerivationGoal::initTmpDir() { /* In a sandbox, for determinism, always use the same temporary directory. */ #if __linux__ - tmpDirInSandbox = useChroot ? settings.sandboxBuildDir : tmpDir; + tmpDirInSandbox = useChroot ? settings()->sandboxBuildDir : tmpDir; #else tmpDirInSandbox = tmpDir; #endif @@ -2729,7 +2729,7 @@ void DerivationGoal::initEnv() env["NIX_STORE"] = worker.store.storeDir; /* The maximum number of cores to utilize for parallel building. */ - env["NIX_BUILD_CORES"] = (format("%d") % settings.buildCores).str(); + env["NIX_BUILD_CORES"] = (format("%d") % settings()->buildCores).str(); initTmpDir(); @@ -3049,7 +3049,7 @@ struct RestrictedStore : public LocalFSStore, public virtual RestrictedStoreConf void DerivationGoal::startDaemon() { - settings.requireExperimentalFeature("recursive-nix"); + settings()->requireExperimentalFeature("recursive-nix"); Store::Params params; params["path-info-cache-size"] = "0"; @@ -3201,7 +3201,7 @@ void DerivationGoal::chownToBuilder(const Path & path) void setupSeccomp() { #if __linux__ - if (!settings.filterSyscalls) return; + if (!settings()->filterSyscalls) return; #if HAVE_SECCOMP scmp_filter_ctx ctx; @@ -3247,7 +3247,7 @@ void setupSeccomp() seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOTSUP), SCMP_SYS(fsetxattr), 0) != 0) throw SysError("unable to add seccomp rule"); - if (seccomp_attr_set(ctx, SCMP_FLTATR_CTL_NNP, settings.allowNewPrivileges ? 0 : 1) != 0) + if (seccomp_attr_set(ctx, SCMP_FLTATR_CTL_NNP, settings()->allowNewPrivileges ? 0 : 1) != 0) throw SysError("unable to set 'no new privileges' seccomp attribute"); if (seccomp_load(ctx) != 0) @@ -3283,7 +3283,7 @@ void DerivationGoal::runChild() std::string netrcData; try { if (drv->isBuiltin() && drv->builder == "builtin:fetchurl") - netrcData = readFile(settings.netrcFile); + netrcData = readFile(settings()->netrcFile); } catch (SysError &) { } #if __linux__ @@ -3424,7 +3424,7 @@ void DerivationGoal::runChild() /* Mount a new tmpfs on /dev/shm to ensure that whatever the builder puts in /dev/shm is cleaned up automatically. */ if (pathExists("/dev/shm") && mount("none", (chrootRootDir + "/dev/shm").c_str(), "tmpfs", 0, - fmt("size=%s", settings.sandboxShmSize).c_str()) == -1) + fmt("size=%s", settings()->sandboxShmSize).c_str()) == -1) throw SysError("mounting /dev/shm"); /* Mount a new devpts on /dev/pts. Note that this @@ -3506,7 +3506,7 @@ void DerivationGoal::runChild() struct utsname utsbuf; uname(&utsbuf); if (drv->platform == "i686-linux" && - (settings.thisSystem == "x86_64-linux" || + (settings()->thisSystem == "x86_64-linux" || (!strcmp(utsbuf.sysname, "Linux") && !strcmp(utsbuf.machine, "x86_64")))) { if (personality(PER_LINUX32) == -1) throw SysError("cannot set i686-linux personality"); @@ -3514,7 +3514,7 @@ void DerivationGoal::runChild() /* Impersonate a Linux 2.6 machine to get some determinism in builds that depend on the kernel version. */ - if ((drv->platform == "i686-linux" || drv->platform == "x86_64-linux") && settings.impersonateLinux26) { + if ((drv->platform == "i686-linux" || drv->platform == "x86_64-linux") && settings()->impersonateLinux26) { int cur = personality(0xffffffff); if (cur != -1) personality(cur | 0x0020000 /* == UNAME26 */); } @@ -3605,7 +3605,7 @@ void DerivationGoal::runChild() } /* Violations will go to the syslog if you set this. Unfortunately the destination does not appear to be configurable */ - if (settings.darwinLogSandboxViolations) { + if (settings()->darwinLogSandboxViolations) { sandboxProfile += "(deny default)\n"; } else { sandboxProfile += "(deny default (with no-log))\n"; @@ -3683,7 +3683,7 @@ void DerivationGoal::runChild() args.push_back("-D"); args.push_back("_GLOBAL_TMP_DIR=" + globalTmpDir); args.push_back("-D"); - args.push_back("IMPORT_DIR=" + settings.nixDataDir + "/nix/sandbox/"); + args.push_back("IMPORT_DIR=" + settings()->nixDataDir + "/nix/sandbox/"); if (allowLocalNetworking) { args.push_back("-D"); args.push_back(string("_ALLOW_LOCAL_NETWORKING=1")); @@ -3791,7 +3791,7 @@ void DerivationGoal::registerOutputs() InodesSeen inodesSeen; Path checkSuffix = ".check"; - bool keepPreviousRound = settings.keepFailed || settings.runDiffHook; + bool keepPreviousRound = settings()->keepFailed || settings()->runDiffHook; std::exception_ptr delayedException; @@ -4142,7 +4142,7 @@ void DerivationGoal::registerOutputs() ValidPathInfo oldInfo(*worker.store.queryPathInfo(newInfo.path)); if (newInfo.narHash != oldInfo.narHash) { worker.checkMismatch = true; - if (settings.runDiffHook || settings.keepFailed) { + if (settings()->runDiffHook || settings()->keepFailed) { Path dst = worker.store.toRealPath(finalDestPath + checkSuffix); deletePath(dst); moveCheckToStore(actualPath, dst); @@ -4224,7 +4224,7 @@ void DerivationGoal::registerOutputs() prev, worker.store.printStorePath(i->second.path), worker.store.printStorePath(drvPath), tmpDir); - if (settings.enforceDeterminism) + if (settings()->enforceDeterminism) throw NotDeterministic(hint); logError({ @@ -4459,7 +4459,7 @@ Path DerivationGoal::openLogFile() { logSize = 0; - if (!settings.keepLog) return ""; + if (!settings()->keepLog) return ""; auto baseName = std::string(baseNameOf(worker.store.printStorePath(drvPath))); @@ -4468,14 +4468,14 @@ Path DerivationGoal::openLogFile() createDirs(dir); Path logFileName = fmt("%s/%s%s", dir, string(baseName, 2), - settings.compressLog ? ".bz2" : ""); + settings()->compressLog ? ".bz2" : ""); fdLogFile = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0666); if (!fdLogFile) throw SysError("creating log file '%1%'", logFileName); logFileSink = std::make_shared(fdLogFile.get()); - if (settings.compressLog) + if (settings()->compressLog) logSink = std::shared_ptr(makeCompressionSink("bzip2", *logFileSink)); else logSink = logFileSink; @@ -4499,7 +4499,7 @@ void DerivationGoal::deleteTmpDir(bool force) if (tmpDir != "") { /* Don't keep temporary directories for builtins because they might have privileged stuff (like a copy of netrc). */ - if (settings.keepFailed && !force && !drv->isBuiltin()) { + if (settings()->keepFailed && !force && !drv->isBuiltin()) { printError("note: keeping build directory '%s'", tmpDir); chmod(tmpDir.c_str(), 0755); } @@ -4516,12 +4516,12 @@ void DerivationGoal::handleChildOutput(int fd, const string & data) (!hook && fd == builderOut.readSide.get())) { logSize += data.size(); - if (settings.maxLogSize && logSize > settings.maxLogSize) { + if (settings()->maxLogSize && logSize > settings()->maxLogSize) { killChild(); done( BuildResult::LogLimitExceeded, Error("%s killed after writing more than %d bytes of log output", - getName(), settings.maxLogSize)); + getName(), settings()->maxLogSize)); return; } @@ -4564,7 +4564,7 @@ void DerivationGoal::flushLine() else { logTail.push_back(currentLogLine); - if (logTail.size() > settings.logLines) logTail.pop_front(); + if (logTail.size() > settings()->logLines) logTail.pop_front(); act->result(resBuildLogLine, currentLogLine); } @@ -4791,10 +4791,10 @@ void SubstitutionGoal::init() return; } - if (settings.readOnlyMode) + if (settings()->readOnlyMode) throw Error("cannot substitute path '%s' - no write access to the Nix store", worker.store.printStorePath(storePath)); - subs = settings.useSubstitutes ? getDefaultSubstituters() : std::list>(); + subs = settings()->useSubstitutes ? getDefaultSubstituters() : std::list>(); tryNext(); } @@ -4841,13 +4841,13 @@ void SubstitutionGoal::tryNext() tryNext(); return; } catch (SubstituterDisabled &) { - if (settings.tryFallback) { + if (settings()->tryFallback) { tryNext(); return; } throw; } catch (Error & e) { - if (settings.tryFallback) { + if (settings()->tryFallback) { logError(e.info()); tryNext(); return; @@ -4936,7 +4936,7 @@ void SubstitutionGoal::tryToRun() if maxBuildJobs == 0 (no local builds allowed), we still allow a substituter to run. This is because substitutions cannot be distributed to another machine via the build hook. */ - if (worker.getNrLocalBuilds() >= std::max(1U, (unsigned int) settings.maxBuildJobs)) { + if (worker.getNrLocalBuilds() >= std::max(1U, (unsigned int) settings()->maxBuildJobs)) { worker.waitForBuildSlot(shared_from_this()); return; } @@ -5124,7 +5124,7 @@ void Worker::removeGoal(GoalPtr goal) topGoals.erase(goal); /* If a top-level goal failed, then kill all other goals (unless keepGoing was set). */ - if (goal->exitCode == Goal::ecFailed && !settings.keepGoing) + if (goal->exitCode == Goal::ecFailed && !settings()->keepGoing) topGoals.clear(); } @@ -5195,7 +5195,7 @@ void Worker::childTerminated(Goal * goal, bool wakeSleepers) void Worker::waitForBuildSlot(GoalPtr goal) { debug("wait for build slot"); - if (getNrLocalBuilds() < settings.maxBuildJobs) + if (getNrLocalBuilds() < settings()->maxBuildJobs) wakeUp(goal); /* we can do it right away */ else addToWeakGoals(wantingToBuild, goal); @@ -5250,7 +5250,7 @@ void Worker::run(const Goals & _topGoals) if (!children.empty() || !waitingForAWhile.empty()) waitForInput(); else { - if (awake.empty() && 0 == settings.maxBuildJobs) + if (awake.empty() && 0 == settings()->maxBuildJobs) { if (getMachines().empty()) throw Error("unable to start any build; either increase '--max-jobs' " @@ -5269,9 +5269,9 @@ void Worker::run(const Goals & _topGoals) /* If --keep-going is not set, it's possible that the main goal exited while some of its subgoals were still active. But if --keep-going *is* set, then they must all be finished now. */ - assert(!settings.keepGoing || awake.empty()); - assert(!settings.keepGoing || wantingToBuild.empty()); - assert(!settings.keepGoing || children.empty()); + assert(!settings()->keepGoing || awake.empty()); + assert(!settings()->keepGoing || wantingToBuild.empty()); + assert(!settings()->keepGoing || children.empty()); } void Worker::waitForInput() @@ -5292,15 +5292,15 @@ void Worker::waitForInput() is a build timeout, then wait for input until the first deadline for any child. */ auto nearest = steady_time_point::max(); // nearest deadline - if (settings.minFree.get() != 0) + if (settings()->minFree.get() != 0) // Periodicallty wake up to see if we need to run the garbage collector. nearest = before + std::chrono::seconds(10); for (auto & i : children) { if (!i.respectTimeouts) continue; - if (0 != settings.maxSilentTime) - nearest = std::min(nearest, i.lastOutput + std::chrono::seconds(settings.maxSilentTime)); - if (0 != settings.buildTimeout) - nearest = std::min(nearest, i.timeStarted + std::chrono::seconds(settings.buildTimeout)); + if (0 != settings()->maxSilentTime) + nearest = std::min(nearest, i.lastOutput + std::chrono::seconds(settings()->maxSilentTime)); + if (0 != settings()->buildTimeout) + nearest = std::min(nearest, i.timeStarted + std::chrono::seconds(settings()->buildTimeout)); } if (nearest != steady_time_point::max()) { timeout = std::max(1L, (long) std::chrono::duration_cast(nearest - before).count()); @@ -5314,7 +5314,7 @@ void Worker::waitForInput() if (lastWokenUp == steady_time_point::min() || lastWokenUp > before) lastWokenUp = before; timeout = std::max(1L, (long) std::chrono::duration_cast( - lastWokenUp + std::chrono::seconds(settings.pollInterval) - before).count()); + lastWokenUp + std::chrono::seconds(settings()->pollInterval) - before).count()); } else lastWokenUp = steady_time_point::min(); if (useTimeout) @@ -5376,27 +5376,27 @@ void Worker::waitForInput() } if (goal->exitCode == Goal::ecBusy && - 0 != settings.maxSilentTime && + 0 != settings()->maxSilentTime && j->respectTimeouts && - after - j->lastOutput >= std::chrono::seconds(settings.maxSilentTime)) + after - j->lastOutput >= std::chrono::seconds(settings()->maxSilentTime)) { goal->timedOut(Error( "%1% timed out after %2% seconds of silence", - goal->getName(), settings.maxSilentTime)); + goal->getName(), settings()->maxSilentTime)); } else if (goal->exitCode == Goal::ecBusy && - 0 != settings.buildTimeout && + 0 != settings()->buildTimeout && j->respectTimeouts && - after - j->timeStarted >= std::chrono::seconds(settings.buildTimeout)) + after - j->timeStarted >= std::chrono::seconds(settings()->buildTimeout)) { goal->timedOut(Error( "%1% timed out after %2% seconds", - goal->getName(), settings.buildTimeout)); + goal->getName(), settings()->buildTimeout)); } } - if (!waitingForAWhile.empty() && lastWokenUp + std::chrono::seconds(settings.pollInterval) <= after) { + if (!waitingForAWhile.empty() && lastWokenUp + std::chrono::seconds(settings()->pollInterval) <= after) { lastWokenUp = after; for (auto & i : waitingForAWhile) { GoalPtr goal = i.lock(); @@ -5474,7 +5474,7 @@ static void primeCache(Store & store, const std::vector & uint64_t downloadSize, narSize; store.queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); - if (!willBuild.empty() && 0 == settings.maxBuildJobs && getMachines().empty()) + if (!willBuild.empty() && 0 == settings()->maxBuildJobs && getMachines().empty()) throw Error( "%d derivations need to be built, but neither local builds ('--max-jobs') " "nor remote builds ('--builders') are enabled", willBuild.size()); diff --git a/src/libstore/builtins/fetchurl.cc b/src/libstore/builtins/fetchurl.cc index 4fb5d8a06b9..68d8d682771 100644 --- a/src/libstore/builtins/fetchurl.cc +++ b/src/libstore/builtins/fetchurl.cc @@ -12,8 +12,8 @@ void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData) this to be stored in a file. It would be nice if we could just pass a pointer to the data. */ if (netrcData != "") { - settings.netrcFile = "netrc"; - writeFile(settings.netrcFile, netrcData, 0600); + settings()->netrcFile = "netrc"; + writeFile(settings()->netrcFile, netrcData, 0600); } auto getAttr = [&](const string & name) { @@ -60,7 +60,7 @@ void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData) /* Try the hashed mirrors first. */ if (getAttr("outputHashMode") == "flat") - for (auto hashedMirror : settings.hashedMirrors.get()) + for (auto hashedMirror : settings()->hashedMirrors.get()) try { if (!hasSuffix(hashedMirror, "/")) hashedMirror += '/'; std::optional ht = parseHashTypeOpt(getAttr("outputHashAlgo")); diff --git a/src/libstore/crypto.cc b/src/libstore/crypto.cc index 9ec8abd228e..6c5728f2d07 100644 --- a/src/libstore/crypto.cc +++ b/src/libstore/crypto.cc @@ -105,12 +105,12 @@ PublicKeys getDefaultPublicKeys() // FIXME: filter duplicates - for (auto s : settings.trustedPublicKeys.get()) { + for (auto s : settings()->trustedPublicKeys.get()) { PublicKey key(s); publicKeys.emplace(key.name, key); } - for (auto secretKeyFile : settings.secretKeyFiles.get()) { + for (auto secretKeyFile : settings()->secretKeyFiles.get()) { try { SecretKey secretKey(readFile(secretKeyFile)); publicKeys.emplace(secretKey.name, secretKey.toPublicKey()); diff --git a/src/libstore/daemon.cc b/src/libstore/daemon.cc index 8adabf5491b..9c0bf995c37 100644 --- a/src/libstore/daemon.cc +++ b/src/libstore/daemon.cc @@ -188,15 +188,15 @@ struct ClientSettings void apply(TrustedFlag trusted) { - settings.keepFailed = keepFailed; - settings.keepGoing = keepGoing; - settings.tryFallback = tryFallback; + settings()->keepFailed = keepFailed; + settings()->keepGoing = keepGoing; + settings()->tryFallback = tryFallback; nix::verbosity = verbosity; - settings.maxBuildJobs.assign(maxBuildJobs); - settings.maxSilentTime = maxSilentTime; - settings.verboseBuild = verboseBuild; - settings.buildCores = buildCores; - settings.useSubstitutes = useSubstitutes; + settings()->maxBuildJobs.assign(maxBuildJobs); + settings()->maxSilentTime = maxSilentTime; + settings()->verboseBuild = verboseBuild; + settings()->buildCores = buildCores; + settings()->useSubstitutes = useSubstitutes; for (auto & i : overrides) { auto & name(i.first); @@ -205,8 +205,8 @@ struct ClientSettings auto setSubstituters = [&](Setting & res) { if (name != res.name && res.aliases.count(name) == 0) return false; - StringSet trusted = settings.trustedSubstituters; - for (auto & s : settings.substituters.get()) + StringSet trusted = settings()->trustedSubstituters; + for (auto & s : settings()->substituters.get()) trusted.insert(s); Strings subs; auto ss = tokenizeString(value); @@ -223,13 +223,13 @@ struct ClientSettings if (name == "ssh-auth-sock") // obsolete ; else if (trusted - || name == settings.buildTimeout.name + || name == settings()->buildTimeout.name || name == "connect-timeout" || (name == "builders" && value == "")) - settings.set(name, value); - else if (setSubstituters(settings.substituters)) + settings()->set(name, value); + else if (setSubstituters(settings()->substituters)) ; - else if (setSubstituters(settings.extraSubstituters)) + else if (setSubstituters(settings()->extraSubstituters)) ; else debug("ignoring the client-specified setting '%s', because it is a restricted setting and you are not a trusted user", name); diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc index 9d8ce5e3683..c4206058214 100644 --- a/src/libstore/derivations.cc +++ b/src/libstore/derivations.cc @@ -79,7 +79,7 @@ StorePath writeDerivation(Store & store, held during a garbage collection). */ auto suffix = std::string(drv.name) + drvExtension; auto contents = drv.unparse(store, false); - return settings.readOnlyMode + return settings()->readOnlyMode ? store.computeStorePathForText(suffix, contents, references) : store.addTextToStore(suffix, contents, references, repair); } @@ -170,7 +170,7 @@ static DerivationOutput parseDerivationOutput(const Store & store, }, }; } else { - settings.requireExperimentalFeature("ca-derivations"); + settings()->requireExperimentalFeature("ca-derivations"); assert(pathS == ""); return DerivationOutput { .output = DerivationOutputCAFloating { diff --git a/src/libstore/filetransfer.cc b/src/libstore/filetransfer.cc index 4149f81550d..398ebd665b7 100644 --- a/src/libstore/filetransfer.cc +++ b/src/libstore/filetransfer.cc @@ -315,9 +315,9 @@ struct curlFileTransfer : public FileTransfer } if (request.verifyTLS) { - debug("verify TLS: Nix CA file = '%s'", settings.caFile); - if (settings.caFile != "") - curl_easy_setopt(req, CURLOPT_CAINFO, settings.caFile.c_str()); + debug("verify TLS: Nix CA file = '%s'", settings()->caFile); + if (settings()->caFile != "") + curl_easy_setopt(req, CURLOPT_CAINFO, settings()->caFile.c_str()); } else { curl_easy_setopt(req, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(req, CURLOPT_SSL_VERIFYHOST, 0); @@ -330,7 +330,7 @@ struct curlFileTransfer : public FileTransfer /* If no file exist in the specified path, curl continues to work anyway as if netrc support was disabled. */ - curl_easy_setopt(req, CURLOPT_NETRC_FILE, settings.netrcFile.get().c_str()); + curl_easy_setopt(req, CURLOPT_NETRC_FILE, settings()->netrcFile.get().c_str()); curl_easy_setopt(req, CURLOPT_NETRC, CURL_NETRC_OPTIONAL); if (writtenToSink) diff --git a/src/libstore/gc.cc b/src/libstore/gc.cc index 08b53c702f7..4211446f0eb 100644 --- a/src/libstore/gc.cc +++ b/src/libstore/gc.cc @@ -694,8 +694,8 @@ void LocalStore::removeUnusedLinks(const GCState & state) void LocalStore::collectGarbage(const GCOptions & options, GCResults & results) { GCState state(options, results); - state.gcKeepOutputs = settings.gcKeepOutputs; - state.gcKeepDerivations = settings.gcKeepDerivations; + state.gcKeepOutputs = settings()->gcKeepOutputs; + state.gcKeepDerivations = settings()->gcKeepDerivations; /* Using `--ignore-liveness' with `--delete' can have unintended consequences if `keep-outputs' or `keep-derivations' are true @@ -876,13 +876,13 @@ void LocalStore::autoGC(bool sync) auto now = std::chrono::steady_clock::now(); - if (now < state->lastGCCheck + std::chrono::seconds(settings.minFreeCheckInterval)) return; + if (now < state->lastGCCheck + std::chrono::seconds(settings()->minFreeCheckInterval)) return; auto avail = getAvail(); state->lastGCCheck = now; - if (avail >= settings.minFree || avail >= settings.maxFree) return; + if (avail >= settings()->minFree || avail >= settings()->maxFree) return; if (avail > state->availAfterGC * 0.97) return; @@ -904,7 +904,7 @@ void LocalStore::autoGC(bool sync) }); GCOptions options; - options.maxFreed = settings.maxFree - avail; + options.maxFreed = settings()->maxFree - avail; printInfo("running auto-GC to free %d bytes", options.maxFreed); diff --git a/src/libstore/globals.cc b/src/libstore/globals.cc index aa694577d25..ae00a35ca4d 100644 --- a/src/libstore/globals.cc +++ b/src/libstore/globals.cc @@ -23,9 +23,16 @@ namespace nix { must be deleted and recreated on startup.) */ #define DEFAULT_SOCKET_PATH "/daemon-socket/socket" -Settings settings; +static Settings* _settings; -static GlobalConfig::Register r1(&settings); +Settings* settings() +{ + if (!_settings) + _settings = new Settings(); + return _settings; +} + +static GlobalConfig::Register r1(settings()); Settings::Settings() : nixPrefix(NIX_PREFIX) @@ -75,13 +82,13 @@ Settings::Settings() void loadConfFile() { - globalConfig.applyConfigFile(settings.nixConfDir + "/nix.conf"); + globalConfig.applyConfigFile(settings()->nixConfDir + "/nix.conf"); /* We only want to send overrides to the daemon, i.e. stuff from ~/.nix/nix.conf or the command line. */ globalConfig.resetOverriden(); - auto files = settings.nixUserConfFiles; + auto files = settings()->nixUserConfFiles; for (auto file = files.rbegin(); file != files.rend(); file++) { globalConfig.applyConfigFile(*file); } @@ -187,7 +194,7 @@ template<> void BaseSetting::convertToArg(Args & args, const std::s static void logFormatCompleter(size_t index, std::string_view prefix) { - for (auto & builder : registeredLoggers) + for (auto & builder : getRegisteredLoggers()) if (hasPrefix(builder->name, prefix)) completions->insert(builder->name); } @@ -196,11 +203,13 @@ std::string listLogFormats() { std::string res; - for (auto format = logFormats.begin(); format != logFormats.end(); ++format) { + auto loggers = getRegisteredLoggers(); + + for (auto format = loggers.begin(); format != loggers.end(); ++format) { if (!res.empty()) res += ", "; - if (std::next(format) == logFormats.end()) res += "or "; + if (std::next(format) == loggers.end()) res += "or "; res += "'"; - res += *format; + res += (*format)->name; res += "'"; } @@ -209,24 +218,14 @@ std::string listLogFormats() template<> void BaseSetting::set(const std::string & str) { - if (str == "raw") value = LogFormat::raw; - else if (str == "raw-with-logs") value = LogFormat::rawWithLogs; - else if (str == "internal-json") value = LogFormat::internalJson; - else if (str == "bar") value = LogFormat::bar; - else if (str == "bar-with-logs") value = LogFormat::barWithLogs; - else throw UsageError("option '%s' has an invalid value '%s'", name, str); - + auto str_ = str; + value = LogFormat(str_); createDefaultLogger(); } template<> std::string BaseSetting::to_string() const { - if (value == LogFormat::raw) return "raw"; - else if (value == LogFormat::rawWithLogs) return "raw-with-logs"; - else if (value == LogFormat::internalJson) return "internal-json"; - else if (value == LogFormat::bar) return "bar"; - else if (value == LogFormat::barWithLogs) return "bar-with-logs"; - else abort(); + return value; } template<> void BaseSetting::convertToArg(Args & args, const std::string & category) @@ -237,7 +236,7 @@ template<> void BaseSetting::convertToArg(Args & args, const std::str .category = category, .labels = {"format"}, .handler = {[&](std::string format) { - settings.logFormat.set(format); + settings()->logFormat.set(format); }}, .completer = logFormatCompleter }); @@ -245,19 +244,19 @@ template<> void BaseSetting::convertToArg(Args & args, const std::str void setLogFormat(const LogFormat & logFormat) { - settings.logFormat = logFormat; + settings()->logFormat = logFormat; createDefaultLogger(); } Logger* makeDefaultLogger() { - for (auto & builder : registeredLoggers) { - if (builder->name == settings.logFormat.to_string()) { + for (auto & builder : getRegisteredLoggers()) { + if (builder->name == settings()->logFormat.to_string()) { return builder->builder(); } } - throw UsageError("Unknown logger '%s'", settings.logFormat.to_string()); + throw UsageError("Unknown logger '%s'", settings()->logFormat.to_string()); } void createDefaultLogger() @@ -275,7 +274,7 @@ void MaxBuildJobsSetting::set(const std::string & str) void initPlugins() { - for (const auto & pluginFile : settings.pluginFiles.get()) { + for (const auto & pluginFile : settings()->pluginFiles.get()) { Paths pluginFiles; try { auto ents = readDirectory(pluginFile); @@ -303,3 +302,5 @@ void initPlugins() } } + + diff --git a/src/libstore/globals.hh b/src/libstore/globals.hh index 50bc496b002..dd7785ae7a5 100644 --- a/src/libstore/globals.hh +++ b/src/libstore/globals.hh @@ -636,7 +636,7 @@ public: is `root`. > **Warning** - > + > > Adding a user to `trusted-users` is essentially equivalent to > giving that user root access to the system. For example, the user > can set `sandbox-paths` and thereby obtain read access to @@ -693,7 +693,7 @@ public: send a series of commands to modify various settings to stdout. The currently recognized commands are: - - `extra-sandbox-paths` + - `extra-sandbox-paths` Pass a list of files and directories to be included in the sandbox for this build. One entry per line, terminated by an empty line. Entries have the same format as `sandbox-paths`. @@ -726,13 +726,13 @@ public: The program executes with no arguments. The program's environment contains the following environment variables: - - `DRV_PATH` + - `DRV_PATH` The derivation for the built paths. Example: `/nix/store/5nihn1a7pa8b25l9zafqaqibznlvvp3f-bash-4.4-p23.drv` - - `OUT_PATHS` + - `OUT_PATHS` Output paths of the built derivation, separated by a space character. @@ -763,7 +763,7 @@ public: documentation](https://ec.haxx.se/usingcurl-netrc.html). > **Note** - > + > > This must be an absolute path, and `~` is not resolved. For > example, `~/.netrc` won't resolve to your home directory's > `.netrc`. @@ -887,8 +887,8 @@ public: // FIXME: default shows as "3", but should show as "bar", due to the default // being an enum variant - Setting logFormat{this, LogFormat::bar, "log-format", - fmt("Default build output logging format. Valid options are: %s.", listLogFormats())}; + Setting logFormat{this, LogFormat("bar"), "log-format", + fmt("Default build output logging format. Valid options are: %s.", "")}; Logger* makeDefaultLogger(); }; @@ -898,7 +898,7 @@ void setLogFormat(const LogFormat & logFormat); void createDefaultLogger(); // FIXME: don't use a global variable. -extern Settings settings; +Settings* settings(); /* This should be called after settings are initialized, but before anything else */ @@ -912,3 +912,7 @@ std::vector getUserConfigFiles(); extern const string nixVersion; } + + + + diff --git a/src/libstore/http-binary-cache-store.cc b/src/libstore/http-binary-cache-store.cc index f4ab15a1098..b97a4a661fa 100644 --- a/src/libstore/http-binary-cache-store.cc +++ b/src/libstore/http-binary-cache-store.cc @@ -77,7 +77,7 @@ class HttpBinaryCacheStore : public BinaryCacheStore, public HttpBinaryCacheStor void maybeDisable() { auto state(_state.lock()); - if (state->enabled && settings.tryFallback) { + if (state->enabled && settings()->tryFallback) { int t = 60; printError("disabling binary cache '%s' for %s seconds", getUri(), t); state->enabled = false; diff --git a/src/libstore/legacy-ssh-store.cc b/src/libstore/legacy-ssh-store.cc index e9478c1d50e..6b43de24ccb 100644 --- a/src/libstore/legacy-ssh-store.cc +++ b/src/libstore/legacy-ssh-store.cc @@ -223,15 +223,15 @@ struct LegacySSHStore : public Store, public virtual LegacySSHStoreConfig void putBuildSettings(Connection & conn) { conn.to - << settings.maxSilentTime - << settings.buildTimeout; + << settings()->maxSilentTime + << settings()->buildTimeout; if (GET_PROTOCOL_MINOR(conn.remoteVersion) >= 2) conn.to - << settings.maxLogSize; + << settings()->maxLogSize; if (GET_PROTOCOL_MINOR(conn.remoteVersion) >= 3) conn.to - << settings.buildRepeat - << settings.enforceDeterminism; + << settings()->buildRepeat + << settings()->enforceDeterminism; } public: diff --git a/src/libstore/local-store.cc b/src/libstore/local-store.cc index c618203f07e..0483fd9ca60 100644 --- a/src/libstore/local-store.cc +++ b/src/libstore/local-store.cc @@ -83,16 +83,16 @@ LocalStore::LocalStore(const Params & params) /* Optionally, create directories and set permissions for a multi-user install. */ - if (getuid() == 0 && settings.buildUsersGroup != "") { + if (getuid() == 0 && settings()->buildUsersGroup != "") { mode_t perm = 01775; - struct group * gr = getgrnam(settings.buildUsersGroup.get().c_str()); + struct group * gr = getgrnam(settings()->buildUsersGroup.get().c_str()); if (!gr) logError({ .name = "'build-users-group' not found", .hint = hintfmt( "warning: the group '%1%' specified in 'build-users-group' does not exist", - settings.buildUsersGroup) + settings()->buildUsersGroup) }); else { struct stat st; @@ -131,16 +131,16 @@ LocalStore::LocalStore(const Params & params) try { struct stat st; if (stat(reservedPath.c_str(), &st) == -1 || - st.st_size != settings.reservedSize) + st.st_size != settings()->reservedSize) { AutoCloseFD fd = open(reservedPath.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600); int res = -1; #if HAVE_POSIX_FALLOCATE - res = posix_fallocate(fd.get(), 0, settings.reservedSize); + res = posix_fallocate(fd.get(), 0, settings()->reservedSize); #endif if (res == -1) { - writeFull(fd.get(), string(settings.reservedSize, 'X')); - [[gnu::unused]] auto res2 = ftruncate(fd.get(), settings.reservedSize); + writeFull(fd.get(), string(settings()->reservedSize, 'X')); + [[gnu::unused]] auto res2 = ftruncate(fd.get(), settings()->reservedSize); } } } catch (SysError & e) { /* don't care about errors */ @@ -322,12 +322,12 @@ void LocalStore::openDB(State & state, bool create) should be safe enough. If the user asks for it, don't sync at all. This can cause database corruption if the system crashes. */ - string syncMode = settings.fsyncMetadata ? "normal" : "off"; + string syncMode = settings()->fsyncMetadata ? "normal" : "off"; db.exec("pragma synchronous = " + syncMode); /* Set the SQLite journal mode. WAL mode is fastest, so it's the default. */ - string mode = settings.useSQLiteWAL ? "wal" : "truncate"; + string mode = settings()->useSQLiteWAL ? "wal" : "truncate"; string prevMode; { SQLiteStmt stmt; @@ -851,7 +851,7 @@ std::optional LocalStore::queryPathFromHashPart(const std::string & h StorePathSet LocalStore::querySubstitutablePaths(const StorePathSet & paths) { - if (!settings.useSubstitutes) return StorePathSet(); + if (!settings()->useSubstitutes) return StorePathSet(); StorePathSet remaining; for (auto & i : paths) @@ -882,7 +882,7 @@ StorePathSet LocalStore::querySubstitutablePaths(const StorePathSet & paths) void LocalStore::querySubstitutablePathInfos(const StorePathCAMap & paths, SubstitutablePathInfos & infos) { - if (!settings.useSubstitutes) return; + if (!settings()->useSubstitutes) return; for (auto & sub : getDefaultSubstituters()) { for (auto & path : paths) { auto subPath(path.first); @@ -913,7 +913,7 @@ void LocalStore::querySubstitutablePathInfos(const StorePathCAMap & paths, Subst } catch (InvalidPath &) { } catch (SubstituterDisabled &) { } catch (Error & e) { - if (settings.tryFallback) + if (settings()->tryFallback) logError(e.info()); else throw; @@ -937,7 +937,7 @@ void LocalStore::registerValidPaths(const ValidPathInfos & infos) be fsync-ed. So some may want to fsync them before registering the validity, at the expense of some speed of the path registering operation. */ - if (settings.syncBeforeRegistering) sync(); + if (settings()->syncBeforeRegistering) sync(); return retrySQLite([&]() { auto state(_state.lock()); @@ -1034,7 +1034,7 @@ void LocalStore::addToStore(const ValidPathInfo & info, Source & source, // text hashing has long been allowed to have non-self-references because it is used for drv files. bool refersToSelf = info.references.count(info.path) > 0; if (info.ca.has_value() && !info.references.empty() && !(std::holds_alternative(*info.ca) && !refersToSelf)) - settings.requireExperimentalFeature("ca-references"); + settings()->requireExperimentalFeature("ca-references"); /* While restoring the path from the NAR, compute the hash of the NAR. */ @@ -1092,10 +1092,10 @@ StorePath LocalStore::addToStoreFromDump(Source & source0, const string & name, /* Fill out buffer, and decide whether we are working strictly in memory based on whether we break out because the buffer is full or the original source is empty */ - while (dump.size() < settings.narBufferSize) { + while (dump.size() < settings()->narBufferSize) { auto oldSize = dump.size(); constexpr size_t chunkSize = 65536; - auto want = std::min(chunkSize, settings.narBufferSize - oldSize); + auto want = std::min(chunkSize, settings()->narBufferSize - oldSize); dump.resize(oldSize + want); auto got = 0; try { @@ -1529,7 +1529,7 @@ void LocalStore::signPathInfo(ValidPathInfo & info) { // FIXME: keep secret keys in memory. - auto secretKeyFiles = settings.secretKeyFiles; + auto secretKeyFiles = settings()->secretKeyFiles; for (auto & secretKeyFile : secretKeyFiles.get()) { SecretKey secretKey(readFile(secretKeyFile)); diff --git a/src/libstore/local-store.hh b/src/libstore/local-store.hh index e7c9d1605be..801ab022a5f 100644 --- a/src/libstore/local-store.hh +++ b/src/libstore/local-store.hh @@ -35,7 +35,7 @@ struct LocalStoreConfig : virtual LocalFSStoreConfig using LocalFSStoreConfig::LocalFSStoreConfig; Setting requireSigs{(StoreConfig*) this, - settings.requireSigs, + settings()->requireSigs, "require-sigs", "whether store paths should have a trusted signature on import"}; const std::string name() override { return "Local Store"; } diff --git a/src/libstore/machines.cc b/src/libstore/machines.cc index 7db2556f4b0..e5459273039 100644 --- a/src/libstore/machines.cc +++ b/src/libstore/machines.cc @@ -101,7 +101,7 @@ void parseMachines(const std::string & s, Machines & machines) }; machines.emplace_back(tokens[0], - isSet(1) ? tokenizeString>(tokens[1], ",") : std::vector{settings.thisSystem}, + isSet(1) ? tokenizeString>(tokens[1], ",") : std::vector{settings()->thisSystem}, isSet(2) ? tokens[2] : "", isSet(3) ? std::stoull(tokens[3]) : 1LL, isSet(4) ? std::stoull(tokens[4]) : 1LL, @@ -115,7 +115,7 @@ Machines getMachines() { static auto machines = [&]() { Machines machines; - parseMachines(settings.builders, machines); + parseMachines(settings()->builders, machines); return machines; }(); return machines; diff --git a/src/libstore/misc.cc b/src/libstore/misc.cc index da398169621..3f1b094fc26 100644 --- a/src/libstore/misc.cc +++ b/src/libstore/misc.cc @@ -220,7 +220,7 @@ void Store::queryMissing(const std::vector & targets, auto drv = make_ref(derivationFromPath(path.path)); ParsedDerivation parsedDrv(StorePath(path.path), *drv); - if (knownOutputPaths && settings.useSubstitutes && parsedDrv.substitutesAllowed()) { + if (knownOutputPaths && settings()->useSubstitutes && parsedDrv.substitutesAllowed()) { auto drvState = make_ref>(DrvState(invalid.size())); for (auto & output : invalid) pool.enqueue(std::bind(checkOutput, printStorePath(path.path), drv, output, drvState)); diff --git a/src/libstore/nar-info-disk-cache.cc b/src/libstore/nar-info-disk-cache.cc index 8541cc51fc1..577e137dd61 100644 --- a/src/libstore/nar-info-disk-cache.cc +++ b/src/libstore/nar-info-disk-cache.cc @@ -109,8 +109,8 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache SQLiteStmt(state->db, "delete from NARs where ((present = 0 and timestamp < ?) or (present = 1 and timestamp < ?))") .use() - (now - settings.ttlNegativeNarInfoCache) - (now - settings.ttlPositiveNarInfoCache) + (now - settings()->ttlNegativeNarInfoCache) + (now - settings()->ttlPositiveNarInfoCache) .exec(); debug("deleted %d entries from the NAR info disk cache", sqlite3_changes(state->db)); @@ -179,8 +179,8 @@ class NarInfoDiskCacheImpl : public NarInfoDiskCache auto queryNAR(state->queryNAR.use() (cache.id) (hashPart) - (now - settings.ttlNegativeNarInfoCache) - (now - settings.ttlPositiveNarInfoCache)); + (now - settings()->ttlNegativeNarInfoCache) + (now - settings()->ttlPositiveNarInfoCache)); if (!queryNAR.next()) return {oUnknown, 0}; diff --git a/src/libstore/optimise-store.cc b/src/libstore/optimise-store.cc index e4b4b621370..3c75439451b 100644 --- a/src/libstore/optimise-store.cc +++ b/src/libstore/optimise-store.cc @@ -304,7 +304,7 @@ void LocalStore::optimisePath(const Path & path) OptimiseStats stats; InodeHash inodeHash; - if (settings.autoOptimiseStore) optimisePath_(nullptr, stats, path, inodeHash); + if (settings()->autoOptimiseStore) optimisePath_(nullptr, stats, path, inodeHash); } diff --git a/src/libstore/parsed-derivations.cc b/src/libstore/parsed-derivations.cc index e7b7202d481..4552a38af83 100644 --- a/src/libstore/parsed-derivations.cc +++ b/src/libstore/parsed-derivations.cc @@ -96,8 +96,8 @@ StringSet ParsedDerivation::getRequiredSystemFeatures() const bool ParsedDerivation::canBuildLocally(Store & localStore) const { - if (drv.platform != settings.thisSystem.get() - && !settings.extraPlatforms.get().count(drv.platform) + if (drv.platform != settings()->thisSystem.get() + && !settings()->extraPlatforms.get().count(drv.platform) && !drv.isBuiltin()) return false; diff --git a/src/libstore/profiles.cc b/src/libstore/profiles.cc index c20386e2bab..265d7b97cbe 100644 --- a/src/libstore/profiles.cc +++ b/src/libstore/profiles.cc @@ -256,8 +256,8 @@ Path getDefaultProfile() if (!pathExists(profileLink)) { replaceSymlink( getuid() == 0 - ? settings.nixStateDir + "/profiles/default" - : fmt("%s/profiles/per-user/%s/profile", settings.nixStateDir, getUserName()), + ? settings()->nixStateDir + "/profiles/default" + : fmt("%s/profiles/per-user/%s/profile", settings()->nixStateDir, getUserName()), profileLink); } return absPath(readLink(profileLink), dirOf(profileLink)); diff --git a/src/libstore/remote-store.cc b/src/libstore/remote-store.cc index e92b94975de..3f400ac1ab2 100644 --- a/src/libstore/remote-store.cc +++ b/src/libstore/remote-store.cc @@ -175,7 +175,7 @@ ref UDSRemoteStore::openConnection() throw SysError("cannot create Unix domain socket"); closeOnExec(conn->fd.get()); - string socketPath = path ? *path : settings.nixDaemonSocketFile; + string socketPath = path ? *path : settings()->nixDaemonSocketFile; struct sockaddr_un addr; addr.sun_family = AF_UNIX; @@ -212,7 +212,7 @@ void RemoteStore::initConnection(Connection & conn) conn.to << PROTOCOL_VERSION; if (GET_PROTOCOL_MINOR(conn.daemonVersion) >= 14) { - int cpu = sameMachine() && settings.lockCPU ? lockToCurrentCPU() : -1; + int cpu = sameMachine() && settings()->lockCPU ? lockToCurrentCPU() : -1; if (cpu != -1) conn.to << 1 << cpu; else @@ -236,29 +236,29 @@ void RemoteStore::initConnection(Connection & conn) void RemoteStore::setOptions(Connection & conn) { conn.to << wopSetOptions - << settings.keepFailed - << settings.keepGoing - << settings.tryFallback + << settings()->keepFailed + << settings()->keepGoing + << settings()->tryFallback << verbosity - << settings.maxBuildJobs - << settings.maxSilentTime + << settings()->maxBuildJobs + << settings()->maxSilentTime << true - << (settings.verboseBuild ? lvlError : lvlVomit) + << (settings()->verboseBuild ? lvlError : lvlVomit) << 0 // obsolete log type << 0 /* obsolete print build trace */ - << settings.buildCores - << settings.useSubstitutes; + << settings()->buildCores + << settings()->useSubstitutes; if (GET_PROTOCOL_MINOR(conn.daemonVersion) >= 12) { std::map overrides; globalConfig.getSettings(overrides, true); - overrides.erase(settings.keepFailed.name); - overrides.erase(settings.keepGoing.name); - overrides.erase(settings.tryFallback.name); - overrides.erase(settings.maxBuildJobs.name); - overrides.erase(settings.maxSilentTime.name); - overrides.erase(settings.buildCores.name); - overrides.erase(settings.useSubstitutes.name); + overrides.erase(settings()->keepFailed.name); + overrides.erase(settings()->keepGoing.name); + overrides.erase(settings()->tryFallback.name); + overrides.erase(settings()->maxBuildJobs.name); + overrides.erase(settings()->maxSilentTime.name); + overrides.erase(settings()->buildCores.name); + overrides.erase(settings()->useSubstitutes.name); overrides.erase(loggerSettings.showTrace.name); conn.to << overrides.size(); for (auto & i : overrides) diff --git a/src/libstore/s3-binary-cache-store.cc b/src/libstore/s3-binary-cache-store.cc index d43f267e00f..92c8e5e0c11 100644 --- a/src/libstore/s3-binary-cache-store.cc +++ b/src/libstore/s3-binary-cache-store.cc @@ -131,7 +131,7 @@ ref S3Helper::makeConfig(const string & region res->requestTimeoutMs = 600 * 1000; res->connectTimeoutMs = 5 * 1000; res->retryStrategy = std::make_shared(); - res->caFile = settings.caFile; + res->caFile = settings()->caFile; return res; } diff --git a/src/libstore/ssh-store.cc b/src/libstore/ssh-store.cc index 6d6eca98d78..2be3c8a7e4f 100644 --- a/src/libstore/ssh-store.cc +++ b/src/libstore/ssh-store.cc @@ -67,7 +67,7 @@ class SSHStore : public virtual RemoteStore, public virtual SSHStoreConfig forwarded. One option: A way to query the daemon for its settings, and then a series of params to SSHStore like forward-cores or forward-overridden-cores that only - override the requested settings. + override the requested settings()-> */ }; }; diff --git a/src/libstore/store-api.cc b/src/libstore/store-api.cc index 2d5077ed033..9d5e811886d 100644 --- a/src/libstore/store-api.cc +++ b/src/libstore/store-api.cc @@ -360,8 +360,8 @@ std::string Store::getUri() bool Store::PathInfoCacheValue::isKnownNow() { std::chrono::duration ttl = didExist() - ? std::chrono::seconds(settings.ttlPositiveNarInfoCache) - : std::chrono::seconds(settings.ttlNegativeNarInfoCache); + ? std::chrono::seconds(settings()->ttlPositiveNarInfoCache) + : std::chrono::seconds(settings()->ttlNegativeNarInfoCache); return std::chrono::steady_clock::now() < time_point + ttl; } @@ -843,7 +843,7 @@ std::map copyPaths(ref srcStore, ref dstStor copyStorePath(srcStore, dstStore, storePath, repair, checkSigs); } catch (Error &e) { nrFailed++; - if (!settings.keepGoing) + if (!settings()->keepGoing) throw e; logger->log(lvlError, fmt("could not copy %s: %s", dstStore->printStorePath(storePath), e.what())); showProgress(); @@ -1043,10 +1043,10 @@ static bool isNonUriPath(const std::string & spec) { std::shared_ptr openFromNonUri(const std::string & uri, const Store::Params & params) { if (uri == "" || uri == "auto") { - auto stateDir = get(params, "state").value_or(settings.nixStateDir); + auto stateDir = get(params, "state").value_or(settings()->nixStateDir); if (access(stateDir.c_str(), R_OK | W_OK) == 0) return std::make_shared(params); - else if (pathExists(settings.nixDaemonSocketFile)) + else if (pathExists(settings()->nixDaemonSocketFile)) return std::make_shared(params); else return std::make_shared(params); @@ -1113,10 +1113,10 @@ std::list> getDefaultSubstituters() } }; - for (auto uri : settings.substituters.get()) + for (auto uri : settings()->substituters.get()) addStore(uri); - for (auto uri : settings.extraSubstituters.get()) + for (auto uri : settings()->extraSubstituters.get()) addStore(uri); stores.sort([](ref & a, ref & b) { diff --git a/src/libstore/store-api.hh b/src/libstore/store-api.hh index 4d3f07dfc37..a1b913bb1b9 100644 --- a/src/libstore/store-api.hh +++ b/src/libstore/store-api.hh @@ -196,7 +196,7 @@ struct StoreConfig : public Config virtual const std::string name() = 0; - const PathSetting storeDir_{this, false, settings.nixStore, + const PathSetting storeDir_{this, false, settings()->nixStore, "store", "path to the Nix store"}; const Path storeDir = storeDir_; @@ -208,7 +208,7 @@ struct StoreConfig : public Config Setting wantMassQuery{this, false, "want-mass-query", "whether this substituter can be queried efficiently for path validity"}; - Setting systemFeatures{this, settings.systemFeatures, + Setting systemFeatures{this, settings()->systemFeatures, "system-features", "Optional features that the system this store builds on implements (like \"kvm\")."}; @@ -693,10 +693,10 @@ struct LocalFSStoreConfig : virtual StoreConfig const PathSetting rootDir{(StoreConfig*) this, true, "", "root", "directory prefixed to all other paths"}; const PathSetting stateDir{(StoreConfig*) this, false, - rootDir != "" ? rootDir + "/nix/var/nix" : settings.nixStateDir, + rootDir != "" ? rootDir + "/nix/var/nix" : settings()->nixStateDir, "state", "directory where Nix will store state"}; const PathSetting logDir{(StoreConfig*) this, false, - rootDir != "" ? rootDir + "/nix/var/log/nix" : settings.nixLogDir, + rootDir != "" ? rootDir + "/nix/var/log/nix" : settings()->nixLogDir, "log", "directory where Nix will store state"}; }; @@ -787,7 +787,7 @@ void removeTempRoots(); You can pass parameters to the store implementation by appending ‘?key=value&key=value&...’ to the URI. */ -ref openStore(const std::string & uri = settings.storeUri.get(), +ref openStore(const std::string & uri = settings()->storeUri.get(), const Store::Params & extraParams = Store::Params()); diff --git a/src/libutil/config.hh b/src/libutil/config.hh index 1f5f4e7b9df..9c7509e55a6 100644 --- a/src/libutil/config.hh +++ b/src/libutil/config.hh @@ -117,7 +117,7 @@ public: void reapplyUnknownSettings(); }; -/* A class to simplify providing configuration settings. The typical +/* A class to simplify providing configuration settings()-> The typical use is to inherit Config and add Setting members: class MyClass : private Config diff --git a/src/libutil/loggers.cc b/src/libutil/loggers.cc index ac9ce7d1d9b..cbc05459529 100644 --- a/src/libutil/loggers.cc +++ b/src/libutil/loggers.cc @@ -2,20 +2,27 @@ namespace nix { -std::set logFormats = { - "raw", - "raw-with-logs", - "internal-json", - "bar", - "bar-with-logs" -}; +static std::vector>* registeredLoggers; -std::vector> registeredLoggers; +void initRegisteredLoggers() +{ + if (!registeredLoggers) + registeredLoggers = new std::vector>(); +} void registerLogger(std::string name, std::function builder) { LoggerBuilder lBuilder { .name = name, .builder = builder }; - registeredLoggers.push_back(std::make_shared(lBuilder)); + initRegisteredLoggers(); + registeredLoggers->push_back(std::make_shared(lBuilder)); +} + +std::vector> getRegisteredLoggers() +{ + return *registeredLoggers; } + } + + diff --git a/src/libutil/loggers.hh b/src/libutil/loggers.hh index 7bc03be6a6c..199768ac70a 100644 --- a/src/libutil/loggers.hh +++ b/src/libutil/loggers.hh @@ -4,12 +4,11 @@ namespace nix { -enum class LogFormat { - raw, - rawWithLogs, - internalJson, - bar, - barWithLogs, +struct LogFormat : std::string { + using std::string::string; + + LogFormat(std::string s) : std::string(s) { } + LogFormat(char* s) : std::string(s) { } }; struct LoggerBuilder { @@ -17,10 +16,10 @@ struct LoggerBuilder { std::function builder; }; -extern std::set logFormats; - -extern std::vector> registeredLoggers; +std::vector> getRegisteredLoggers(); void registerLogger(std::string name, std::function builder); } + + diff --git a/src/nix-build/nix-build.cc b/src/nix-build/nix-build.cc index 3a8d67f2158..d0ec01523e7 100755 --- a/src/nix-build/nix-build.cc +++ b/src/nix-build/nix-build.cc @@ -330,7 +330,7 @@ static void _main(int argc, char * * argv) store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); - if (settings.printMissing) + if (settings()->printMissing) printMissing(ref(store), willBuild, willSubstitute, unknown, downloadSize, narSize); if (!dryRun) @@ -407,7 +407,7 @@ static void _main(int argc, char * * argv) env["NIX_BUILD_TOP"] = env["TMPDIR"] = env["TEMPDIR"] = env["TMP"] = env["TEMP"] = *tmp; env["NIX_STORE"] = store->storeDir; - env["NIX_BUILD_CORES"] = std::to_string(settings.buildCores); + env["NIX_BUILD_CORES"] = std::to_string(settings()->buildCores); auto passAsFile = tokenizeString(get(drv.env, "passAsFile").value_or("")); diff --git a/src/nix-channel/nix-channel.cc b/src/nix-channel/nix-channel.cc index e48f7af9a77..08b38302392 100755 --- a/src/nix-channel/nix-channel.cc +++ b/src/nix-channel/nix-channel.cc @@ -64,7 +64,7 @@ static void removeChannel(const string & name) channels.erase(name); writeChannels(); - runProgram(settings.nixBinDir + "/nix-env", true, { "--profile", profile, "--uninstall", name }); + runProgram(settings()->nixBinDir + "/nix-env", true, { "--profile", profile, "--uninstall", name }); } static Path nixDefExpr; @@ -111,7 +111,7 @@ static void update(const StringSet & channelNames) bool unpacked = false; if (std::regex_search(filename, std::regex("\\.tar\\.(gz|bz2|xz)$"))) { - runProgram(settings.nixBinDir + "/nix-build", false, { "--no-out-link", "--expr", "import " + unpackChannelPath + + runProgram(settings()->nixBinDir + "/nix-build", false, { "--no-out-link", "--expr", "import " + unpackChannelPath + "{ name = \"" + cname + "\"; channelName = \"" + name + "\"; src = builtins.storePath \"" + filename + "\"; }" }); unpacked = true; } @@ -136,7 +136,7 @@ static void update(const StringSet & channelNames) for (auto & expr : exprs) envArgs.push_back(std::move(expr)); envArgs.push_back("--quiet"); - runProgram(settings.nixBinDir + "/nix-env", false, envArgs); + runProgram(settings()->nixBinDir + "/nix-env", false, envArgs); // Make the channels appear in nix-env. struct stat st; @@ -162,7 +162,7 @@ static int _main(int argc, char ** argv) nixDefExpr = home + "/.nix-defexpr"; // Figure out the name of the channels profile. - profile = fmt("%s/profiles/per-user/%s/channels", settings.nixStateDir, getUserName()); + profile = fmt("%s/profiles/per-user/%s/channels", settings()->nixStateDir, getUserName()); enum { cNone, @@ -242,7 +242,7 @@ static int _main(int argc, char ** argv) } else { envArgs.push_back("--rollback"); } - runProgram(settings.nixBinDir + "/nix-env", false, envArgs); + runProgram(settings()->nixBinDir + "/nix-env", false, envArgs); break; } diff --git a/src/nix-collect-garbage/nix-collect-garbage.cc b/src/nix-collect-garbage/nix-collect-garbage.cc index bcf1d8518d3..c3678a51837 100644 --- a/src/nix-collect-garbage/nix-collect-garbage.cc +++ b/src/nix-collect-garbage/nix-collect-garbage.cc @@ -76,7 +76,7 @@ static int _main(int argc, char * * argv) initPlugins(); - auto profilesDir = settings.nixStateDir + "/profiles"; + auto profilesDir = settings()->nixStateDir + "/profiles"; if (removeOld) removeOldGenerations(profilesDir); // Run the actual garbage collector. diff --git a/src/nix-daemon/nix-daemon.cc b/src/nix-daemon/nix-daemon.cc index 6e652ccbf0a..da76f798353 100644 --- a/src/nix-daemon/nix-daemon.cc +++ b/src/nix-daemon/nix-daemon.cc @@ -146,7 +146,7 @@ static ref openUncachedStore() Store::Params params; // FIXME: get params from somewhere // Disable caching since the client already does that. params["path-info-cache-size"] = "0"; - return openStore(settings.storeUri, params); + return openStore(settings()->storeUri, params); } @@ -171,8 +171,8 @@ static void daemonLoop(char * * argv) // Otherwise, create and bind to a Unix domain socket. else { - createDirs(dirOf(settings.nixDaemonSocketFile)); - fdSocket = createUnixDomainSocket(settings.nixDaemonSocketFile, 0666); + createDirs(dirOf(settings()->nixDaemonSocketFile)); + fdSocket = createUnixDomainSocket(settings()->nixDaemonSocketFile, 0666); } // Loop accepting connections. @@ -202,13 +202,13 @@ static void daemonLoop(char * * argv) struct group * gr = peer.gidKnown ? getgrgid(peer.gid) : 0; string group = gr ? gr->gr_name : std::to_string(peer.gid); - Strings trustedUsers = settings.trustedUsers; - Strings allowedUsers = settings.allowedUsers; + Strings trustedUsers = settings()->trustedUsers; + Strings allowedUsers = settings()->allowedUsers; if (matchUser(user, group, trustedUsers)) trusted = Trusted; - if ((!trusted && !matchUser(user, group, allowedUsers)) || group == settings.buildUsersGroup) + if ((!trusted && !matchUser(user, group, allowedUsers)) || group == settings()->buildUsersGroup) throw Error("user '%1%' is not allowed to connect to the Nix daemon", user); printInfo(format((string) "accepted connection from pid %1%, user %2%" + (trusted ? " (trusted)" : "")) diff --git a/src/nix-env/nix-env.cc b/src/nix-env/nix-env.cc index e5a433ac013..f1b3179c815 100644 --- a/src/nix-env/nix-env.cc +++ b/src/nix-env/nix-env.cc @@ -271,8 +271,8 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems, if (k != newest.end()) { d = j.first.querySystem() == k->second.first.querySystem() ? 0 : - j.first.querySystem() == settings.thisSystem ? 1 : - k->second.first.querySystem() == settings.thisSystem ? -1 : 0; + j.first.querySystem() == settings()->thisSystem ? 1 : + k->second.first.querySystem() == settings()->thisSystem ? -1 : 0; if (d == 0) d = comparePriorities(state, j.first, k->second.first); if (d == 0) @@ -494,7 +494,7 @@ static void installDerivations(Globals & globals, if (globals.dryRun) return; if (createUserEnv(*globals.state, allElems, - profile, settings.envKeepDerivations, lockToken)) break; + profile, settings()->envKeepDerivations, lockToken)) break; } } @@ -604,7 +604,7 @@ static void upgradeDerivations(Globals & globals, if (globals.dryRun) return; if (createUserEnv(*globals.state, newElems, - globals.profile, settings.envKeepDerivations, lockToken)) break; + globals.profile, settings()->envKeepDerivations, lockToken)) break; } } @@ -668,7 +668,7 @@ static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs) /* Write the new user environment. */ if (createUserEnv(*globals.state, installedElems, - globals.profile, settings.envKeepDerivations, lockToken)) break; + globals.profile, settings()->envKeepDerivations, lockToken)) break; } } @@ -754,7 +754,7 @@ static void uninstallDerivations(Globals & globals, Strings & selectors, if (globals.dryRun) return; if (createUserEnv(*globals.state, workingElems, - profile, settings.envKeepDerivations, lockToken)) break; + profile, settings()->envKeepDerivations, lockToken)) break; } } @@ -909,7 +909,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs) enum { sInstalled, sAvailable } source = sInstalled; - settings.readOnlyMode = true; /* makes evaluation a bit faster */ + settings()->readOnlyMode = true; /* makes evaluation a bit faster */ for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { string arg = *i++; @@ -1348,11 +1348,11 @@ static int _main(int argc, char * * argv) try { createDirs(globals.instSource.nixExprPath); replaceSymlink( - fmt("%s/profiles/per-user/%s/channels", settings.nixStateDir, getUserName()), + fmt("%s/profiles/per-user/%s/channels", settings()->nixStateDir, getUserName()), globals.instSource.nixExprPath + "/channels"); if (getuid() != 0) replaceSymlink( - fmt("%s/profiles/per-user/root/channels", settings.nixStateDir), + fmt("%s/profiles/per-user/root/channels", settings()->nixStateDir), globals.instSource.nixExprPath + "/channels_root"); } catch (Error &) { } } diff --git a/src/nix-instantiate/nix-instantiate.cc b/src/nix-instantiate/nix-instantiate.cc index 539092cbe33..a3453831b56 100644 --- a/src/nix-instantiate/nix-instantiate.cc +++ b/src/nix-instantiate/nix-instantiate.cc @@ -138,7 +138,7 @@ static int _main(int argc, char * * argv) else if (*arg == "--repair") repair = Repair; else if (*arg == "--dry-run") - settings.readOnlyMode = true; + settings()->readOnlyMode = true; else if (*arg != "" && arg->at(0) == '-') return false; else @@ -151,7 +151,7 @@ static int _main(int argc, char * * argv) initPlugins(); if (evalOnly && !wantsReadWrite) - settings.readOnlyMode = true; + settings()->readOnlyMode = true; auto store = openStore(); diff --git a/src/nix-store/nix-store.cc b/src/nix-store/nix-store.cc index b027e84b7b4..35c5a867655 100644 --- a/src/nix-store/nix-store.cc +++ b/src/nix-store/nix-store.cc @@ -143,7 +143,7 @@ static void opRealise(Strings opFlags, Strings opArgs) unknown = StorePathSet(); } - if (settings.printMissing) + if (settings()->printMissing) printMissing(ref(store), willBuild, willSubstitute, unknown, downloadSize, narSize); if (dryRun) return; @@ -423,7 +423,7 @@ static void opQuery(Strings opFlags, Strings opArgs) StorePathSet referrers; store->computeFSClosure( - args, referrers, true, settings.gcKeepOutputs, settings.gcKeepDerivations); + args, referrers, true, settings()->gcKeepOutputs, settings()->gcKeepDerivations); Roots roots = store->findRoots(false); for (auto & [target, links] : roots) @@ -795,18 +795,18 @@ static void opServe(Strings opFlags, Strings opArgs) // FIXME: changing options here doesn't work if we're // building through the daemon. verbosity = lvlError; - settings.keepLog = false; - settings.useSubstitutes = false; - settings.maxSilentTime = readInt(in); - settings.buildTimeout = readInt(in); + settings()->keepLog = false; + settings()->useSubstitutes = false; + settings()->maxSilentTime = readInt(in); + settings()->buildTimeout = readInt(in); if (GET_PROTOCOL_MINOR(clientVersion) >= 2) - settings.maxLogSize = readNum(in); + settings()->maxLogSize = readNum(in); if (GET_PROTOCOL_MINOR(clientVersion) >= 3) { - settings.buildRepeat = readInt(in); - settings.enforceDeterminism = readInt(in); - settings.runDiffHook = true; + settings()->buildRepeat = readInt(in); + settings()->enforceDeterminism = readInt(in); + settings()->runDiffHook = true; } - settings.printRepeatedBuilds = false; + settings()->printRepeatedBuilds = false; }; while (true) { diff --git a/src/nix/bundle.cc b/src/nix/bundle.cc index 241c8699bb9..f58572fc0c4 100644 --- a/src/nix/bundle.cc +++ b/src/nix/bundle.cc @@ -52,7 +52,7 @@ struct CmdBundle : InstallableCommand Strings getDefaultFlakeAttrPaths() override { - Strings res{"defaultApp." + settings.thisSystem.get()}; + Strings res{"defaultApp." + settings()->thisSystem.get()}; for (auto & s : SourceExprCommand::getDefaultFlakeAttrPaths()) res.push_back(s); return res; @@ -60,7 +60,7 @@ struct CmdBundle : InstallableCommand Strings getDefaultFlakeAttrPathPrefixes() override { - Strings res{"apps." + settings.thisSystem.get() + ".", "packages"}; + Strings res{"apps." + settings()->thisSystem.get() + ".", "packages"}; for (auto & s : SourceExprCommand::getDefaultFlakeAttrPathPrefixes()) res.push_back(s); return res; @@ -88,7 +88,7 @@ struct CmdBundle : InstallableCommand context.insert("=" + store->printStorePath(i.path)); mkString(*evalState->allocAttr(*arg, evalState->symbols.create("program")), app.program, context); - mkString(*evalState->allocAttr(*arg, evalState->symbols.create("system")), settings.thisSystem.get()); + mkString(*evalState->allocAttr(*arg, evalState->symbols.create("system")), settings()->thisSystem.get()); arg->attrs->sort(); diff --git a/src/nix/develop.cc b/src/nix/develop.cc index f29fa71d2d4..3d9eeda75ce 100644 --- a/src/nix/develop.cc +++ b/src/nix/develop.cc @@ -231,7 +231,7 @@ struct Common : InstallableCommand, MixProfile Strings getDefaultFlakeAttrPaths() override { - return {"devShell." + settings.thisSystem.get(), "defaultPackage." + settings.thisSystem.get()}; + return {"devShell." + settings()->thisSystem.get(), "defaultPackage." + settings()->thisSystem.get()}; } StorePath getShellOutPath(ref store) @@ -394,7 +394,7 @@ struct CmdDevelop : Common, MixEnvironment state, installable->nixpkgsFlakeRef(), Strings{"bashInteractive"}, - Strings{"legacyPackages." + settings.thisSystem.get() + "."}, + Strings{"legacyPackages." + settings()->thisSystem.get() + "."}, lockFlags); shell = state->store->printStorePath( diff --git a/src/nix/doctor.cc b/src/nix/doctor.cc index 683e9144602..6c8ed0b2a5c 100644 --- a/src/nix/doctor.cc +++ b/src/nix/doctor.cc @@ -99,7 +99,7 @@ struct CmdDoctor : StoreCommand if (!dirs.empty()) { std::stringstream ss; - ss << "Found profiles outside of " << settings.nixStateDir << "/profiles.\n" + ss << "Found profiles outside of " << settings()->nixStateDir << "/profiles.\n" << "The generation this profile points to might not have a gcroot and could be\n" << "garbage collected, resulting in broken symlinks.\n\n"; for (auto & dir : dirs) diff --git a/src/nix/flake.cc b/src/nix/flake.cc index ae6f4c5f9a2..9b2df4408b5 100644 --- a/src/nix/flake.cc +++ b/src/nix/flake.cc @@ -107,7 +107,7 @@ struct CmdFlakeUpdate : FlakeCommand void run(nix::ref store) override { /* Use --refresh by default for 'nix flake update'. */ - settings.tarballTtl = 0; + settings()->tarballTtl = 0; lockFlake(); } @@ -213,7 +213,7 @@ struct CmdFlakeCheck : FlakeCommand void run(nix::ref store) override { - settings.readOnlyMode = !build; + settings()->readOnlyMode = !build; auto state = getEvalState(); auto flake = lockFlake(); @@ -407,7 +407,7 @@ struct CmdFlakeCheck : FlakeCommand auto drvPath = checkDerivation( fmt("%s.%s.%s", name, attr.name, attr2.name), *attr2.value, *attr2.pos); - if ((std::string) attr.name == settings.thisSystem.get()) + if ((std::string) attr.name == settings()->thisSystem.get()) drvPaths.push_back({drvPath}); } } @@ -959,7 +959,7 @@ struct CmdFlake : NixMultiCommand { if (!command) throw UsageError("'nix flake' requires a sub-command."); - settings.requireExperimentalFeature("flakes"); + settings()->requireExperimentalFeature("flakes"); command->second->prepare(); command->second->run(); } diff --git a/src/nix/installables.cc b/src/nix/installables.cc index 9bf6b7caac5..aebe3948b98 100644 --- a/src/nix/installables.cc +++ b/src/nix/installables.cc @@ -138,7 +138,7 @@ SourceExprCommand::SourceExprCommand() Strings SourceExprCommand::getDefaultFlakeAttrPaths() { - return {"defaultPackage." + settings.thisSystem.get()}; + return {"defaultPackage." + settings()->thisSystem.get()}; } Strings SourceExprCommand::getDefaultFlakeAttrPathPrefixes() @@ -146,10 +146,10 @@ Strings SourceExprCommand::getDefaultFlakeAttrPathPrefixes() return { // As a convenience, look for the attribute in // 'outputs.packages'. - "packages." + settings.thisSystem.get() + ".", + "packages." + settings()->thisSystem.get() + ".", // As a temporary hack until Nixpkgs is properly converted // to provide a clean 'packages' set, look in 'legacyPackages'. - "legacyPackages." + settings.thisSystem.get() + "." + "legacyPackages." + settings()->thisSystem.get() + "." }; } @@ -630,7 +630,7 @@ Buildables build(ref store, Realise mode, std::vector> installables, BuildMode bMode) { if (mode == Realise::Nothing) - settings.readOnlyMode = true; + settings()->readOnlyMode = true; Buildables buildables; @@ -683,7 +683,7 @@ StorePathSet toStorePaths(ref store, }, b); } else { if (mode == Realise::Nothing) - settings.readOnlyMode = true; + settings()->readOnlyMode = true; for (auto & i : installables) for (auto & b : i->toBuildables()) diff --git a/src/nix/log.cc b/src/nix/log.cc index 33380dcf55d..2da72138430 100644 --- a/src/nix/log.cc +++ b/src/nix/log.cc @@ -35,7 +35,7 @@ struct CmdLog : InstallableCommand void run(ref store) override { - settings.readOnlyMode = true; + settings()->readOnlyMode = true; auto subs = getDefaultSubstituters(); diff --git a/src/nix/main.cc b/src/nix/main.cc index 2c3d83df556..bf8bbbdf205 100644 --- a/src/nix/main.cc +++ b/src/nix/main.cc @@ -92,7 +92,7 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs .longName = "print-build-logs", .shortName = 'L', .description = "print full build logs on stderr", - .handler = {[&]() {setLogFormat(LogFormat::barWithLogs); }}, + .handler = {[&]() {setLogFormat(LogFormat("bar-with-logs")); }}, }); addFlag({ @@ -170,7 +170,7 @@ void mainWrapped(int argc, char * * argv) } verbosity = lvlWarn; - settings.verboseBuild = false; + settings()->verboseBuild = false; evalSettings.pureEval = true; createDefaultLogger(); @@ -227,7 +227,7 @@ void mainWrapped(int argc, char * * argv) if (args.command->first != "repl" && args.command->first != "doctor" && args.command->first != "upgrade-nix") - settings.requireExperimentalFeature("nix-command"); + settings()->requireExperimentalFeature("nix-command"); if (args.useNet && !haveInternet()) { warn("you don't have Internet access; disabling some network-dependent features"); @@ -236,10 +236,10 @@ void mainWrapped(int argc, char * * argv) if (!args.useNet) { // FIXME: should check for command line overrides only. - if (!settings.useSubstitutes.overriden) - settings.useSubstitutes = false; - if (!settings.tarballTtl.overriden) - settings.tarballTtl = std::numeric_limits::max(); + if (!settings()->useSubstitutes.overriden) + settings()->useSubstitutes = false; + if (!settings()->tarballTtl.overriden) + settings()->tarballTtl = std::numeric_limits::max(); if (!fileTransferSettings.tries.overriden) fileTransferSettings.tries = 0; if (!fileTransferSettings.connectTimeout.overriden) @@ -247,7 +247,7 @@ void mainWrapped(int argc, char * * argv) } if (args.refresh) - settings.tarballTtl = 0; + settings()->tarballTtl = 0; args.command->second->prepare(); args.command->second->run(); @@ -261,3 +261,5 @@ int main(int argc, char * * argv) nix::mainWrapped(argc, argv); }); } + + diff --git a/src/nix/repl.cc b/src/nix/repl.cc index 3299994753d..f45a5e064f7 100644 --- a/src/nix/repl.cc +++ b/src/nix/repl.cc @@ -480,7 +480,7 @@ bool NixRepl::processLine(string line) state->callFunction(f, v, result, Pos()); StorePath drvPath = getDerivationPath(result); - runProgram(settings.nixBinDir + "/nix-shell", Strings{state->store->printStorePath(drvPath)}); + runProgram(settings()->nixBinDir + "/nix-shell", Strings{state->store->printStorePath(drvPath)}); } else if (command == ":b" || command == ":i" || command == ":s") { @@ -493,16 +493,16 @@ bool NixRepl::processLine(string line) /* We could do the build in this process using buildPaths(), but doing it in a child makes it easier to recover from problems / SIGINT. */ - if (runProgram(settings.nixBinDir + "/nix", Strings{"build", "--no-link", drvPathRaw}) == 0) { + if (runProgram(settings()->nixBinDir + "/nix", Strings{"build", "--no-link", drvPathRaw}) == 0) { auto drv = state->store->readDerivation(drvPath); std::cout << std::endl << "this derivation produced the following outputs:" << std::endl; for (auto & i : drv.outputsAndOptPaths(*state->store)) std::cout << fmt(" %s -> %s\n", i.first, state->store->printStorePath(*i.second.second)); } } else if (command == ":i") { - runProgram(settings.nixBinDir + "/nix-env", Strings{"-i", drvPathRaw}); + runProgram(settings()->nixBinDir + "/nix-env", Strings{"-i", drvPathRaw}); } else { - runProgram(settings.nixBinDir + "/nix-shell", Strings{drvPathRaw}); + runProgram(settings()->nixBinDir + "/nix-shell", Strings{drvPathRaw}); } } diff --git a/src/nix/run.cc b/src/nix/run.cc index cbaba9d909e..0ef491ec853 100644 --- a/src/nix/run.cc +++ b/src/nix/run.cc @@ -172,7 +172,7 @@ struct CmdRun : InstallableCommand, RunCommon Strings getDefaultFlakeAttrPaths() override { - Strings res{"defaultApp." + settings.thisSystem.get()}; + Strings res{"defaultApp." + settings()->thisSystem.get()}; for (auto & s : SourceExprCommand::getDefaultFlakeAttrPaths()) res.push_back(s); return res; @@ -180,7 +180,7 @@ struct CmdRun : InstallableCommand, RunCommon Strings getDefaultFlakeAttrPathPrefixes() override { - Strings res{"apps." + settings.thisSystem.get() + ".", "packages"}; + Strings res{"apps." + settings()->thisSystem.get() + ".", "packages"}; for (auto & s : SourceExprCommand::getDefaultFlakeAttrPathPrefixes()) res.push_back(s); return res; diff --git a/src/nix/search.cc b/src/nix/search.cc index 43097927453..57b13712d23 100644 --- a/src/nix/search.cc +++ b/src/nix/search.cc @@ -69,14 +69,14 @@ struct CmdSearch : InstallableCommand, MixJSON Strings getDefaultFlakeAttrPaths() override { return { - "packages." + settings.thisSystem.get() + ".", - "legacyPackages." + settings.thisSystem.get() + "." + "packages." + settings()->thisSystem.get() + ".", + "legacyPackages." + settings()->thisSystem.get() + "." }; } void run(ref store) override { - settings.readOnlyMode = true; + settings()->readOnlyMode = true; // Empty search string should match all packages // Use "^" here instead of ".*" due to differences in resulting highlighting diff --git a/src/nix/upgrade-nix.cc b/src/nix/upgrade-nix.cc index a880bdae097..cad93ac549d 100644 --- a/src/nix/upgrade-nix.cc +++ b/src/nix/upgrade-nix.cc @@ -93,7 +93,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand { Activity act(*logger, lvlInfo, actUnknown, fmt("installing '%s' into profile '%s'...", store->printStorePath(storePath), profileDir)); - runProgram(settings.nixBinDir + "/nix-env", false, + runProgram(settings()->nixBinDir + "/nix-env", false, {"--profile", profileDir, "-i", store->printStorePath(storePath), "--no-sandbox"}); } @@ -152,7 +152,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand auto v = state->allocValue(); state->eval(state->parseExprFromString(*res.data, "/no-such-path"), *v); Bindings & bindings(*state->allocBindings(0)); - auto v2 = findAlongAttrPath(*state, settings.thisSystem, bindings, *v).first; + auto v2 = findAlongAttrPath(*state, settings()->thisSystem, bindings, *v).first; return store->parseStorePath(state->forceString(*v2)); } diff --git a/src/resolve-system-dependencies/resolve-system-dependencies.cc b/src/resolve-system-dependencies/resolve-system-dependencies.cc index 434ad80a662..80272bfe691 100644 --- a/src/resolve-system-dependencies/resolve-system-dependencies.cc +++ b/src/resolve-system-dependencies/resolve-system-dependencies.cc @@ -173,7 +173,7 @@ int main(int argc, char ** argv) uname(&_uname); - auto cacheParentDir = (format("%1%/dependency-maps") % settings.nixStateDir).str(); + auto cacheParentDir = (format("%1%/dependency-maps") % settings()->nixStateDir).str(); cacheDir = (format("%1%/%2%-%3%-%4%") % cacheParentDir