convert some printError calls to logError

This commit is contained in:
Ben Burdette 2020-05-03 08:01:25 -06:00
parent 4b99c09f5c
commit ab6f0b9641
19 changed files with 195 additions and 70 deletions

View file

@ -200,9 +200,13 @@ static int _main(int argc, char * * argv)
} catch (std::exception & e) { } catch (std::exception & e) {
auto msg = chomp(drainFD(5, false)); auto msg = chomp(drainFD(5, false));
printError("cannot build on '%s': %s%s", logError(
ErrorInfo {
.name = "remote build",
.hint = hintfmt("cannot build on '%s': %s%s",
bestMachine->storeUri, e.what(), bestMachine->storeUri, e.what(),
(msg.empty() ? "" : ": " + msg)); (msg.empty() ? "" : ": " + msg))
});
bestMachine->enabled = false; bestMachine->enabled = false;
continue; continue;
} }

View file

@ -689,8 +689,12 @@ std::pair<bool, std::string> EvalState::resolveSearchPathElem(const SearchPathEl
request.unpack = true; request.unpack = true;
res = { true, getDownloader()->downloadCached(store, request).path }; res = { true, getDownloader()->downloadCached(store, request).path };
} catch (DownloadError & e) { } catch (DownloadError & e) {
// TODO: change to warn()? logWarning(
printError("warning: Nix search path entry '%1%' cannot be downloaded, ignoring", elem.second); ErrorInfo {
.name = "Download Error",
.hint = hintfmt("warning: Nix search path entry '%1%' cannot be downloaded, ignoring", elem.second)
});
res = { false, "" }; res = { false, "" };
} }
} else { } else {
@ -698,8 +702,11 @@ std::pair<bool, std::string> EvalState::resolveSearchPathElem(const SearchPathEl
if (pathExists(path)) if (pathExists(path))
res = { true, path }; res = { true, path };
else { else {
// TODO: change to warn()? logWarning(
printError("warning: Nix search path entry '%1%' does not exist, ignoring", elem.second); ErrorInfo {
.name = "Search path not found",
.hint = hintfmt("warning: Nix search path entry '%1%' does not exist, ignoring", elem.second)
});
res = { false, "" }; res = { false, "" };
} }
} }

View file

@ -300,21 +300,21 @@ int handleExceptions(const string & programName, std::function<void()> fun)
} catch (UsageError & e) { } catch (UsageError & e) {
// TODO: switch to logError // TODO: switch to logError
// logError(e.info()); // logError(e.info());
printError( _printError(
format("%1%\nTry '%2% --help' for more information.") format("%1%\nTry '%2% --help' for more information.")
% e.what() % programName); % e.what() % programName);
return 1; return 1;
} catch (BaseError & e) { } catch (BaseError & e) {
// logError(e.info()); // logError(e.info());
printError("%1%%2%", (settings.showTrace ? e.prefix() : ""), e.msg()); _printError("%1%%2%", (settings.showTrace ? e.prefix() : ""), e.msg());
if (e.prefix() != "" && !settings.showTrace) if (e.prefix() != "" && !settings.showTrace)
printError("(use '--show-trace' to show detailed location information)"); _printError("(use '--show-trace' to show detailed location information)");
return e.status; return e.status;
} catch (std::bad_alloc & e) { } catch (std::bad_alloc & e) {
printError(error + "out of memory"); _printError(error + "out of memory");
return 1; return 1;
} catch (std::exception & e) { } catch (std::exception & e) {
printError(error + e.what()); _printError(error + e.what());
return 1; return 1;
} }

View file

@ -493,7 +493,9 @@ void handleDiffHook(
if (diffRes.second != "") if (diffRes.second != "")
printError(chomp(diffRes.second)); printError(chomp(diffRes.second));
} catch (Error & error) { } catch (Error & error) {
printError("diff hook execution failed: %s", error.what()); // logError(error.info())
// TODO append message onto errorinfo...
_printError("diff hook execution failed: %s", error.what());
} }
} }
} }
@ -1144,7 +1146,11 @@ void DerivationGoal::loadDerivation()
trace("loading derivation"); trace("loading derivation");
if (nrFailed != 0) { if (nrFailed != 0) {
printError("cannot build missing derivation '%s'", worker.store.printStorePath(drvPath)); logError(
ErrorInfo {
.name = "missing derivation during build",
.hint = hintfmt("cannot build missing derivation '%s'", worker.store.printStorePath(drvPath))
});
done(BuildResult::MiscFailure); done(BuildResult::MiscFailure);
return; return;
} }
@ -1295,8 +1301,14 @@ void DerivationGoal::repairClosure()
/* Check each path (slow!). */ /* Check each path (slow!). */
for (auto & i : outputClosure) { for (auto & i : outputClosure) {
if (worker.pathContentsGood(i)) continue; if (worker.pathContentsGood(i)) continue;
printError("found corrupted or missing path '%s' in the output closure of '%s'", logError(
worker.store.printStorePath(i), worker.store.printStorePath(drvPath)); ErrorInfo {
.name = "Corrupt path in closure",
.hint = hintfmt(
"found corrupted or missing path '%s' in the output closure of '%s'",
worker.store.printStorePath(i), worker.store.printStorePath(drvPath))
});
auto drvPath2 = outputsToDrv.find(i); auto drvPath2 = outputsToDrv.find(i);
if (drvPath2 == outputsToDrv.end()) if (drvPath2 == outputsToDrv.end())
addWaitee(worker.makeSubstitutionGoal(i, Repair)); addWaitee(worker.makeSubstitutionGoal(i, Repair));
@ -1330,8 +1342,13 @@ void DerivationGoal::inputsRealised()
if (nrFailed != 0) { if (nrFailed != 0) {
if (!useDerivation) if (!useDerivation)
throw Error("some dependencies of '%s' are missing", worker.store.printStorePath(drvPath)); throw Error("some dependencies of '%s' are missing", worker.store.printStorePath(drvPath));
printError("cannot build derivation '%s': %s dependencies couldn't be built", logError(
worker.store.printStorePath(drvPath), nrFailed); ErrorInfo {
.name = "Dependencies could not be built",
.hint = hintfmt(
"cannot build derivation '%s': %s dependencies couldn't be built",
worker.store.printStorePath(drvPath), nrFailed)
});
done(BuildResult::DependencyFailed); done(BuildResult::DependencyFailed);
return; return;
} }
@ -1489,7 +1506,7 @@ void DerivationGoal::tryToBuild()
startBuilder(); startBuilder();
} catch (BuildError & e) { } catch (BuildError & e) {
printError(e.msg()); logError(e.info());
outputLocks.unlock(); outputLocks.unlock();
buildUser.reset(); buildUser.reset();
worker.permanentFailure = true; worker.permanentFailure = true;
@ -1709,7 +1726,7 @@ void DerivationGoal::buildDone()
outputLocks.unlock(); outputLocks.unlock();
} catch (BuildError & e) { } catch (BuildError & e) {
printError(e.msg()); logError(e.info());
outputLocks.unlock(); outputLocks.unlock();
@ -1788,8 +1805,13 @@ HookReply DerivationGoal::tryBuildHook()
} catch (SysError & e) { } catch (SysError & e) {
if (e.errNo == EPIPE) { if (e.errNo == EPIPE) {
printError("build hook died unexpectedly: %s", logError(
chomp(drainFD(worker.hook->fromHook.readSide.get()))); ErrorInfo {
.name = "Build hook died",
.hint = hintfmt(
"build hook died unexpectedly: %s",
chomp(drainFD(worker.hook->fromHook.readSide.get())))
});
worker.hook = 0; worker.hook = 0;
return rpDecline; return rpDecline;
} else } else
@ -3783,10 +3805,10 @@ void DerivationGoal::registerOutputs()
result.isNonDeterministic = true; result.isNonDeterministic = true;
Path prev = worker.store.printStorePath(i->second.path) + checkSuffix; Path prev = worker.store.printStorePath(i->second.path) + checkSuffix;
bool prevExists = keepPreviousRound && pathExists(prev); bool prevExists = keepPreviousRound && pathExists(prev);
auto msg = prevExists hintformat hint = prevExists
? fmt("output '%s' of '%s' differs from '%s' from previous round", ? hintfmt("output '%s' of '%s' differs from '%s' from previous round",
worker.store.printStorePath(i->second.path), worker.store.printStorePath(drvPath), prev) worker.store.printStorePath(i->second.path), worker.store.printStorePath(drvPath), prev)
: fmt("output '%s' of '%s' differs from previous round", : hintfmt("output '%s' of '%s' differs from previous round",
worker.store.printStorePath(i->second.path), worker.store.printStorePath(drvPath)); worker.store.printStorePath(i->second.path), worker.store.printStorePath(drvPath));
handleDiffHook( handleDiffHook(
@ -3796,9 +3818,15 @@ void DerivationGoal::registerOutputs()
worker.store.printStorePath(drvPath), tmpDir); worker.store.printStorePath(drvPath), tmpDir);
if (settings.enforceDeterminism) if (settings.enforceDeterminism)
throw NotDeterministic(msg); throw NotDeterministic(hint);
logError(
ErrorInfo {
.name = "Output determinism error",
.hint = hint
});
printError(msg);
curRound = nrRounds; // we know enough, bail out early curRound = nrRounds; // we know enough, bail out early
} }
} }
@ -4060,9 +4088,13 @@ void DerivationGoal::handleChildOutput(int fd, const string & data)
{ {
logSize += data.size(); logSize += data.size();
if (settings.maxLogSize && logSize > settings.maxLogSize) { if (settings.maxLogSize && logSize > settings.maxLogSize) {
printError( logError(
format("%1% killed after writing more than %2% bytes of log output") ErrorInfo {
% getName() % settings.maxLogSize); .name = "Max log size exceeded",
.hint = hintfmt(
"%1% killed after writing more than %2% bytes of log output",
getName(), settings.maxLogSize)
});
killChild(); killChild();
done(BuildResult::LogLimitExceeded); done(BuildResult::LogLimitExceeded);
return; return;
@ -4352,7 +4384,7 @@ void SubstitutionGoal::tryNext()
throw; throw;
} catch (Error & e) { } catch (Error & e) {
if (settings.tryFallback) { if (settings.tryFallback) {
printError(e.what()); logError(e.info());
tryNext(); tryNext();
return; return;
} }
@ -4864,9 +4896,13 @@ void Worker::waitForInput()
j->respectTimeouts && j->respectTimeouts &&
after - j->lastOutput >= std::chrono::seconds(settings.maxSilentTime)) after - j->lastOutput >= std::chrono::seconds(settings.maxSilentTime))
{ {
printError( logError(
format("%1% timed out after %2% seconds of silence") ErrorInfo {
% goal->getName() % settings.maxSilentTime); .name = "Silent build timeout",
.hint = hintfmt(
"%1% timed out after %2% seconds of silence",
goal->getName(), settings.maxSilentTime)
});
goal->timedOut(); goal->timedOut();
} }
@ -4875,9 +4911,13 @@ void Worker::waitForInput()
j->respectTimeouts && j->respectTimeouts &&
after - j->timeStarted >= std::chrono::seconds(settings.buildTimeout)) after - j->timeStarted >= std::chrono::seconds(settings.buildTimeout))
{ {
printError( logError(
format("%1% timed out after %2% seconds") ErrorInfo {
% goal->getName() % settings.buildTimeout); .name = "Build timeout",
.hint = hintfmt(
"%1% timed out after %2% seconds",
goal->getName(), settings.buildTimeout)
});
goal->timedOut(); goal->timedOut();
} }
} }
@ -4939,7 +4979,12 @@ bool Worker::pathContentsGood(const StorePath & path)
res = info->narHash == nullHash || info->narHash == current.first; res = info->narHash == nullHash || info->narHash == current.first;
} }
pathContentsGoodCache.insert_or_assign(path.clone(), res); pathContentsGoodCache.insert_or_assign(path.clone(), res);
if (!res) printError("path '%s' is corrupted or missing!", store.printStorePath(path)); if (!res)
logError(
ErrorInfo {
.name = "Corrupted path",
.hint = hintfmt("path '%s' is corrupted or missing!", store.printStorePath(path))
});
return res; return res;
} }

View file

@ -160,7 +160,8 @@ void PathLocks::unlock()
if (close(i.first) == -1) if (close(i.first) == -1)
printError( printError(
format("error (ignored): cannot close lock file on '%1%'") % i.second); "error (ignored): cannot close lock file on '%1%'",
i.second);
debug(format("lock released on '%1%'") % i.second); debug(format("lock released on '%1%'") % i.second);
} }

View file

@ -111,7 +111,9 @@ class RetryStrategy : public Aws::Client::DefaultRetryStrategy
auto retry = Aws::Client::DefaultRetryStrategy::ShouldRetry(error, attemptedRetries); auto retry = Aws::Client::DefaultRetryStrategy::ShouldRetry(error, attemptedRetries);
if (retry) if (retry)
printError("AWS error '%s' (%s), will retry in %d ms", printError("AWS error '%s' (%s), will retry in %d ms",
error.GetExceptionName(), error.GetMessage(), CalculateDelayBeforeNextRetry(error, attemptedRetries)); error.GetExceptionName(),
error.GetMessage(),
CalculateDelayBeforeNextRetry(error, attemptedRetries));
return retry; return retry;
} }
}; };

View file

@ -961,7 +961,7 @@ std::list<ref<Store>> getDefaultSubstituters()
try { try {
stores.push_back(openStore(uri)); stores.push_back(openStore(uri));
} catch (Error & e) { } catch (Error & e) {
printError("warning: %s", e.what()); logWarning(e.info());
} }
}; };

View file

@ -25,7 +25,7 @@ void setAffinityTo(int cpu)
CPU_ZERO(&newAffinity); CPU_ZERO(&newAffinity);
CPU_SET(cpu, &newAffinity); CPU_SET(cpu, &newAffinity);
if (sched_setaffinity(0, sizeof(cpu_set_t), &newAffinity) == -1) if (sched_setaffinity(0, sizeof(cpu_set_t), &newAffinity) == -1)
printError(format("failed to lock thread to CPU %1%") % cpu); printError("failed to lock thread to CPU %1%", cpu);
#endif #endif
} }
@ -47,7 +47,7 @@ void restoreAffinity()
#if __linux__ #if __linux__
if (!didSaveAffinity) return; if (!didSaveAffinity) return;
if (sched_setaffinity(0, sizeof(cpu_set_t), &savedAffinity) == -1) if (sched_setaffinity(0, sizeof(cpu_set_t), &savedAffinity) == -1)
printError("failed to restore affinity %1%"); _printError("failed to restore affinity");
#endif #endif
} }

View file

@ -117,6 +117,12 @@ public:
} }
{ } { }
BaseError(hintformat hint)
: err { .level = lvlError,
.hint = hint
}
{ }
BaseError(ErrorInfo e) BaseError(ErrorInfo e)
: err(e) : err(e)
{ } { }

View file

@ -149,6 +149,7 @@ extern Verbosity verbosity; /* suppress msgs > this */
} \ } \
} while (0) } while (0)
#define _printError(args...) printMsg(lvlError, args)
#define printError(args...) printMsg(lvlError, args) #define printError(args...) printMsg(lvlError, args)
#define printInfo(args...) printMsg(lvlInfo, args) #define printInfo(args...) printMsg(lvlInfo, args)
#define printTalkative(args...) printMsg(lvlTalkative, args) #define printTalkative(args...) printMsg(lvlTalkative, args)

View file

@ -1417,15 +1417,15 @@ string base64Decode(const string & s)
} }
void callFailure(const std::function<void(std::exception_ptr exc)> & failure, std::exception_ptr exc) // void callFailure(const std::function<void(std::exception_ptr exc)> & failure, std::exception_ptr exc)
{ // {
try { // try {
failure(exc); // failure(exc);
} catch (std::exception & e) { // } catch (std::exception & e) {
printError("uncaught exception: %s", e.what()); // printError("uncaught exception: %s", e.what());
abort(); // abort();
} // }
} // }
static Sync<std::pair<unsigned short, unsigned short>> windowSize{{0, 0}}; static Sync<std::pair<unsigned short, unsigned short>> windowSize{{0, 0}};

View file

@ -368,6 +368,8 @@ static void _main(int argc, char * * argv)
shell = drv->queryOutPath() + "/bin/bash"; shell = drv->queryOutPath() + "/bin/bash";
} catch (Error & e) { } catch (Error & e) {
// TODO: append error msg
logError(e.info());
printError("warning: %s; will use bash from your environment", e.what()); printError("warning: %s; will use bash from your environment", e.what());
shell = "bash"; shell = "bash";
} }

View file

@ -247,7 +247,8 @@ static void daemonLoop(char * * argv)
} catch (Interrupted & e) { } catch (Interrupted & e) {
return; return;
} catch (Error & e) { } catch (Error & e) {
printError("error processing connection: %1%", e.msg()); // TODO append error message
_printError("error processing connection: %1%", e.msg());
} }
} }
} }

View file

@ -123,7 +123,11 @@ static void getAllExprs(EvalState & state,
if (hasSuffix(attrName, ".nix")) if (hasSuffix(attrName, ".nix"))
attrName = string(attrName, 0, attrName.size() - 4); attrName = string(attrName, 0, attrName.size() - 4);
if (!attrs.insert(attrName).second) { if (!attrs.insert(attrName).second) {
printError(format("warning: name collision in input Nix expressions, skipping '%1%'") % path2); logError(
ErrorInfo {
.name = "Name collision",
.hint = hintfmt("warning: name collision in input Nix expressions, skipping '%1%'", path2)
});
continue; continue;
} }
/* Load the expression on demand. */ /* Load the expression on demand. */
@ -860,7 +864,12 @@ static void queryJSON(Globals & globals, vector<DrvInfo> & elems)
auto placeholder = metaObj.placeholder(j); auto placeholder = metaObj.placeholder(j);
Value * v = i.queryMeta(j); Value * v = i.queryMeta(j);
if (!v) { if (!v) {
printError("derivation '%s' has invalid meta attribute '%s'", i.queryName(), j); logError(
ErrorInfo {
.name = "Invalid meta attribute",
.hint = hintfmt("derivation '%s' has invalid meta attribute '%s'",
i.queryName(), j)
});
placeholder.write(nullptr); placeholder.write(nullptr);
} else { } else {
PathSet context; PathSet context;
@ -1110,8 +1119,14 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
XMLAttrs attrs2; XMLAttrs attrs2;
attrs2["name"] = j; attrs2["name"] = j;
Value * v = i.queryMeta(j); Value * v = i.queryMeta(j);
if (!v) if (!v)
printError("derivation '%s' has invalid meta attribute '%s'", i.queryName(), j); logError(
ErrorInfo {
.name = "Invalid meta attribute",
.hint = hintfmt(
"derivation '%s' has invalid meta attribute '%s'",
i.queryName(), j)
});
else { else {
if (v->type == tString) { if (v->type == tString) {
attrs2["type"] = "string"; attrs2["type"] = "string";

View file

@ -146,7 +146,7 @@ bool createUserEnv(EvalState & state, DrvInfos & elems,
Path lockTokenCur = optimisticLockProfile(profile); Path lockTokenCur = optimisticLockProfile(profile);
if (lockToken != lockTokenCur) { if (lockToken != lockTokenCur) {
printError(format("profile '%1%' changed while we were busy; restarting") % profile); printError("profile '%1%' changed while we were busy; restarting", profile);
return false; return false;
} }

View file

@ -726,9 +726,15 @@ static void opVerifyPath(Strings opFlags, Strings opArgs)
store->narFromPath(path, sink); store->narFromPath(path, sink);
auto current = sink.finish(); auto current = sink.finish();
if (current.first != info->narHash) { if (current.first != info->narHash) {
printError( logError(
"path '%s' was modified! expected hash '%s', got '%s'", ErrorInfo {
store->printStorePath(path), info->narHash.to_string(), current.first.to_string()); .name = "Hash match error",
.hint = hintfmt(
"path '%s' was modified! expected hash '%s', got '%s'",
store->printStorePath(path),
info->narHash.to_string(),
current.first.to_string())
});
status = 1; status = 1;
} }
} }
@ -835,7 +841,8 @@ static void opServe(Strings opFlags, Strings opArgs)
for (auto & p : willSubstitute) subs.emplace_back(p.clone()); for (auto & p : willSubstitute) subs.emplace_back(p.clone());
store->buildPaths(subs); store->buildPaths(subs);
} catch (Error & e) { } catch (Error & e) {
printError("warning: %1%", e.msg()); // logWarning(e.info()) TODO:
_printError("warning: %1%", e.msg());
} }
} }

View file

@ -64,7 +64,13 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand
if (dryRun) { if (dryRun) {
stopProgressBar(); stopProgressBar();
printError("would upgrade to version %s", version); // TODO change to info?
logWarning(
ErrorInfo {
.name = "Version update",
.hint = hintfmt("would upgrade to version %s", version)
});
// printError("would upgrade to version %s", version);
return; return;
} }

View file

@ -97,9 +97,15 @@ struct CmdVerify : StorePathsCommand
if (hash.first != info->narHash) { if (hash.first != info->narHash) {
corrupted++; corrupted++;
act2.result(resCorruptedPath, store->printStorePath(info->path)); act2.result(resCorruptedPath, store->printStorePath(info->path));
printError( logError(
"path '%s' was modified! expected hash '%s', got '%s'", ErrorInfo {
store->printStorePath(info->path), info->narHash.to_string(), hash.first.to_string()); .name = "Hash error - path modified",
.hint = hintfmt(
"path '%s' was modified! expected hash '%s', got '%s'",
store->printStorePath(info->path),
info->narHash.to_string(),
hash.first.to_string())
});
} }
} }
@ -148,7 +154,13 @@ struct CmdVerify : StorePathsCommand
if (!good) { if (!good) {
untrusted++; untrusted++;
act2.result(resUntrustedPath, store->printStorePath(info->path)); act2.result(resUntrustedPath, store->printStorePath(info->path));
printError("path '%s' is untrusted", store->printStorePath(info->path)); logError(
ErrorInfo {
.name = "Untrusted path",
.hint = hintfmt("path '%s' is untrusted",
store->printStorePath(info->path))
});
} }
} }

View file

@ -39,12 +39,20 @@ std::set<std::string> runResolver(const Path & filename)
throw SysError("statting '%s'", filename); throw SysError("statting '%s'", filename);
if (!S_ISREG(st.st_mode)) { if (!S_ISREG(st.st_mode)) {
printError("file '%s' is not a regular file", filename); logError(
ErrorInfo {
.name = "Regular MACH file",
.hint = hintfmt("file '%s' is not a regular file", filename)
});
return {}; return {};
} }
if (st.st_size < sizeof(mach_header_64)) { if (st.st_size < sizeof(mach_header_64)) {
printError("file '%s' is too short for a MACH binary", filename); logError(
ErrorInfo {
.name = "File too short",
.hint = hintfmt("file '%s' is too short for a MACH binary", filename)
});
return {}; return {};
} }
@ -66,13 +74,21 @@ std::set<std::string> runResolver(const Path & filename)
} }
} }
if (mach64_offset == 0) { if (mach64_offset == 0) {
printError(format("Could not find any mach64 blobs in file '%1%', continuing...") % filename); logError(
ErrorInfo {
.name = "No mach64 blobs",
.hint = hintfmt("Could not find any mach64 blobs in file '%1%', continuing...", filename)
});
return {}; return {};
} }
} else if (magic == MH_MAGIC_64 || magic == MH_CIGAM_64) { } else if (magic == MH_MAGIC_64 || magic == MH_CIGAM_64) {
mach64_offset = 0; mach64_offset = 0;
} else { } else {
printError(format("Object file has unknown magic number '%1%', skipping it...") % magic); logError(
ErrorInfo {
.name = "Magic number",
.hint = hintfmt("Object file has unknown magic number '%1%', skipping it...", magic)
});
return {}; return {};
} }