Compare commits

..

1 commit

Author SHA1 Message Date
Rebecca Turner 47677c645e
repl-overlays: Provide an elaborate example
This is the repl overlay from my dotfiles, which I think provides a
reasonable and ergonomic set of variables. We can iterate on this over
time, or (perhaps?) provide a sentinel value like `repl-overlays =
<DEFAULT>` to include a "suggested default" overlay like this one.
2024-09-01 15:28:59 -07:00
112 changed files with 1577 additions and 2824 deletions

View file

@ -29,7 +29,3 @@ trim_trailing_whitespace = false
indent_style = space indent_style = space
indent_size = 2 indent_size = 2
max_line_length = 0 max_line_length = 0
[meson.build]
indent_style = space
indent_size = 2

View file

@ -2,7 +2,7 @@
name: Missing or incorrect documentation name: Missing or incorrect documentation
about: Help us improve the reference manual about: Help us improve the reference manual
title: '' title: ''
labels: docs labels: documentation
assignees: '' assignees: ''
--- ---
@ -19,10 +19,10 @@ assignees: ''
<!-- make sure this issue is not redundant or obsolete --> <!-- make sure this issue is not redundant or obsolete -->
- [ ] checked [latest Lix manual] or its [source code] - [ ] checked [latest Lix manual] \([source]\)
- [ ] checked [documentation issues] and [recent documentation changes] for possible duplicates - [ ] checked [documentation issues] and [recent documentation changes] for possible duplicates
[latest Lix manual]: https://docs.lix.systems/manual/lix/nightly [latest Nix manual]: https://docs.lix.systems/manual/lix/nightly
[source code]: https://git.lix.systems/lix-project/lix/src/main/doc/manual/src [source]: https://git.lix.systems/lix-project/lix/src/main/doc/manual/src
[documentation issues]: https://git.lix.systems/lix-project/lix/issues?labels=151&state=all [documentation issues]: https://git.lix.systems/lix-project/lix/issues?labels=151&state=all
[recent documentation changes]: https://gerrit.lix.systems/q/p:lix+path:%22%5Edoc/manual/.*%22 [recent documentation changes]: https://gerrit.lix.systems/q/p:lix+path:%22%5Edoc/manual/.*%22

View file

@ -33,7 +33,32 @@ GENERATE_LATEX = NO
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
# Note: If this tag is empty the current directory is searched. # Note: If this tag is empty the current directory is searched.
INPUT = @INPUT_PATHS@ # FIXME Make this list more maintainable somehow. We could maybe generate this
# in the Makefile, but we would need to change how `.in` files are preprocessed
# so they can expand variables despite configure variables.
INPUT = \
src/libcmd \
src/libexpr \
src/libexpr/flake \
tests/unit/libexpr \
tests/unit/libexpr/value \
tests/unit/libexpr/test \
tests/unit/libexpr/test/value \
src/libexpr/value \
src/libfetchers \
src/libmain \
src/libstore \
src/libstore/build \
src/libstore/builtins \
tests/unit/libstore \
tests/unit/libstore/test \
src/libutil \
tests/unit/libutil \
tests/unit/libutil/test \
src/nix \
src/nix-env \
src/nix-store
# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names # If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
# in the source code. If set to NO, only conditional compilation will be # in the source code. If set to NO, only conditional compilation will be
@ -72,15 +97,3 @@ EXPAND_AS_DEFINED = \
DECLARE_WORKER_SERIALISER \ DECLARE_WORKER_SERIALISER \
DECLARE_SERVE_SERIALISER \ DECLARE_SERVE_SERIALISER \
LENGTH_PREFIXED_PROTO_HELPER LENGTH_PREFIXED_PROTO_HELPER
# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
# Stripping is only done if one of the specified strings matches the left-hand
# part of the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the path to
# strip.
#
# Note that you can specify absolute paths here, but also relative paths, which
# will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES.
STRIP_FROM_PATH = "@PROJECT_SOURCE_ROOT@"

View file

@ -1,35 +1,3 @@
internal_api_sources = [
'src/libcmd',
'src/libexpr',
'src/libexpr/flake',
'tests/unit/libexpr',
'tests/unit/libexpr/value',
'tests/unit/libexpr/test',
'tests/unit/libexpr/test/value',
'src/libexpr/value',
'src/libfetchers',
'src/libmain',
'src/libstore',
'src/libstore/build',
'src/libstore/builtins',
'tests/unit/libstore',
'tests/unit/libstore/test',
'src/libutil',
'tests/unit/libutil',
'tests/unit/libutil/test',
'src/nix',
'src/nix-env',
'src/nix-store',
]
# We feed Doxygen absolute paths so it can be invoked from any working directory.
internal_api_sources_absolute = []
foreach src : internal_api_sources
internal_api_sources_absolute += '"' + (meson.project_source_root() / src) + '"'
endforeach
internal_api_sources_oneline = ' \\\n '.join(internal_api_sources_absolute)
doxygen_cfg = configure_file( doxygen_cfg = configure_file(
input : 'doxygen.cfg.in', input : 'doxygen.cfg.in',
output : 'doxygen.cfg', output : 'doxygen.cfg',
@ -37,16 +5,22 @@ doxygen_cfg = configure_file(
'PACKAGE_VERSION': meson.project_version(), 'PACKAGE_VERSION': meson.project_version(),
'RAPIDCHECK_HEADERS': rapidcheck_meson.get_variable('includedir'), 'RAPIDCHECK_HEADERS': rapidcheck_meson.get_variable('includedir'),
'docdir' : meson.current_build_dir(), 'docdir' : meson.current_build_dir(),
'INPUT_PATHS' : internal_api_sources_oneline,
'PROJECT_SOURCE_ROOT' : meson.project_source_root(),
}, },
) )
internal_api_docs = custom_target( internal_api_docs = custom_target(
'internal-api-docs', 'internal-api-docs',
command : [ command : [
doxygen.full_path(), bash,
'@INPUT0@', # Meson can you please just give us a `workdir` argument to custom targets...
'-c',
# We have to prefix the doxygen_cfg path with the project build root
# because of the cd in front.
'cd @0@ && @1@ @2@/@INPUT0@'.format(
meson.project_source_root(),
doxygen.full_path(),
meson.project_build_root(),
),
], ],
input : [ input : [
doxygen_cfg, doxygen_cfg,

View file

@ -147,6 +147,3 @@ winter:
yshui: yshui:
github: yshui github: yshui
zimbatm:
github: zimbatm

View file

@ -126,19 +126,20 @@ manual = custom_target(
'manual', 'manual',
'markdown', 'markdown',
], ],
install : true,
install_dir : [
datadir / 'doc/nix',
false,
],
depfile : 'manual.d', depfile : 'manual.d',
env : { env : {
'RUST_LOG': 'info', 'RUST_LOG': 'info',
'MDBOOK_SUBSTITUTE_SEARCH': meson.current_build_dir() / 'src', 'MDBOOK_SUBSTITUTE_SEARCH': meson.current_build_dir() / 'src',
}, },
) )
manual_html = manual[0]
manual_md = manual[1] manual_md = manual[1]
install_subdir(
manual_html.full_path(),
install_dir : datadir / 'doc/nix',
)
nix_nested_manpages = [ nix_nested_manpages = [
[ 'nix-env', [ 'nix-env',
[ [

View file

@ -1,10 +0,0 @@
---
synopsis: "`Alt+Left` and `Alt+Right` go back/forwards by words in `nix repl`"
issues: [fj#501]
cls: [1883]
category: Fixes
credits: 9999years
---
`nix repl` now recognizes `Alt+Left` and `Alt+Right` for navigating by words
when entering input in `nix repl` on more terminals/platforms.

View file

@ -1,23 +0,0 @@
---
synopsis: restore backwards-compatibility of `builtins.fetchGit` with Nix 2.3
issues: [5291, 5128]
credits: [ma27]
category: Fixes
---
Compatibility with `builtins.fetchGit` from Nix 2.3 has been restored as follows:
* Until now, each `ref` was prefixed with `refs/heads` unless it starts with `refs/` itself.
Now, this is not done if the `ref` looks like a commit hash.
* Specifying `builtins.fetchGit { ref = "a-tag"; /* … */ }` was broken because `refs/heads` was appended.
Now, the fetcher doesn't turn a ref into `refs/heads/ref`, but into `refs/*/ref`. That way,
the value in `ref` can be either a tag or a branch.
* The ref resolution happens the same way as in git:
* If `refs/ref` exists, it's used.
* If a tag `refs/tags/ref` exists, it's used.
* If a branch `refs/heads/ref` exists, it's used.

View file

@ -1,38 +0,0 @@
---
synopsis: Removing the `.` default argument passed to the `nix fmt` formatter
issues: []
prs: [11438]
cls: [1902]
category: Breaking Changes
credits: zimbatm
---
The underlying formatter no longer receives the ". " default argument when `nix fmt` is called with no arguments.
This change was necessary as the formatter wasn't able to distinguish between
a user wanting to format the current folder with `nix fmt .` or the generic
`nix fmt`.
The default behaviour is now the responsibility of the formatter itself, and
allows tools such as treefmt to format the whole tree instead of only the
current directory and below.
This may cause issues with some formatters: nixfmt, nixpkgs-fmt and alejandra currently format stdin when no arguments are passed.
Here is a small wrapper example that will restore the previous behaviour for such a formatter:
```nix
{
outputs = { self, nixpkgs, systems }:
let
eachSystem = nixpkgs.lib.genAttrs (import systems) (system: nixpkgs.legacyPackages.${system});
in
{
formatter = eachSystem (pkgs:
pkgs.writeShellScriptBin "formatter" ''
if [[ $# = 0 ]]; set -- .; fi
exec "${pkgs.nixfmt-rfc-style}/bin/nixfmt "$@"
'');
};
}
```

View file

@ -1,17 +0,0 @@
---
synopsis: readline support removed
cls: [1885]
category: Packaging
credits: [9999years]
---
Support for building Lix with [`readline`][readline] instead of
[`editline`][editline] has been removed. `readline` support hasn't worked for a
long time (attempting to use it would lead to build errors) and would make Lix
subject to the GPL if it did work. In the future, we're hoping to replace
`editline` with [`rustyline`][rustyline] for improved ergonomics in the `nix
repl`.
[readline]: https://en.wikipedia.org/wiki/GNU_Readline
[editline]: https://github.com/troglobit/editline
[rustyline]: https://github.com/kkawakam/rustyline

View file

@ -1,26 +0,0 @@
---
synopsis: "Some Lix crashes now produce reporting instructions and a stack trace, then abort"
cls: [1854]
category: Improvements
credits: jade
---
Lix, being a C++ program, can crash in a few kinds of ways.
It can obviously do a memory access violation, which will generate a core dump and thus be relatively debuggable.
But, worse, it could throw an unhandled exception, and, in the past, we would just show the message but not where it comes from, in spite of this always being a bug, since we expect all such errors to be translated to a Lix specific error.
Now the latter kind of bug should print reporting instructions, a rudimentary stack trace and (depending on system configuration) generate a core dump.
Sample output:
```
Lix crashed. This is a bug. We would appreciate if you report it along with what caused it at https://git.lix.systems/lix-project/lix/issues with the following information included:
Exception: std::runtime_error: test exception
Stack trace:
0# nix::printStackTrace() in /home/jade/lix/lix3/build/src/nix/../libutil/liblixutil.so
1# 0x000073C9862331F2 in /home/jade/lix/lix3/build/src/nix/../libmain/liblixmain.so
2# 0x000073C985F2E21A in /nix/store/p44qan69linp3ii0xrviypsw2j4qdcp2-gcc-13.2.0-lib/lib/libstdc++.so.6
3# 0x000073C985F2E285 in /nix/store/p44qan69linp3ii0xrviypsw2j4qdcp2-gcc-13.2.0-lib/lib/libstdc++.so.6
4# nix::handleExceptions(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::function<void ()>) in /home/jade/lix/lix3/build/src/nix/../libmain/liblixmain.so
...
```

View file

@ -1,10 +0,0 @@
---
synopsis: "`<nix/fetchurl.nix>` now uses TLS verification"
category: Fixes
prs: [11585]
credits: edolstra
---
Previously `<nix/fetchurl.nix>` did not do TLS verification. This was because the Nix sandbox in the past did not have access to TLS certificates, and Nix checks the hash of the fetched file anyway. However, this can expose authentication data from `netrc` and URLs to man-in-the-middle attackers. In addition, Nix now in some cases (such as when using impure derivations) does *not* check the hash. Therefore we have now enabled TLS verification. This means that downloads by `<nix/fetchurl.nix>` will now fail if you're fetching from a HTTPS server that does not have a valid certificate.
`<nix/fetchurl.nix>` is also known as the builtin derivation builder `builtin:fetchurl`. It's not to be confused with the evaluation-time function `builtins.fetchurl`, which was not affected by this issue.

View file

@ -99,10 +99,9 @@
]; ];
stdenvs = [ stdenvs = [
# see assertion in package.nix why these two are disabled "gccStdenv"
# "stdenv"
# "gccStdenv"
"clangStdenv" "clangStdenv"
"stdenv"
"libcxxStdenv" "libcxxStdenv"
"ccacheStdenv" "ccacheStdenv"
]; ];
@ -122,11 +121,7 @@
name = "${stdenvName}Packages"; name = "${stdenvName}Packages";
value = f stdenvName; value = f stdenvName;
}) stdenvs }) stdenvs
) );
// {
# TODO delete this and reënable gcc stdenvs once gcc compiles kj coros correctly
stdenvPackages = f "clangStdenv";
};
# Memoize nixpkgs for different platforms for efficiency. # Memoize nixpkgs for different platforms for efficiency.
nixpkgsFor = forAllSystems ( nixpkgsFor = forAllSystems (
@ -217,7 +212,7 @@
# A Nixpkgs overlay that overrides the 'nix' and # A Nixpkgs overlay that overrides the 'nix' and
# 'nix.perl-bindings' packages. # 'nix.perl-bindings' packages.
overlays.default = overlayFor (p: p.clangStdenv); overlays.default = overlayFor (p: p.stdenv);
hydraJobs = { hydraJobs = {
# Binary package for various platforms. # Binary package for various platforms.

View file

@ -47,7 +47,6 @@
# in the build directory. # in the build directory.
project('lix', 'cpp', 'rust', project('lix', 'cpp', 'rust',
meson_version : '>=1.4.0',
version : run_command('bash', '-c', 'echo -n $(jq -r .version < ./version.json)$VERSION_SUFFIX', check : true).stdout().strip(), version : run_command('bash', '-c', 'echo -n $(jq -r .version < ./version.json)$VERSION_SUFFIX', check : true).stdout().strip(),
default_options : [ default_options : [
'cpp_std=c++2a', 'cpp_std=c++2a',
@ -168,18 +167,10 @@ endif
# frees one would expect when the objects are unique_ptrs. these problems # frees one would expect when the objects are unique_ptrs. these problems
# often show up as memory corruption when nesting generators (since we do # often show up as memory corruption when nesting generators (since we do
# treat generators like owned memory) and will cause inexplicable crashs. # treat generators like owned memory) and will cause inexplicable crashs.
#
# gcc 13 does not compile capnp coroutine code correctly. a newer version
# may fix this. (cf. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102051)
# we allow gcc 13 here anyway because CI uses it for clang-tidy, and when
# the compiler crashes outright if won't produce any bad binaries either.
assert( assert(
cxx.get_id() != 'gcc' or cxx.version().version_compare('>=13'), cxx.get_id() != 'gcc' or cxx.version().version_compare('>=13'),
'GCC is known to miscompile coroutines, use clang.' 'GCC 12 and earlier are known to miscompile lix coroutines, use GCC 13 or clang.'
) )
if cxx.get_id() == 'gcc'
warning('GCC is known to crash while building coroutines, use clang.')
endif
# Translate some historical and Mesony CPU names to Lixy CPU names. # Translate some historical and Mesony CPU names to Lixy CPU names.
@ -238,7 +229,6 @@ configdata += {
} }
boost = dependency('boost', required : true, modules : ['container'], include_type : 'system') boost = dependency('boost', required : true, modules : ['container'], include_type : 'system')
kj = dependency('kj-async', required : true, include_type : 'system')
# cpuid only makes sense on x86_64 # cpuid only makes sense on x86_64
cpuid_required = is_x64 ? get_option('cpuid') : false cpuid_required = is_x64 ? get_option('cpuid') : false
@ -493,6 +483,12 @@ add_project_arguments(
'-Wdeprecated-copy', '-Wdeprecated-copy',
'-Wignored-qualifiers', '-Wignored-qualifiers',
'-Werror=suggest-override', '-Werror=suggest-override',
# Enable assertions in libstdc++ by default. Harmless on libc++. Benchmarked
# at ~1% overhead in `nix search`.
#
# FIXME: remove when we get meson 1.4.0 which will default this to on for us:
# https://mesonbuild.com/Release-notes-for-1-4-0.html#ndebug-setting-now-controls-c-stdlib-assertions
'-D_GLIBCXX_ASSERTIONS=1',
language : 'cpp', language : 'cpp',
) )
@ -588,10 +584,10 @@ run_command(
) )
if is_darwin if is_darwin
fs.copyfile( configure_file(
'misc/launchd/org.nixos.nix-daemon.plist.in', input : 'misc/launchd/org.nixos.nix-daemon.plist.in',
'org.nixos.nix-daemon.plist', output : 'org.nixos.nix-daemon.plist',
install : true, copy : true,
install_dir : prefix / 'Library/LaunchDaemons', install_dir : prefix / 'Library/LaunchDaemons',
) )
endif endif

View file

@ -1,7 +1,8 @@
fs.copyfile( configure_file(
'completion.sh', input : 'completion.sh',
'nix', output : 'nix',
install : true, install : true,
install_dir : datadir / 'bash-completion/completions', install_dir : datadir / 'bash-completion/completions',
install_mode : 'rw-r--r--', install_mode : 'rw-r--r--',
copy : true,
) )

View file

@ -14,7 +14,7 @@ function _nix_complete
# But the variable also misses the current token so it cancels out. # But the variable also misses the current token so it cancels out.
set -l nix_arg_to_complete (count $nix_args) set -l nix_arg_to_complete (count $nix_args)
env NIX_GET_COMPLETIONS=$nix_arg_to_complete $nix_args $current_token 2>/dev/null env NIX_GET_COMPLETIONS=$nix_arg_to_complete $nix_args $current_token
end end
function _nix_accepts_files function _nix_accepts_files

View file

@ -1,7 +1,8 @@
fs.copyfile( configure_file(
'completion.fish', input : 'completion.fish',
'nix.fish', output : 'nix.fish',
install : true, install : true,
install_dir : datadir / 'fish/vendor_completions.d', install_dir : datadir / 'fish/vendor_completions.d',
install_mode : 'rw-r--r--', install_mode : 'rw-r--r--',
copy : true,
) )

View file

@ -5,4 +5,8 @@ subdir('zsh')
subdir('systemd') subdir('systemd')
subdir('flake-registry') subdir('flake-registry')
runinpty = fs.copyfile('runinpty.py') runinpty = configure_file(
copy : true,
input : meson.current_source_dir() / 'runinpty.py',
output : 'runinpty.py',
)

View file

@ -1,9 +1,10 @@
foreach script : [ [ 'completion.zsh', '_nix' ], [ 'run-help-nix' ] ] foreach script : [ [ 'completion.zsh', '_nix' ], [ 'run-help-nix' ] ]
fs.copyfile( configure_file(
script[0], input : script[0],
script.get(1, script[0]), output : script.get(1, script[0]),
install : true, install : true,
install_dir : datadir / 'zsh/site-functions', install_dir : datadir / 'zsh/site-functions',
install_mode : 'rw-r--r--', install_mode : 'rw-r--r--',
copy : true,
) )
endforeach endforeach

View file

@ -1,106 +0,0 @@
From d0f2a5bc2300b96b2434c7838184c1dfd6a639f5 Mon Sep 17 00:00:00 2001
From: Rebecca Turner <rbt@sent.as>
Date: Sun, 8 Sep 2024 15:42:42 -0700
Subject: [PATCH 1/2] Recognize Meta+Left and Meta+Right
Recognize `Alt-Left` and `Alt-Right` for navigating by words in more
terminals/shells/platforms.
I'm not sure exactly where to find canonical documentation for these
codes, but this seems to match what my terminal produces (macOS + iTerm2
+ Fish + Tmux).
It might also be nice to have some more support for editing the bindings
for these characters; sequences of more than one character are not
supported by `el_bind_key` and similar.
Originally from: https://github.com/troglobit/editline/pull/70
This patch is applied upstream: https://gerrit.lix.systems/c/lix/+/1883
---
src/editline.c | 29 +++++++++++++++++++++++++++--
1 file changed, 27 insertions(+), 2 deletions(-)
diff --git a/src/editline.c b/src/editline.c
index 5ec9afb..d1cfbbc 100644
--- a/src/editline.c
+++ b/src/editline.c
@@ -1034,6 +1034,30 @@ static el_status_t meta(void)
return CSeof;
#ifdef CONFIG_ANSI_ARROWS
+ /* See: https://en.wikipedia.org/wiki/ANSI_escape_code */
+ /* Recognize ANSI escapes for `Meta+Left` and `Meta+Right`. */
+ if (c == '\e') {
+ switch (tty_get()) {
+ case '[':
+ {
+ switch (tty_get()) {
+ /* \e\e[C = Meta+Left */
+ case 'C': return fd_word();
+ /* \e\e[D = Meta+Right */
+ case 'D': return bk_word();
+ default:
+ break;
+ }
+
+ return el_ring_bell();
+ }
+ default:
+ break;
+ }
+
+ return el_ring_bell();
+ }
+
/* Also include VT-100 arrows. */
if (c == '[' || c == 'O') {
switch (tty_get()) {
@@ -1043,6 +1067,7 @@ static el_status_t meta(void)
char seq[4] = { 0 };
seq[0] = tty_get();
+ /* \e[1~ */
if (seq[0] == '~')
return beg_line(); /* Home */
@@ -1050,9 +1075,9 @@ static el_status_t meta(void)
seq[c] = tty_get();
if (!strncmp(seq, ";5C", 3))
- return fd_word(); /* Ctrl+Right */
+ return fd_word(); /* \e[1;5C = Ctrl+Right */
if (!strncmp(seq, ";5D", 3))
- return bk_word(); /* Ctrl+Left */
+ return bk_word(); /* \e[1;5D = Ctrl+Left */
break;
}
From 4c4455353a0a88bee09d5f27c28f81f747682fed Mon Sep 17 00:00:00 2001
From: Rebecca Turner <rbt@sent.as>
Date: Mon, 9 Sep 2024 09:44:44 -0700
Subject: [PATCH 2/2] Add support for \e[1;3C and \e[1;3D
---
src/editline.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/src/editline.c b/src/editline.c
index d1cfbbc..350b5cb 100644
--- a/src/editline.c
+++ b/src/editline.c
@@ -1074,9 +1074,11 @@ static el_status_t meta(void)
for (c = 1; c < 3; c++)
seq[c] = tty_get();
- if (!strncmp(seq, ";5C", 3))
+ if (!strncmp(seq, ";5C", 3)
+ || !strncmp(seq, ";3C", 3))
return fd_word(); /* \e[1;5C = Ctrl+Right */
- if (!strncmp(seq, ";5D", 3))
+ if (!strncmp(seq, ";5D", 3)
+ || !strncmp(seq, ";3D", 3))
return bk_word(); /* \e[1;5D = Ctrl+Left */
break;

View file

@ -15,8 +15,6 @@
brotli, brotli,
bzip2, bzip2,
callPackage, callPackage,
capnproto-lix ? __forDefaults.capnproto-lix,
capnproto,
cmake, cmake,
curl, curl,
doxygen, doxygen,
@ -38,7 +36,6 @@
mercurial, mercurial,
meson, meson,
ninja, ninja,
ncurses,
openssl, openssl,
pegtl, pegtl,
pkg-config, pkg-config,
@ -82,36 +79,12 @@
boehmgc-nix = boehmgc.override { enableLargeConfig = true; }; boehmgc-nix = boehmgc.override { enableLargeConfig = true; };
editline-lix = editline.overrideAttrs (prev: { editline-lix = editline.overrideAttrs (prev: {
patches = (prev.patches or [ ]) ++ [ configureFlags = prev.configureFlags or [ ] ++ [ (lib.enableFeature true "sigstop") ];
# Recognize `Alt-Left` and `Alt-Right` for navigating by words in more
# terminals/shells/platforms.
#
# See: https://github.com/troglobit/editline/pull/70
./nix-support/editline.patch
];
configureFlags = (prev.configureFlags or [ ]) ++ [
# Enable SIGSTOP (Ctrl-Z) behavior.
(lib.enableFeature true "sigstop")
# Enable ANSI arrow keys.
(lib.enableFeature true "arrow-keys")
# Use termcap library to query terminal size.
(lib.enableFeature (ncurses != null) "termcap")
];
buildInputs = (prev.buildInputs or [ ]) ++ [ ncurses ];
}); });
build-release-notes = callPackage ./maintainers/build-release-notes.nix { }; build-release-notes = callPackage ./maintainers/build-release-notes.nix { };
# needs explicit c++20 to enable coroutine support
capnproto-lix = capnproto.overrideAttrs { CXXFLAGS = "-std=c++20"; };
}, },
}: }:
# gcc miscompiles coroutines at least until 13.2, possibly longer
assert stdenv.cc.isClang || lintInsteadOfBuild || internalApiDocs;
let let
inherit (__forDefaults) canRunInstalled; inherit (__forDefaults) canRunInstalled;
inherit (lib) fileset; inherit (lib) fileset;
@ -247,7 +220,6 @@ stdenv.mkDerivation (finalAttrs: {
ninja ninja
cmake cmake
rustc rustc
capnproto-lix
] ]
++ [ ++ [
(lib.getBin lowdown) (lib.getBin lowdown)
@ -288,7 +260,6 @@ stdenv.mkDerivation (finalAttrs: {
libsodium libsodium
toml11 toml11
pegtl pegtl
capnproto-lix
] ]
++ lib.optionals hostPlatform.isLinux [ ++ lib.optionals hostPlatform.isLinux [
libseccomp libseccomp

View file

@ -8,7 +8,12 @@ configure_file(
} }
) )
fs.copyfile('nix-profile.sh.in') # https://github.com/mesonbuild/meson/issues/860
configure_file(
input : 'nix-profile.sh.in',
output : 'nix-profile.sh.in',
copy : true,
)
foreach rc : [ '.sh', '.fish', '-daemon.sh', '-daemon.fish' ] foreach rc : [ '.sh', '.fish', '-daemon.sh', '-daemon.fish' ]
configure_file( configure_file(

View file

@ -9,24 +9,8 @@
#include "store-api.hh" #include "store-api.hh"
#include "command.hh" #include "command.hh"
#include <regex>
namespace nix { namespace nix {
static std::regex const identifierRegex("^[A-Za-z_][A-Za-z0-9_'-]*$");
static void warnInvalidNixIdentifier(const std::string & name)
{
std::smatch match;
if (!std::regex_match(name, match, identifierRegex)) {
warn("This Nix invocation specifies a value for argument '%s' which isn't a valid \
Nix identifier. The project is considering to drop support for this \
or to require quotes around args that aren't valid Nix identifiers. \
If you depend on this behvior, please reach out in \
https://git.lix.systems/lix-project/lix/issues/496 so we can discuss \
your use-case.", name);
}
}
MixEvalArgs::MixEvalArgs() MixEvalArgs::MixEvalArgs()
{ {
addFlag({ addFlag({
@ -34,10 +18,7 @@ MixEvalArgs::MixEvalArgs()
.description = "Pass the value *expr* as the argument *name* to Nix functions.", .description = "Pass the value *expr* as the argument *name* to Nix functions.",
.category = category, .category = category,
.labels = {"name", "expr"}, .labels = {"name", "expr"},
.handler = {[&](std::string name, std::string expr) { .handler = {[&](std::string name, std::string expr) { autoArgs[name] = 'E' + expr; }}
warnInvalidNixIdentifier(name);
autoArgs[name] = 'E' + expr;
}}
}); });
addFlag({ addFlag({
@ -45,10 +26,7 @@ MixEvalArgs::MixEvalArgs()
.description = "Pass the string *string* as the argument *name* to Nix functions.", .description = "Pass the string *string* as the argument *name* to Nix functions.",
.category = category, .category = category,
.labels = {"name", "string"}, .labels = {"name", "string"},
.handler = {[&](std::string name, std::string s) { .handler = {[&](std::string name, std::string s) { autoArgs[name] = 'S' + s; }},
warnInvalidNixIdentifier(name);
autoArgs[name] = 'S' + s;
}},
}); });
addFlag({ addFlag({

View file

@ -8,6 +8,10 @@
#include <string_view> #include <string_view>
#include <cerrno> #include <cerrno>
#ifdef READLINE
#include <readline/history.h>
#include <readline/readline.h>
#else
// editline < 1.15.2 don't wrap their API for C++ usage // editline < 1.15.2 don't wrap their API for C++ usage
// (added in https://github.com/troglobit/editline/commit/91398ceb3427b730995357e9d120539fb9bb7461). // (added in https://github.com/troglobit/editline/commit/91398ceb3427b730995357e9d120539fb9bb7461).
// This results in linker errors due to to name-mangling of editline C symbols. // This results in linker errors due to to name-mangling of editline C symbols.
@ -16,6 +20,7 @@
extern "C" { extern "C" {
#include <editline.h> #include <editline.h>
} }
#endif
#include "finally.hh" #include "finally.hh"
#include "repl-interacter.hh" #include "repl-interacter.hh"
@ -110,13 +115,17 @@ ReadlineLikeInteracter::Guard ReadlineLikeInteracter::init(detail::ReplCompleter
} catch (SysError & e) { } catch (SysError & e) {
logWarning(e.info()); logWarning(e.info());
} }
#ifndef READLINE
el_hist_size = 1000; el_hist_size = 1000;
#endif
read_history(historyFile.c_str()); read_history(historyFile.c_str());
auto oldRepl = curRepl; auto oldRepl = curRepl;
curRepl = repl; curRepl = repl;
Guard restoreRepl([oldRepl] { curRepl = oldRepl; }); Guard restoreRepl([oldRepl] { curRepl = oldRepl; });
#ifndef READLINE
rl_set_complete_func(completionCallback); rl_set_complete_func(completionCallback);
rl_set_list_possib_func(listPossibleCallback); rl_set_list_possib_func(listPossibleCallback);
#endif
return restoreRepl; return restoreRepl;
} }

View file

@ -79,7 +79,7 @@ struct AttrDb
state->txn->commit(); state->txn->commit();
state->txn.reset(); state->txn.reset();
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
@ -90,7 +90,7 @@ struct AttrDb
try { try {
return fun(); return fun();
} catch (SQLiteError &) { } catch (SQLiteError &) {
ignoreExceptionExceptInterrupt(); ignoreException();
failed = true; failed = true;
return 0; return 0;
} }
@ -329,7 +329,7 @@ static std::shared_ptr<AttrDb> makeAttrDb(
try { try {
return std::make_shared<AttrDb>(cfg, fingerprint, symbols); return std::make_shared<AttrDb>(cfg, fingerprint, symbols);
} catch (SQLiteError &) { } catch (SQLiteError &) {
ignoreExceptionExceptInterrupt(); ignoreException();
return nullptr; return nullptr;
} }
} }

View file

@ -394,8 +394,7 @@ static RegisterPrimOp primop_fetchGit({
[Git reference]: https://git-scm.com/book/en/v2/Git-Internals-Git-References [Git reference]: https://git-scm.com/book/en/v2/Git-Internals-Git-References
By default, the `ref` value is prefixed with `refs/heads/`. By default, the `ref` value is prefixed with `refs/heads/`.
As of 2.3.0, Nix will not prefix `refs/heads/` if `ref` starts with `refs/` or As of 2.3.0, Nix will not prefix `refs/heads/` if `ref` starts with `refs/`.
if `ref` looks like a commit hash for backwards compatibility with CppNix 2.3.
- `submodules` (default: `false`) - `submodules` (default: `false`)

View file

@ -7,32 +7,6 @@
namespace nix { namespace nix {
void to_json(nlohmann::json & j, const AcceptFlakeConfig & e)
{
if (e == AcceptFlakeConfig::False) {
j = false;
} else if (e == AcceptFlakeConfig::Ask) {
j = "ask";
} else if (e == AcceptFlakeConfig::True) {
j = true;
} else {
abort();
}
}
void from_json(const nlohmann::json & j, AcceptFlakeConfig & e)
{
if (j == false) {
e = AcceptFlakeConfig::False;
} else if (j == "ask") {
e = AcceptFlakeConfig::Ask;
} else if (j == true) {
e = AcceptFlakeConfig::True;
} else {
throw Error("Invalid accept-flake-config value '%s'", std::string(j));
}
}
template<> AcceptFlakeConfig BaseSetting<AcceptFlakeConfig>::parse(const std::string & str, const ApplyConfigOptions & options) const template<> AcceptFlakeConfig BaseSetting<AcceptFlakeConfig>::parse(const std::string & str, const ApplyConfigOptions & options) const
{ {
if (str == "true") return AcceptFlakeConfig::True; if (str == "true") return AcceptFlakeConfig::True;

View file

@ -13,9 +13,6 @@ namespace nix {
enum class AcceptFlakeConfig { False, Ask, True }; enum class AcceptFlakeConfig { False, Ask, True };
void to_json(nlohmann::json & j, const AcceptFlakeConfig & e);
void from_json(const nlohmann::json & j, AcceptFlakeConfig & e);
struct FetchSettings : public Config struct FetchSettings : public Config
{ {
FetchSettings(); FetchSettings();

View file

@ -1,4 +1,3 @@
#include "error.hh"
#include "fetchers.hh" #include "fetchers.hh"
#include "cache.hh" #include "cache.hh"
#include "globals.hh" #include "globals.hh"
@ -258,28 +257,6 @@ std::pair<StorePath, Input> fetchFromWorkdir(ref<Store> store, Input & input, co
} }
} // end namespace } // end namespace
static std::optional<Path> resolveRefToCachePath(
Input & input,
const Path & cacheDir,
std::vector<Path> & gitRefFileCandidates,
std::function<bool(const Path&)> condition)
{
if (input.getRef()->starts_with("refs/")) {
Path fullpath = cacheDir + "/" + *input.getRef();
if (condition(fullpath)) {
return fullpath;
}
}
for (auto & candidate : gitRefFileCandidates) {
if (condition(candidate)) {
return candidate;
}
}
return std::nullopt;
}
struct GitInputScheme : InputScheme struct GitInputScheme : InputScheme
{ {
std::optional<Input> inputFromURL(const ParsedURL & url, bool requireTree) const override std::optional<Input> inputFromURL(const ParsedURL & url, bool requireTree) const override
@ -562,13 +539,10 @@ struct GitInputScheme : InputScheme
runProgram("git", true, { "-c", "init.defaultBranch=" + gitInitialBranch, "init", "--bare", repoDir }); runProgram("git", true, { "-c", "init.defaultBranch=" + gitInitialBranch, "init", "--bare", repoDir });
} }
std::vector<Path> gitRefFileCandidates; Path localRefFile =
for (auto & infix : {"", "tags/", "heads/"}) { input.getRef()->compare(0, 5, "refs/") == 0
Path p = cacheDir + "/refs/" + infix + *input.getRef(); ? cacheDir + "/" + *input.getRef()
gitRefFileCandidates.push_back(p); : cacheDir + "/refs/heads/" + *input.getRef();
}
Path localRefFile;
bool doFetch; bool doFetch;
time_t now = time(0); time_t now = time(0);
@ -590,70 +564,29 @@ struct GitInputScheme : InputScheme
if (allRefs) { if (allRefs) {
doFetch = true; doFetch = true;
} else { } else {
std::function<bool(const Path&)> condition; /* If the local ref is older than tarball-ttl seconds, do a
condition = [&now](const Path & path) { git fetch to update the local ref to the remote ref. */
/* If the local ref is older than tarball-ttl seconds, do a struct stat st;
git fetch to update the local ref to the remote ref. */ doFetch = stat(localRefFile.c_str(), &st) != 0 ||
struct stat st; !isCacheFileWithinTtl(now, st);
return stat(path.c_str(), &st) == 0 &&
isCacheFileWithinTtl(now, st);
};
if (auto result = resolveRefToCachePath(
input,
cacheDir,
gitRefFileCandidates,
condition
)) {
localRefFile = *result;
doFetch = false;
} else {
doFetch = true;
}
} }
} }
// When having to fetch, we don't know `localRefFile` yet.
// Because git needs to figure out what we're fetching
// (i.e. is it a rev? a branch? a tag?)
if (doFetch) { if (doFetch) {
Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", actualUrl)); Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", actualUrl));
auto ref = input.getRef(); // FIXME: git stderr messes up our progress indicator, so
std::string fetchRef; // we're using --quiet for now. Should process its stderr.
if (allRefs) {
fetchRef = "refs/*";
} else if (
ref->starts_with("refs/")
|| *ref == "HEAD"
|| std::regex_match(*ref, revRegex))
{
fetchRef = *ref;
} else {
fetchRef = "refs/*/" + *ref;
}
try { try {
Finally finally([&]() { auto ref = input.getRef();
if (auto p = resolveRefToCachePath( auto fetchRef = allRefs
input, ? "refs/*"
cacheDir, : ref->compare(0, 5, "refs/") == 0
gitRefFileCandidates, ? *ref
pathExists : ref == "HEAD"
)) { ? *ref
localRefFile = *p; : "refs/heads/" + *ref;
} runProgram("git", true, { "-C", repoDir, "--git-dir", gitDir, "fetch", "--quiet", "--force", "--", actualUrl, fmt("%s:%s", fetchRef, fetchRef) }, true);
});
// FIXME: git stderr messes up our progress indicator, so
// we're using --quiet for now. Should process its stderr.
runProgram("git", true, {
"-C", repoDir,
"--git-dir", gitDir,
"fetch",
"--quiet",
"--force",
"--", actualUrl, fmt("%s:%s", fetchRef, fetchRef)
}, true);
} catch (Error & e) { } catch (Error & e) {
if (!pathExists(localRefFile)) throw; if (!pathExists(localRefFile)) throw;
warn("could not update local clone of Git repository '%s'; continuing with the most recent version", actualUrl); warn("could not update local clone of Git repository '%s'; continuing with the most recent version", actualUrl);

View file

@ -1,41 +0,0 @@
#include "crash-handler.hh"
#include "fmt.hh"
#include <boost/core/demangle.hpp>
#include <exception>
namespace nix {
namespace {
void onTerminate()
{
std::cerr << "Lix crashed. This is a bug. We would appreciate if you report it along with what caused it at https://git.lix.systems/lix-project/lix/issues with the following information included:\n\n";
try {
std::exception_ptr eptr = std::current_exception();
if (eptr) {
std::rethrow_exception(eptr);
} else {
std::cerr << "std::terminate() called without exception\n";
}
} catch (const std::exception & ex) {
std::cerr << "Exception: " << boost::core::demangle(typeid(ex).name()) << ": " << ex.what() << "\n";
} catch (...) {
std::cerr << "Unknown exception! Spooky.\n";
}
std::cerr << "Stack trace:\n";
nix::printStackTrace();
std::abort();
}
}
void registerCrashHandler()
{
// DO NOT use this for signals. Boost stacktrace is very much not
// async-signal-safe, and in a world with ASLR, addr2line is pointless.
//
// If you want signals, set up a minidump system and do it out-of-process.
std::set_terminate(onTerminate);
}
}

View file

@ -1,21 +0,0 @@
#pragma once
/// @file Crash handler for Lix that prints back traces (hopefully in instances where it is not just going to crash the process itself).
/*
* Author's note: This will probably be partially/fully supplanted by a
* minidump writer like the following once we get our act together on crashes a
* little bit more:
* https://github.com/rust-minidump/minidump-writer
* https://github.com/EmbarkStudios/crash-handling
* (out of process implementation *should* be able to be done on-demand)
*
* Such an out-of-process implementation could then both make minidumps and
* print stack traces for arbitrarily messed-up process states such that we can
* safely give out backtraces for SIGSEGV and other deadly signals.
*/
namespace nix {
/** Registers the Lix crash handler for std::terminate (currently; will support more crashes later). See also detectStackOverflow(). */
void registerCrashHandler();
}

View file

@ -7,7 +7,7 @@ namespace nix {
LogFormat defaultLogFormat = LogFormat::raw; LogFormat defaultLogFormat = LogFormat::raw;
LogFormat parseLogFormat(const std::string & logFormatStr) { LogFormat parseLogFormat(const std::string & logFormatStr) {
if (logFormatStr == "raw") if (logFormatStr == "raw" || getEnv("NIX_GET_COMPLETIONS"))
return LogFormat::raw; return LogFormat::raw;
else if (logFormatStr == "raw-with-logs") else if (logFormatStr == "raw-with-logs")
return LogFormat::rawWithLogs; return LogFormat::rawWithLogs;

View file

@ -1,6 +1,5 @@
libmain_sources = files( libmain_sources = files(
'common-args.cc', 'common-args.cc',
'crash-handler.cc',
'loggers.cc', 'loggers.cc',
'progress-bar.cc', 'progress-bar.cc',
'shared.cc', 'shared.cc',
@ -9,7 +8,6 @@ libmain_sources = files(
libmain_headers = files( libmain_headers = files(
'common-args.hh', 'common-args.hh',
'crash-handler.hh',
'loggers.hh', 'loggers.hh',
'progress-bar.hh', 'progress-bar.hh',
'shared.hh', 'shared.hh',

View file

@ -92,7 +92,7 @@ void ProgressBar::resume()
nextWakeup = draw(*state, {}); nextWakeup = draw(*state, {});
state.wait_for(quitCV, std::chrono::milliseconds(50)); state.wait_for(quitCV, std::chrono::milliseconds(50));
} }
eraseProgressDisplay(*state); writeLogsToStderr("\r\e[K");
}); });
} }
@ -558,8 +558,7 @@ std::optional<char> ProgressBar::ask(std::string_view msg)
{ {
auto state(state_.lock()); auto state(state_.lock());
if (state->paused > 0 || !isatty(STDIN_FILENO)) return {}; if (state->paused > 0 || !isatty(STDIN_FILENO)) return {};
eraseProgressDisplay(*state); std::cerr << fmt("\r\e[K%s ", msg);
std::cerr << msg;
auto s = trim(readLine(STDIN_FILENO)); auto s = trim(readLine(STDIN_FILENO));
if (s.size() != 1) return {}; if (s.size() != 1) return {};
draw(*state, {}); draw(*state, {});

View file

@ -1,4 +1,3 @@
#include "crash-handler.hh"
#include "globals.hh" #include "globals.hh"
#include "shared.hh" #include "shared.hh"
#include "store-api.hh" #include "store-api.hh"
@ -119,8 +118,6 @@ static void sigHandler(int signo) { }
void initNix() void initNix()
{ {
registerCrashHandler();
/* Turn on buffering for cerr. */ /* Turn on buffering for cerr. */
static char buf[1024]; static char buf[1024];
std::cerr.rdbuf()->pubsetbuf(buf, sizeof(buf)); std::cerr.rdbuf()->pubsetbuf(buf, sizeof(buf));
@ -338,15 +335,12 @@ int handleExceptions(const std::string & programName, std::function<void()> fun)
} catch (BaseError & e) { } catch (BaseError & e) {
logError(e.info()); logError(e.info());
return e.info().status; return e.info().status;
} catch (const std::bad_alloc & e) { } catch (std::bad_alloc & e) {
printError(error + "out of memory"); printError(error + "out of memory");
return 1; return 1;
} catch (const std::exception & e) { } catch (std::exception & e) {
// Random exceptions bubbling into main are cause for bug reports, crash printError(error + e.what());
std::terminate(); return 1;
} catch (...) {
// Explicitly do not tolerate non-std exceptions escaping.
std::terminate();
} }
return 0; return 0;
@ -395,7 +389,7 @@ RunPager::~RunPager()
pid.wait(); pid.wait();
} }
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -111,7 +111,7 @@ struct PrintFreed
/** /**
* Install a SIGSEGV handler to detect stack overflows. See also registerCrashHandler(). * Install a SIGSEGV handler to detect stack overflows.
*/ */
void detectStackOverflow(); void detectStackOverflow();

View file

@ -11,13 +11,7 @@
#include "drv-output-substitution-goal.hh" #include "drv-output-substitution-goal.hh"
#include "strings.hh" #include "strings.hh"
#include <boost/outcome/try.hpp>
#include <fstream> #include <fstream>
#include <kj/array.h>
#include <kj/async-unix.h>
#include <kj/async.h>
#include <kj/debug.h>
#include <kj/vector.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/un.h> #include <sys/un.h>
@ -71,6 +65,7 @@ DerivationGoal::DerivationGoal(const StorePath & drvPath,
, wantedOutputs(wantedOutputs) , wantedOutputs(wantedOutputs)
, buildMode(buildMode) , buildMode(buildMode)
{ {
state = &DerivationGoal::getDerivation;
name = fmt( name = fmt(
"building of '%s' from .drv file", "building of '%s' from .drv file",
DerivedPath::Built { makeConstantStorePathRef(drvPath), wantedOutputs }.to_string(worker.store)); DerivedPath::Built { makeConstantStorePathRef(drvPath), wantedOutputs }.to_string(worker.store));
@ -90,6 +85,7 @@ DerivationGoal::DerivationGoal(const StorePath & drvPath, const BasicDerivation
{ {
this->drv = std::make_unique<Derivation>(drv); this->drv = std::make_unique<Derivation>(drv);
state = &DerivationGoal::haveDerivation;
name = fmt( name = fmt(
"building of '%s' from in-memory derivation", "building of '%s' from in-memory derivation",
DerivedPath::Built { makeConstantStorePathRef(drvPath), drv.outputNames() }.to_string(worker.store)); DerivedPath::Built { makeConstantStorePathRef(drvPath), drv.outputNames() }.to_string(worker.store));
@ -107,7 +103,17 @@ DerivationGoal::~DerivationGoal() noexcept(false)
{ {
/* Careful: we should never ever throw an exception from a /* Careful: we should never ever throw an exception from a
destructor. */ destructor. */
try { closeLogFile(); } catch (...) { ignoreExceptionInDestructor(); } try { closeLogFile(); } catch (...) { ignoreException(); }
}
std::string DerivationGoal::key()
{
/* Ensure that derivations get built in order of their name,
i.e. a derivation named "aardvark" always comes before
"baboon". And substitution goals always happen before
derivation goals (due to "b$"). */
return "b$" + std::string(drvPath.name()) + "$" + worker.store.printStorePath(drvPath);
} }
@ -118,24 +124,20 @@ void DerivationGoal::killChild()
} }
Goal::WorkResult DerivationGoal::timedOut(Error && ex) Goal::Finished DerivationGoal::timedOut(Error && ex)
{ {
killChild(); killChild();
return done(BuildResult::TimedOut, {}, std::move(ex)); return done(BuildResult::TimedOut, {}, std::move(ex));
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::workImpl() noexcept Goal::WorkResult DerivationGoal::work(bool inBuildSlot)
{ {
return useDerivation ? getDerivation() : haveDerivation(); return (this->*state)(inBuildSlot);
} }
bool DerivationGoal::addWantedOutputs(const OutputsSpec & outputs) void DerivationGoal::addWantedOutputs(const OutputsSpec & outputs)
{ {
if (isDone) {
return false;
}
auto newWanted = wantedOutputs.union_(outputs); auto newWanted = wantedOutputs.union_(outputs);
switch (needRestart) { switch (needRestart) {
case NeedRestartForMoreOutputs::OutputsUnmodifedDontNeed: case NeedRestartForMoreOutputs::OutputsUnmodifedDontNeed:
@ -152,38 +154,32 @@ bool DerivationGoal::addWantedOutputs(const OutputsSpec & outputs)
break; break;
}; };
wantedOutputs = newWanted; wantedOutputs = newWanted;
return true;
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::getDerivation() noexcept Goal::WorkResult DerivationGoal::getDerivation(bool inBuildSlot)
try { {
trace("init"); trace("init");
/* The first thing to do is to make sure that the derivation /* The first thing to do is to make sure that the derivation
exists. If it doesn't, it may be created through a exists. If it doesn't, it may be created through a
substitute. */ substitute. */
if (buildMode == bmNormal && worker.evalStore.isValidPath(drvPath)) { if (buildMode == bmNormal && worker.evalStore.isValidPath(drvPath)) {
co_return co_await loadDerivation(); return loadDerivation(inBuildSlot);
} }
(co_await waitForGoals(worker.goalFactory().makePathSubstitutionGoal(drvPath))).value();
co_return co_await loadDerivation(); state = &DerivationGoal::loadDerivation;
} catch (...) { return WaitForGoals{{worker.goalFactory().makePathSubstitutionGoal(drvPath)}};
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::loadDerivation() noexcept Goal::WorkResult DerivationGoal::loadDerivation(bool inBuildSlot)
try { {
trace("loading derivation"); trace("loading derivation");
if (nrFailed != 0) { if (nrFailed != 0) {
return {done( return done(BuildResult::MiscFailure, {}, Error("cannot build missing derivation '%s'", worker.store.printStorePath(drvPath)));
BuildResult::MiscFailure,
{},
Error("cannot build missing derivation '%s'", worker.store.printStorePath(drvPath))
)};
} }
/* `drvPath' should already be a root, but let's be on the safe /* `drvPath' should already be a root, but let's be on the safe
@ -205,14 +201,12 @@ try {
} }
assert(drv); assert(drv);
return haveDerivation(); return haveDerivation(inBuildSlot);
} catch (...) {
return {std::current_exception()};
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::haveDerivation() noexcept Goal::WorkResult DerivationGoal::haveDerivation(bool inBuildSlot)
try { {
trace("have derivation"); trace("have derivation");
parsedDrv = std::make_unique<ParsedDerivation>(drvPath, *drv); parsedDrv = std::make_unique<ParsedDerivation>(drvPath, *drv);
@ -239,7 +233,7 @@ try {
}); });
} }
co_return co_await gaveUpOnSubstitution(); return gaveUpOnSubstitution(inBuildSlot);
} }
for (auto & i : drv->outputsAndOptPaths(worker.store)) for (auto & i : drv->outputsAndOptPaths(worker.store))
@ -261,19 +255,19 @@ try {
/* If they are all valid, then we're done. */ /* If they are all valid, then we're done. */
if (allValid && buildMode == bmNormal) { if (allValid && buildMode == bmNormal) {
co_return done(BuildResult::AlreadyValid, std::move(validOutputs)); return done(BuildResult::AlreadyValid, std::move(validOutputs));
} }
/* We are first going to try to create the invalid output paths /* We are first going to try to create the invalid output paths
through substitutes. If that doesn't work, we'll build through substitutes. If that doesn't work, we'll build
them. */ them. */
kj::Vector<std::pair<GoalPtr, kj::Promise<Result<WorkResult>>>> dependencies; WaitForGoals result;
if (settings.useSubstitutes) { if (settings.useSubstitutes) {
if (parsedDrv->substitutesAllowed()) { if (parsedDrv->substitutesAllowed()) {
for (auto & [outputName, status] : initialOutputs) { for (auto & [outputName, status] : initialOutputs) {
if (!status.wanted) continue; if (!status.wanted) continue;
if (!status.known) if (!status.known)
dependencies.add( result.goals.insert(
worker.goalFactory().makeDrvOutputSubstitutionGoal( worker.goalFactory().makeDrvOutputSubstitutionGoal(
DrvOutput{status.outputHash, outputName}, DrvOutput{status.outputHash, outputName},
buildMode == bmRepair ? Repair : NoRepair buildMode == bmRepair ? Repair : NoRepair
@ -281,7 +275,7 @@ try {
); );
else { else {
auto * cap = getDerivationCA(*drv); auto * cap = getDerivationCA(*drv);
dependencies.add(worker.goalFactory().makePathSubstitutionGoal( result.goals.insert(worker.goalFactory().makePathSubstitutionGoal(
status.known->path, status.known->path,
buildMode == bmRepair ? Repair : NoRepair, buildMode == bmRepair ? Repair : NoRepair,
cap ? std::optional { *cap } : std::nullopt)); cap ? std::optional { *cap } : std::nullopt));
@ -292,31 +286,24 @@ try {
} }
} }
if (!dependencies.empty()) { /* to prevent hang (no wake-up event) */ if (result.goals.empty()) { /* to prevent hang (no wake-up event) */
(co_await waitForGoals(dependencies.releaseAsArray())).value(); return outputsSubstitutionTried(inBuildSlot);
} else {
state = &DerivationGoal::outputsSubstitutionTried;
return result;
} }
co_return co_await outputsSubstitutionTried();
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::outputsSubstitutionTried() noexcept Goal::WorkResult DerivationGoal::outputsSubstitutionTried(bool inBuildSlot)
try { {
trace("all outputs substituted (maybe)"); trace("all outputs substituted (maybe)");
assert(drv->type().isPure()); assert(drv->type().isPure());
if (nrFailed > 0 && nrFailed > nrNoSubstituters + nrIncompleteClosure && !settings.tryFallback) if (nrFailed > 0 && nrFailed > nrNoSubstituters + nrIncompleteClosure && !settings.tryFallback) {
{ return done(BuildResult::TransientFailure, {},
return {done( Error("some substitutes for the outputs of derivation '%s' failed (usually happens due to networking issues); try '--fallback' to build derivation from source ",
BuildResult::TransientFailure, worker.store.printStorePath(drvPath)));
{},
Error(
"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)
)
)};
} }
/* If the substitutes form an incomplete closure, then we should /* If the substitutes form an incomplete closure, then we should
@ -350,13 +337,13 @@ try {
if (needRestart == NeedRestartForMoreOutputs::OutputsAddedDoNeed) { if (needRestart == NeedRestartForMoreOutputs::OutputsAddedDoNeed) {
needRestart = NeedRestartForMoreOutputs::OutputsUnmodifedDontNeed; needRestart = NeedRestartForMoreOutputs::OutputsUnmodifedDontNeed;
return haveDerivation(); return haveDerivation(inBuildSlot);
} }
auto [allValid, validOutputs] = checkPathValidity(); auto [allValid, validOutputs] = checkPathValidity();
if (buildMode == bmNormal && allValid) { if (buildMode == bmNormal && allValid) {
return {done(BuildResult::Substituted, std::move(validOutputs))}; return done(BuildResult::Substituted, std::move(validOutputs));
} }
if (buildMode == bmRepair && allValid) { if (buildMode == bmRepair && allValid) {
return repairClosure(); return repairClosure();
@ -366,17 +353,15 @@ try {
worker.store.printStorePath(drvPath)); worker.store.printStorePath(drvPath));
/* Nothing to wait for; tail call */ /* Nothing to wait for; tail call */
return gaveUpOnSubstitution(); return gaveUpOnSubstitution(inBuildSlot);
} catch (...) {
return {std::current_exception()};
} }
/* At least one of the output paths could not be /* At least one of the output paths could not be
produced using a substitute. So we have to build instead. */ produced using a substitute. So we have to build instead. */
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::gaveUpOnSubstitution() noexcept Goal::WorkResult DerivationGoal::gaveUpOnSubstitution(bool inBuildSlot)
try { {
kj::Vector<std::pair<GoalPtr, kj::Promise<Result<WorkResult>>>> dependencies; WaitForGoals result;
/* At this point we are building all outputs, so if more are wanted there /* At this point we are building all outputs, so if more are wanted there
is no need to restart. */ is no need to restart. */
@ -389,7 +374,7 @@ try {
addWaiteeDerivedPath = [&](ref<SingleDerivedPath> inputDrv, const DerivedPathMap<StringSet>::ChildNode & inputNode) { addWaiteeDerivedPath = [&](ref<SingleDerivedPath> inputDrv, const DerivedPathMap<StringSet>::ChildNode & inputNode) {
if (!inputNode.value.empty()) if (!inputNode.value.empty())
dependencies.add(worker.goalFactory().makeGoal( result.goals.insert(worker.goalFactory().makeGoal(
DerivedPath::Built { DerivedPath::Built {
.drvPath = inputDrv, .drvPath = inputDrv,
.outputs = inputNode.value, .outputs = inputNode.value,
@ -434,20 +419,20 @@ try {
if (!settings.useSubstitutes) if (!settings.useSubstitutes)
throw Error("dependency '%s' of '%s' does not exist, and substitution is disabled", throw Error("dependency '%s' of '%s' does not exist, and substitution is disabled",
worker.store.printStorePath(i), worker.store.printStorePath(drvPath)); worker.store.printStorePath(i), worker.store.printStorePath(drvPath));
dependencies.add(worker.goalFactory().makePathSubstitutionGoal(i)); result.goals.insert(worker.goalFactory().makePathSubstitutionGoal(i));
} }
if (!dependencies.empty()) {/* to prevent hang (no wake-up event) */ if (result.goals.empty()) {/* to prevent hang (no wake-up event) */
(co_await waitForGoals(dependencies.releaseAsArray())).value(); return inputsRealised(inBuildSlot);
} else {
state = &DerivationGoal::inputsRealised;
return result;
} }
co_return co_await inputsRealised();
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::repairClosure() noexcept Goal::WorkResult DerivationGoal::repairClosure()
try { {
assert(drv->type().isPure()); assert(drv->type().isPure());
/* If we're repairing, we now know that our own outputs are valid. /* If we're repairing, we now know that our own outputs are valid.
@ -482,7 +467,7 @@ try {
} }
/* Check each path (slow!). */ /* Check each path (slow!). */
kj::Vector<std::pair<GoalPtr, kj::Promise<Result<WorkResult>>>> dependencies; WaitForGoals result;
for (auto & i : outputClosure) { for (auto & i : outputClosure) {
if (worker.pathContentsGood(i)) continue; if (worker.pathContentsGood(i)) continue;
printError( printError(
@ -490,9 +475,9 @@ try {
worker.store.printStorePath(i), worker.store.printStorePath(drvPath)); 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())
dependencies.add(worker.goalFactory().makePathSubstitutionGoal(i, Repair)); result.goals.insert(worker.goalFactory().makePathSubstitutionGoal(i, Repair));
else else
dependencies.add(worker.goalFactory().makeGoal( result.goals.insert(worker.goalFactory().makeGoal(
DerivedPath::Built { DerivedPath::Built {
.drvPath = makeConstantStorePathRef(drvPath2->second), .drvPath = makeConstantStorePathRef(drvPath2->second),
.outputs = OutputsSpec::All { }, .outputs = OutputsSpec::All { },
@ -500,50 +485,40 @@ try {
bmRepair)); bmRepair));
} }
if (dependencies.empty()) { if (result.goals.empty()) {
co_return done(BuildResult::AlreadyValid, assertPathValidity()); return done(BuildResult::AlreadyValid, assertPathValidity());
} }
(co_await waitForGoals(dependencies.releaseAsArray())).value(); state = &DerivationGoal::closureRepaired;
co_return co_await closureRepaired(); return result;
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::closureRepaired() noexcept Goal::WorkResult DerivationGoal::closureRepaired(bool inBuildSlot)
try { {
trace("closure repaired"); trace("closure repaired");
if (nrFailed > 0) if (nrFailed > 0)
throw Error("some paths in the output closure of derivation '%s' could not be repaired", throw Error("some paths in the output closure of derivation '%s' could not be repaired",
worker.store.printStorePath(drvPath)); worker.store.printStorePath(drvPath));
return {done(BuildResult::AlreadyValid, assertPathValidity())}; return done(BuildResult::AlreadyValid, assertPathValidity());
} catch (...) {
return {std::current_exception()};
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::inputsRealised() noexcept Goal::WorkResult DerivationGoal::inputsRealised(bool inBuildSlot)
try { {
trace("all inputs realised"); trace("all inputs realised");
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));
co_return done( return done(BuildResult::DependencyFailed, {}, Error(
BuildResult::DependencyFailed,
{},
Error(
"%s dependencies of derivation '%s' failed to build", "%s dependencies of derivation '%s' failed to build",
nrFailed, nrFailed, worker.store.printStorePath(drvPath)));
worker.store.printStorePath(drvPath)
)
);
} }
if (retrySubstitution == RetrySubstitution::YesNeed) { if (retrySubstitution == RetrySubstitution::YesNeed) {
retrySubstitution = RetrySubstitution::AlreadyRetried; retrySubstitution = RetrySubstitution::AlreadyRetried;
co_return co_await haveDerivation(); return haveDerivation(inBuildSlot);
} }
/* Gather information necessary for computing the closure and/or /* Gather information necessary for computing the closure and/or
@ -605,12 +580,11 @@ try {
worker.store.printStorePath(pathResolved), worker.store.printStorePath(pathResolved),
}); });
auto dependency = worker.goalFactory().makeDerivationGoal( resolvedDrvGoal = worker.goalFactory().makeDerivationGoal(
pathResolved, wantedOutputs, buildMode); pathResolved, wantedOutputs, buildMode);
resolvedDrvGoal = dependency.first;
(co_await waitForGoals(std::move(dependency))).value(); state = &DerivationGoal::resolvedFinished;
co_return co_await resolvedFinished(); return WaitForGoals{{resolvedDrvGoal}};
} }
std::function<void(const StorePath &, const DerivedPathMap<StringSet>::ChildNode &)> accumInputPaths; std::function<void(const StorePath &, const DerivedPathMap<StringSet>::ChildNode &)> accumInputPaths;
@ -674,9 +648,8 @@ try {
/* Okay, try to build. Note that here we don't wait for a build /* 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 slot to become available, since we don't need one if there is a
build hook. */ build hook. */
co_return co_await tryToBuild(); state = &DerivationGoal::tryToBuild;
} catch (...) { return tryToBuild(inBuildSlot);
co_return result::failure(std::current_exception());
} }
void DerivationGoal::started() void DerivationGoal::started()
@ -692,9 +665,8 @@ void DerivationGoal::started()
mcRunningBuilds = worker.runningBuilds.addTemporarily(1); mcRunningBuilds = worker.runningBuilds.addTemporarily(1);
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::tryToBuild() noexcept Goal::WorkResult DerivationGoal::tryToBuild(bool inBuildSlot)
try { {
retry:
trace("trying to build"); trace("trying to build");
/* Obtain locks on all output paths, if the paths are known a priori. /* Obtain locks on all output paths, if the paths are known a priori.
@ -728,9 +700,7 @@ retry:
if (!actLock) if (!actLock)
actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting, actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting,
fmt("waiting for lock on %s", Magenta(showPaths(lockFiles)))); fmt("waiting for lock on %s", Magenta(showPaths(lockFiles))));
co_await waitForAWhile(); return WaitForAWhile{};
// we can loop very often, and `co_return co_await` always allocates a new frame
goto retry;
} }
actLock.reset(); actLock.reset();
@ -747,7 +717,7 @@ retry:
if (buildMode != bmCheck && allValid) { if (buildMode != bmCheck && allValid) {
debug("skipping build of derivation '%s', someone beat us to it", worker.store.printStorePath(drvPath)); debug("skipping build of derivation '%s', someone beat us to it", worker.store.printStorePath(drvPath));
outputLocks.setDeletion(true); outputLocks.setDeletion(true);
co_return done(BuildResult::AlreadyValid, std::move(validOutputs)); return done(BuildResult::AlreadyValid, std::move(validOutputs));
} }
/* If any of the outputs already exist but are not valid, delete /* If any of the outputs already exist but are not valid, delete
@ -767,63 +737,49 @@ retry:
&& settings.maxBuildJobs.get() != 0; && settings.maxBuildJobs.get() != 0;
if (!buildLocally) { if (!buildLocally) {
auto hookReply = tryBuildHook(); auto hookReply = tryBuildHook(inBuildSlot);
switch (hookReply.index()) { auto result = std::visit(
case 0: { overloaded{
HookReply::Accept & a = std::get<0>(hookReply); [&](HookReply::Accept & a) -> std::optional<WorkResult> {
/* Yes, it has started doing so. Wait until we get /* Yes, it has started doing so. Wait until we get
EOF from the hook. */ EOF from the hook. */
actLock.reset(); actLock.reset();
buildResult.startTime = time(0); // inexact buildResult.startTime = time(0); // inexact
started(); state = &DerivationGoal::buildDone;
auto r = co_await a.promise; started();
if (r.has_value()) { return WaitForWorld{std::move(a.fds), false};
co_return co_await buildDone(); },
} else if (r.has_error()) { [&](HookReply::Postpone) -> std::optional<WorkResult> {
co_return r.assume_error(); /* Not now; wait until at least one child finishes or
} else { the wake-up timeout expires. */
co_return r.assume_exception(); if (!actLock)
} actLock = std::make_unique<Activity>(*logger, lvlTalkative, actBuildWaiting,
} fmt("waiting for a machine to build '%s'", Magenta(worker.store.printStorePath(drvPath))));
outputLocks.unlock();
case 1: { return WaitForAWhile{};
HookReply::Decline _ [[gnu::unused]] = std::get<1>(hookReply); },
break; [&](HookReply::Decline) -> std::optional<WorkResult> {
} /* We should do it ourselves. */
return std::nullopt;
case 2: { },
HookReply::Postpone _ [[gnu::unused]] = std::get<2>(hookReply); },
/* Not now; wait until at least one child finishes or hookReply);
the wake-up timeout expires. */ if (result) {
if (!actLock) return std::move(*result);
actLock = std::make_unique<Activity>(*logger, lvlTalkative, actBuildWaiting,
fmt("waiting for a machine to build '%s'", Magenta(worker.store.printStorePath(drvPath))));
outputLocks.unlock();
co_await waitForAWhile();
goto retry;
}
default:
// can't static_assert this because HookReply *subclasses* variant and std::variant_size breaks
assert(false && "unexpected hook reply");
} }
} }
actLock.reset(); actLock.reset();
co_return co_await tryLocalBuild(); state = &DerivationGoal::tryLocalBuild;
} catch (...) { return tryLocalBuild(inBuildSlot);
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::tryLocalBuild() noexcept Goal::WorkResult DerivationGoal::tryLocalBuild(bool inBuildSlot) {
try {
throw Error( throw Error(
"unable to build with a primary store that isn't a local store; " "unable to build with a primary store that isn't a local store; "
"either pass a different '--store' or enable remote builds." "either pass a different '--store' or enable remote builds."
"\nhttps://docs.lix.systems/manual/lix/stable/advanced-topics/distributed-builds.html"); "\nhttps://docs.lix.systems/manual/lix/stable/advanced-topics/distributed-builds.html");
} catch (...) {
return {std::current_exception()};
} }
@ -863,7 +819,7 @@ void replaceValidPath(const Path & storePath, const Path & tmpPath)
// attempt to recover // attempt to recover
movePath(oldPath, storePath); movePath(oldPath, storePath);
} catch (...) { } catch (...) {
ignoreExceptionExceptInterrupt(); ignoreException();
} }
throw; throw;
} }
@ -979,11 +935,10 @@ void runPostBuildHook(
proc.getStdout()->drainInto(sink); proc.getStdout()->drainInto(sink);
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::buildDone() noexcept Goal::WorkResult DerivationGoal::buildDone(bool inBuildSlot)
try { {
trace("build done"); trace("build done");
slotToken = {};
Finally releaseBuildUser([&](){ this->cleanupHookFinally(); }); Finally releaseBuildUser([&](){ this->cleanupHookFinally(); });
cleanupPreChildKill(); cleanupPreChildKill();
@ -999,6 +954,9 @@ try {
buildResult.timesBuilt++; buildResult.timesBuilt++;
buildResult.stopTime = time(0); buildResult.stopTime = time(0);
/* So the child is gone now. */
worker.childTerminated(this);
/* Close the read side of the logger pipe. */ /* Close the read side of the logger pipe. */
closeReadPipes(); closeReadPipes();
@ -1072,7 +1030,7 @@ try {
outputLocks.setDeletion(true); outputLocks.setDeletion(true);
outputLocks.unlock(); outputLocks.unlock();
return {done(BuildResult::Built, std::move(builtOutputs))}; return done(BuildResult::Built, std::move(builtOutputs));
} catch (BuildError & e) { } catch (BuildError & e) {
outputLocks.unlock(); outputLocks.unlock();
@ -1093,14 +1051,12 @@ try {
BuildResult::PermanentFailure; BuildResult::PermanentFailure;
} }
return {done(st, {}, std::move(e))}; return done(st, {}, std::move(e));
} }
} catch (...) {
return {std::current_exception()};
} }
kj::Promise<Result<Goal::WorkResult>> DerivationGoal::resolvedFinished() noexcept Goal::WorkResult DerivationGoal::resolvedFinished(bool inBuildSlot)
try { {
trace("resolved derivation finished"); trace("resolved derivation finished");
assert(resolvedDrvGoal); assert(resolvedDrvGoal);
@ -1167,12 +1123,10 @@ try {
if (status == BuildResult::AlreadyValid) if (status == BuildResult::AlreadyValid)
status = BuildResult::ResolvesToAlreadyValid; status = BuildResult::ResolvesToAlreadyValid;
return {done(status, std::move(builtOutputs))}; return done(status, std::move(builtOutputs));
} catch (...) {
return {std::current_exception()};
} }
HookReply DerivationGoal::tryBuildHook() HookReply DerivationGoal::tryBuildHook(bool inBuildSlot)
{ {
if (!worker.hook.available || !useDerivation) return HookReply::Decline{}; if (!worker.hook.available || !useDerivation) return HookReply::Decline{};
@ -1184,7 +1138,7 @@ HookReply DerivationGoal::tryBuildHook()
/* Send the request to the hook. */ /* Send the request to the hook. */
worker.hook.instance->sink worker.hook.instance->sink
<< "try" << "try"
<< (slotToken.valid() ? 1 : 0) << (inBuildSlot ? 1 : 0)
<< drv->platform << drv->platform
<< worker.store.printStorePath(drvPath) << worker.store.printStorePath(drvPath)
<< parsedDrv->getRequiredSystemFeatures(); << parsedDrv->getRequiredSystemFeatures();
@ -1270,8 +1224,12 @@ HookReply DerivationGoal::tryBuildHook()
/* Create the log file and pipe. */ /* Create the log file and pipe. */
Path logFile = openLogFile(); Path logFile = openLogFile();
std::set<int> fds;
fds.insert(hook->fromHook.get());
fds.insert(hook->builderOut.get());
builderOutFD = &hook->builderOut; builderOutFD = &hook->builderOut;
return HookReply::Accept{handleChildOutput()};
return HookReply::Accept{std::move(fds)};
} }
@ -1331,69 +1289,23 @@ void DerivationGoal::closeLogFile()
} }
Goal::WorkResult DerivationGoal::tooMuchLogs() Goal::WorkResult DerivationGoal::handleChildOutput(int fd, std::string_view data)
{ {
killChild(); assert(builderOutFD);
return done(
BuildResult::LogLimitExceeded, {},
Error("%s killed after writing more than %d bytes of log output",
getName(), settings.maxLogSize));
}
struct DerivationGoal::InputStream final : private kj::AsyncObject auto tooMuchLogs = [&] {
{ killChild();
int fd; return done(
kj::UnixEventPort::FdObserver observer; BuildResult::LogLimitExceeded, {},
Error("%s killed after writing more than %d bytes of log output",
InputStream(kj::UnixEventPort & ep, int fd) getName(), settings.maxLogSize));
: fd(fd) };
, observer(ep, fd, kj::UnixEventPort::FdObserver::OBSERVE_READ)
{
int flags = fcntl(fd, F_GETFL);
if (flags < 0) {
throw SysError("fcntl(F_GETFL) failed on fd %i", fd);
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
throw SysError("fcntl(F_SETFL) failed on fd %i", fd);
}
}
kj::Promise<std::string_view> read(kj::ArrayPtr<char> buffer)
{
const auto res = ::read(fd, buffer.begin(), buffer.size());
// closing a pty endpoint causes EIO on the other endpoint. stock kj streams
// do not handle this and throw exceptions we can't ask for errno instead :(
// (we can't use `errno` either because kj may well have mangled it by now.)
if (res == 0 || (res == -1 && errno == EIO)) {
return std::string_view{};
}
KJ_NONBLOCKING_SYSCALL(res) {}
if (res > 0) {
return std::string_view{buffer.begin(), static_cast<size_t>(res)};
}
return observer.whenBecomesReadable().then([this, buffer] {
return read(buffer);
});
}
};
kj::Promise<Outcome<void, Goal::WorkResult>> DerivationGoal::handleBuilderOutput(InputStream & in) noexcept
try {
auto buf = kj::heapArray<char>(4096);
while (true) {
auto data = co_await in.read(buf);
lastChildActivity = worker.aio.provider->getTimer().now();
if (data.empty()) {
co_return result::success();
}
// local & `ssh://`-builds are dealt with here.
if (fd == builderOutFD->get()) {
logSize += data.size(); logSize += data.size();
if (settings.maxLogSize && logSize > settings.maxLogSize) { if (settings.maxLogSize && logSize > settings.maxLogSize) {
co_return tooMuchLogs(); return tooMuchLogs();
} }
for (auto c : data) for (auto c : data)
@ -1408,22 +1320,10 @@ try {
} }
if (logSink) (*logSink)(data); if (logSink) (*logSink)(data);
return StillAlive{};
} }
} catch (...) {
co_return std::current_exception();
}
kj::Promise<Outcome<void, Goal::WorkResult>> DerivationGoal::handleHookOutput(InputStream & in) noexcept
try {
auto buf = kj::heapArray<char>(4096);
while (true) {
auto data = co_await in.read(buf);
lastChildActivity = worker.aio.provider->getTimer().now();
if (data.empty()) {
co_return result::success();
}
if (hook && fd == hook->fromHook.get()) {
for (auto c : data) for (auto c : data)
if (c == '\n') { if (c == '\n') {
auto json = parseJSONMessage(currentHookLine); auto json = parseJSONMessage(currentHookLine);
@ -1439,7 +1339,7 @@ try {
(fields.size() > 0 ? fields[0].get<std::string>() : "") + "\n"; (fields.size() > 0 ? fields[0].get<std::string>() : "") + "\n";
logSize += logLine.size(); logSize += logLine.size();
if (settings.maxLogSize && logSize > settings.maxLogSize) { if (settings.maxLogSize && logSize > settings.maxLogSize) {
co_return tooMuchLogs(); return tooMuchLogs();
} }
(*logSink)(logLine); (*logSink)(logLine);
} else if (type == resSetPhase && ! fields.is_null()) { } else if (type == resSetPhase && ! fields.is_null()) {
@ -1463,83 +1363,16 @@ try {
} else } else
currentHookLine += c; currentHookLine += c;
} }
} catch (...) {
co_return std::current_exception(); return StillAlive{};
} }
kj::Promise<Outcome<void, Goal::WorkResult>> DerivationGoal::handleChildOutput() noexcept
try {
assert(builderOutFD);
auto builderIn = kj::heap<InputStream>(worker.aio.unixEventPort, builderOutFD->get()); void DerivationGoal::handleEOF(int fd)
kj::Own<InputStream> hookIn;
if (hook) {
hookIn = kj::heap<InputStream>(worker.aio.unixEventPort, hook->fromHook.get());
}
auto handlers = handleChildStreams(*builderIn, hookIn.get()).attach(std::move(builderIn), std::move(hookIn));
if (respectsTimeouts() && settings.buildTimeout != 0) {
handlers = handlers.exclusiveJoin(
worker.aio.provider->getTimer()
.afterDelay(settings.buildTimeout.get() * kj::SECONDS)
.then([this]() -> Outcome<void, WorkResult> {
return timedOut(
Error("%1% timed out after %2% seconds", name, settings.buildTimeout)
);
})
);
}
return handlers.then([this](auto r) -> Outcome<void, WorkResult> {
if (!currentLogLine.empty()) flushLine();
return r;
});
} catch (...) {
return {std::current_exception()};
}
kj::Promise<Outcome<void, Goal::WorkResult>> DerivationGoal::monitorForSilence() noexcept
{ {
while (true) { if (!currentLogLine.empty()) flushLine();
const auto stash = lastChildActivity;
auto waitUntil = lastChildActivity + settings.maxSilentTime.get() * kj::SECONDS;
co_await worker.aio.provider->getTimer().atTime(waitUntil);
if (lastChildActivity == stash) {
co_return timedOut(
Error("%1% timed out after %2% seconds of silence", name, settings.maxSilentTime)
);
}
}
} }
kj::Promise<Outcome<void, Goal::WorkResult>>
DerivationGoal::handleChildStreams(InputStream & builderIn, InputStream * hookIn) noexcept
{
lastChildActivity = worker.aio.provider->getTimer().now();
auto handlers = kj::joinPromisesFailFast([&] {
kj::Vector<kj::Promise<Outcome<void, WorkResult>>> parts{2};
parts.add(handleBuilderOutput(builderIn));
if (hookIn) {
parts.add(handleHookOutput(*hookIn));
}
return parts.releaseAsArray();
}());
if (respectsTimeouts() && settings.maxSilentTime != 0) {
handlers = handlers.exclusiveJoin(monitorForSilence().then([](auto r) {
return kj::arr(std::move(r));
}));
}
for (auto r : co_await handlers) {
BOOST_OUTCOME_CO_TRYV(r);
}
co_return result::success();
}
void DerivationGoal::flushLine() void DerivationGoal::flushLine()
{ {
@ -1680,13 +1513,11 @@ SingleDrvOutputs DerivationGoal::assertPathValidity()
} }
Goal::WorkResult DerivationGoal::done( Goal::Finished DerivationGoal::done(
BuildResult::Status status, BuildResult::Status status,
SingleDrvOutputs builtOutputs, SingleDrvOutputs builtOutputs,
std::optional<Error> ex) std::optional<Error> ex)
{ {
isDone = true;
outputLocks.unlock(); outputLocks.unlock();
buildResult.status = status; buildResult.status = status;
if (ex) if (ex)
@ -1717,7 +1548,7 @@ Goal::WorkResult DerivationGoal::done(
logError(ex->info()); logError(ex->info());
} }
return WorkResult{ return Finished{
.exitCode = buildResult.success() ? ecSuccess : ecFailed, .exitCode = buildResult.success() ? ecSuccess : ecFailed,
.result = buildResult, .result = buildResult,
.ex = ex ? std::make_shared<Error>(std::move(*ex)) : nullptr, .ex = ex ? std::make_shared<Error>(std::move(*ex)) : nullptr,
@ -1756,4 +1587,5 @@ void DerivationGoal::waiteeDone(GoalPtr waitee)
} }
} }
} }
} }

View file

@ -8,7 +8,6 @@
#include "store-api.hh" #include "store-api.hh"
#include "pathlocks.hh" #include "pathlocks.hh"
#include "goal.hh" #include "goal.hh"
#include <kj/time.h>
namespace nix { namespace nix {
@ -18,7 +17,7 @@ struct HookInstance;
struct HookReplyBase { struct HookReplyBase {
struct [[nodiscard]] Accept { struct [[nodiscard]] Accept {
kj::Promise<Outcome<void, Goal::WorkResult>> promise; std::set<int> fds;
}; };
struct [[nodiscard]] Decline {}; struct [[nodiscard]] Decline {};
struct [[nodiscard]] Postpone {}; struct [[nodiscard]] Postpone {};
@ -71,14 +70,6 @@ struct InitialOutput {
*/ */
struct DerivationGoal : public Goal struct DerivationGoal : public Goal
{ {
struct InputStream;
/**
* Whether this goal has completed. Completed goals can not be
* asked for more outputs, a new goal must be created instead.
*/
bool isDone = false;
/** /**
* Whether to use an on-disk .drv file. * Whether to use an on-disk .drv file.
*/ */
@ -184,11 +175,6 @@ struct DerivationGoal : public Goal
std::map<std::string, InitialOutput> initialOutputs; std::map<std::string, InitialOutput> initialOutputs;
/**
* Build result.
*/
BuildResult buildResult;
/** /**
* File descriptor for the log file. * File descriptor for the log file.
*/ */
@ -227,6 +213,9 @@ struct DerivationGoal : public Goal
*/ */
std::optional<DerivationType> derivationType; std::optional<DerivationType> derivationType;
typedef WorkResult (DerivationGoal::*GoalState)(bool inBuildSlot);
GoalState state;
BuildMode buildMode; BuildMode buildMode;
NotifyingCounter<uint64_t>::Bump mcExpectedBuilds, mcRunningBuilds; NotifyingCounter<uint64_t>::Bump mcExpectedBuilds, mcRunningBuilds;
@ -253,35 +242,37 @@ struct DerivationGoal : public Goal
BuildMode buildMode = bmNormal); BuildMode buildMode = bmNormal);
virtual ~DerivationGoal() noexcept(false); virtual ~DerivationGoal() noexcept(false);
WorkResult timedOut(Error && ex); Finished timedOut(Error && ex) override;
kj::Promise<Result<WorkResult>> workImpl() noexcept override; std::string key() override;
WorkResult work(bool inBuildSlot) override;
/** /**
* Add wanted outputs to an already existing derivation goal. * Add wanted outputs to an already existing derivation goal.
*/ */
bool addWantedOutputs(const OutputsSpec & outputs); void addWantedOutputs(const OutputsSpec & outputs);
/** /**
* The states. * The states.
*/ */
kj::Promise<Result<WorkResult>> getDerivation() noexcept; WorkResult getDerivation(bool inBuildSlot);
kj::Promise<Result<WorkResult>> loadDerivation() noexcept; WorkResult loadDerivation(bool inBuildSlot);
kj::Promise<Result<WorkResult>> haveDerivation() noexcept; WorkResult haveDerivation(bool inBuildSlot);
kj::Promise<Result<WorkResult>> outputsSubstitutionTried() noexcept; WorkResult outputsSubstitutionTried(bool inBuildSlot);
kj::Promise<Result<WorkResult>> gaveUpOnSubstitution() noexcept; WorkResult gaveUpOnSubstitution(bool inBuildSlot);
kj::Promise<Result<WorkResult>> closureRepaired() noexcept; WorkResult closureRepaired(bool inBuildSlot);
kj::Promise<Result<WorkResult>> inputsRealised() noexcept; WorkResult inputsRealised(bool inBuildSlot);
kj::Promise<Result<WorkResult>> tryToBuild() noexcept; WorkResult tryToBuild(bool inBuildSlot);
virtual kj::Promise<Result<WorkResult>> tryLocalBuild() noexcept; virtual WorkResult tryLocalBuild(bool inBuildSlot);
kj::Promise<Result<WorkResult>> buildDone() noexcept; WorkResult buildDone(bool inBuildSlot);
kj::Promise<Result<WorkResult>> resolvedFinished() noexcept; WorkResult resolvedFinished(bool inBuildSlot);
/** /**
* Is the build hook willing to perform the build? * Is the build hook willing to perform the build?
*/ */
HookReply tryBuildHook(); HookReply tryBuildHook(bool inBuildSlot);
virtual int getChildStatus(); virtual int getChildStatus();
@ -321,19 +312,13 @@ struct DerivationGoal : public Goal
virtual void cleanupPostOutputsRegisteredModeCheck(); virtual void cleanupPostOutputsRegisteredModeCheck();
virtual void cleanupPostOutputsRegisteredModeNonCheck(); virtual void cleanupPostOutputsRegisteredModeNonCheck();
protected: /**
kj::TimePoint lastChildActivity = kj::minValue; * Callback used by the worker to write to the log.
*/
kj::Promise<Outcome<void, WorkResult>> handleChildOutput() noexcept; WorkResult handleChildOutput(int fd, std::string_view data) override;
kj::Promise<Outcome<void, WorkResult>> void handleEOF(int fd) override;
handleChildStreams(InputStream & builderIn, InputStream * hookIn) noexcept;
kj::Promise<Outcome<void, WorkResult>> handleBuilderOutput(InputStream & in) noexcept;
kj::Promise<Outcome<void, WorkResult>> handleHookOutput(InputStream & in) noexcept;
kj::Promise<Outcome<void, WorkResult>> monitorForSilence() noexcept;
WorkResult tooMuchLogs();
void flushLine(); void flushLine();
public:
/** /**
* Wrappers around the corresponding Store methods that first consult the * Wrappers around the corresponding Store methods that first consult the
* derivation. This is currently needed because when there is no drv file * derivation. This is currently needed because when there is no drv file
@ -361,22 +346,17 @@ public:
*/ */
virtual void killChild(); virtual void killChild();
kj::Promise<Result<WorkResult>> repairClosure() noexcept; WorkResult repairClosure();
void started(); void started();
WorkResult done( Finished done(
BuildResult::Status status, BuildResult::Status status,
SingleDrvOutputs builtOutputs = {}, SingleDrvOutputs builtOutputs = {},
std::optional<Error> ex = {}); std::optional<Error> ex = {});
void waiteeDone(GoalPtr waitee) override; void waiteeDone(GoalPtr waitee) override;
virtual bool respectsTimeouts()
{
return false;
}
StorePathSet exportReferences(const StorePathSet & storePaths); StorePathSet exportReferences(const StorePathSet & storePaths);
JobCategory jobCategory() const override { JobCategory jobCategory() const override {

View file

@ -4,9 +4,6 @@
#include "worker.hh" #include "worker.hh"
#include "substitution-goal.hh" #include "substitution-goal.hh"
#include "signals.hh" #include "signals.hh"
#include <kj/array.h>
#include <kj/async.h>
#include <kj/vector.h>
namespace nix { namespace nix {
@ -19,32 +16,31 @@ DrvOutputSubstitutionGoal::DrvOutputSubstitutionGoal(
: Goal(worker, isDependency) : Goal(worker, isDependency)
, id(id) , id(id)
{ {
state = &DrvOutputSubstitutionGoal::init;
name = fmt("substitution of '%s'", id.to_string()); name = fmt("substitution of '%s'", id.to_string());
trace("created"); trace("created");
} }
kj::Promise<Result<Goal::WorkResult>> DrvOutputSubstitutionGoal::workImpl() noexcept Goal::WorkResult DrvOutputSubstitutionGoal::init(bool inBuildSlot)
try { {
trace("init"); trace("init");
/* If the derivation already exists, were done */ /* If the derivation already exists, were done */
if (worker.store.queryRealisation(id)) { if (worker.store.queryRealisation(id)) {
co_return WorkResult{ecSuccess}; return Finished{ecSuccess, std::move(buildResult)};
} }
subs = settings.useSubstitutes ? getDefaultSubstituters() : std::list<ref<Store>>(); subs = settings.useSubstitutes ? getDefaultSubstituters() : std::list<ref<Store>>();
co_return co_await tryNext(); return tryNext(inBuildSlot);
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> DrvOutputSubstitutionGoal::tryNext() noexcept Goal::WorkResult DrvOutputSubstitutionGoal::tryNext(bool inBuildSlot)
try { {
trace("trying next substituter"); trace("trying next substituter");
if (!slotToken.valid()) { if (!inBuildSlot) {
slotToken = co_await worker.substitutions.acquire(); return WaitForSlot{};
} }
maintainRunningSubstitutions = worker.runningSubstitutions.addTemporarily(1); maintainRunningSubstitutions = worker.runningSubstitutions.addTemporarily(1);
@ -61,7 +57,7 @@ try {
/* Hack: don't indicate failure if there were no substituters. /* Hack: don't indicate failure if there were no substituters.
In that case the calling derivation should just do a In that case the calling derivation should just do a
build. */ build. */
co_return WorkResult{substituterFailed ? ecFailed : ecNoSubstituters}; return Finished{substituterFailed ? ecFailed : ecNoSubstituters, std::move(buildResult)};
} }
sub = subs.front(); sub = subs.front();
@ -71,26 +67,23 @@ try {
some other error occurs), so it must not touch `this`. So put some other error occurs), so it must not touch `this`. So put
the shared state in a separate refcounted object. */ the shared state in a separate refcounted object. */
downloadState = std::make_shared<DownloadState>(); downloadState = std::make_shared<DownloadState>();
auto pipe = kj::newPromiseAndCrossThreadFulfiller<void>(); downloadState->outPipe.create();
downloadState->outPipe = kj::mv(pipe.fulfiller);
downloadState->result = downloadState->result =
std::async(std::launch::async, [downloadState{downloadState}, id{id}, sub{sub}] { std::async(std::launch::async, [downloadState{downloadState}, id{id}, sub{sub}] {
Finally updateStats([&]() { downloadState->outPipe->fulfill(); });
ReceiveInterrupts receiveInterrupts; ReceiveInterrupts receiveInterrupts;
Finally updateStats([&]() { downloadState->outPipe.writeSide.close(); });
return sub->queryRealisation(id); return sub->queryRealisation(id);
}); });
co_await pipe.promise; state = &DrvOutputSubstitutionGoal::realisationFetched;
co_return co_await realisationFetched(); return WaitForWorld{{downloadState->outPipe.readSide.get()}, true};
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> DrvOutputSubstitutionGoal::realisationFetched() noexcept Goal::WorkResult DrvOutputSubstitutionGoal::realisationFetched(bool inBuildSlot)
try { {
worker.childTerminated(this);
maintainRunningSubstitutions.reset(); maintainRunningSubstitutions.reset();
slotToken = {};
try { try {
outputInfo = downloadState->result.get(); outputInfo = downloadState->result.get();
@ -100,10 +93,10 @@ try {
} }
if (!outputInfo) { if (!outputInfo) {
co_return co_await tryNext(); return tryNext(inBuildSlot);
} }
kj::Vector<std::pair<GoalPtr, kj::Promise<Result<WorkResult>>>> dependencies; WaitForGoals result;
for (const auto & [depId, depPath] : outputInfo->dependentRealisations) { for (const auto & [depId, depPath] : outputInfo->dependentRealisations) {
if (depId != id) { if (depId != id) {
if (auto localOutputInfo = worker.store.queryRealisation(depId); if (auto localOutputInfo = worker.store.queryRealisation(depId);
@ -117,46 +110,56 @@ try {
worker.store.printStorePath(localOutputInfo->outPath), worker.store.printStorePath(localOutputInfo->outPath),
worker.store.printStorePath(depPath) worker.store.printStorePath(depPath)
); );
co_return co_await tryNext(); return tryNext(inBuildSlot);
} }
dependencies.add(worker.goalFactory().makeDrvOutputSubstitutionGoal(depId)); result.goals.insert(worker.goalFactory().makeDrvOutputSubstitutionGoal(depId));
} }
} }
dependencies.add(worker.goalFactory().makePathSubstitutionGoal(outputInfo->outPath)); result.goals.insert(worker.goalFactory().makePathSubstitutionGoal(outputInfo->outPath));
if (!dependencies.empty()) { if (result.goals.empty()) {
(co_await waitForGoals(dependencies.releaseAsArray())).value(); return outPathValid(inBuildSlot);
} else {
state = &DrvOutputSubstitutionGoal::outPathValid;
return result;
} }
co_return co_await outPathValid();
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> DrvOutputSubstitutionGoal::outPathValid() noexcept Goal::WorkResult DrvOutputSubstitutionGoal::outPathValid(bool inBuildSlot)
try { {
assert(outputInfo); assert(outputInfo);
trace("output path substituted"); trace("output path substituted");
if (nrFailed > 0) { if (nrFailed > 0) {
debug("The output path of the derivation output '%s' could not be substituted", id.to_string()); debug("The output path of the derivation output '%s' could not be substituted", id.to_string());
return {WorkResult{ return Finished{
nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed, nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed,
}}; std::move(buildResult),
};
} }
worker.store.registerDrvOutput(*outputInfo); worker.store.registerDrvOutput(*outputInfo);
return finished(); return finished();
} catch (...) {
return {std::current_exception()};
} }
kj::Promise<Result<Goal::WorkResult>> DrvOutputSubstitutionGoal::finished() noexcept Goal::WorkResult DrvOutputSubstitutionGoal::finished()
try { {
trace("finished"); trace("finished");
return {WorkResult{ecSuccess}}; return Finished{ecSuccess, std::move(buildResult)};
} catch (...) {
return {std::current_exception()};
} }
std::string DrvOutputSubstitutionGoal::key()
{
/* "a$" ensures substitution goals happen before derivation
goals. */
return "a$" + std::string(id.to_string());
}
Goal::WorkResult DrvOutputSubstitutionGoal::work(bool inBuildSlot)
{
return (this->*state)(inBuildSlot);
}
} }

View file

@ -45,7 +45,7 @@ class DrvOutputSubstitutionGoal : public Goal {
struct DownloadState struct DownloadState
{ {
kj::Own<kj::CrossThreadPromiseFulfiller<void>> outPipe; Pipe outPipe;
std::future<std::shared_ptr<const Realisation>> result; std::future<std::shared_ptr<const Realisation>> result;
}; };
@ -65,12 +65,20 @@ public:
std::optional<ContentAddress> ca = std::nullopt std::optional<ContentAddress> ca = std::nullopt
); );
kj::Promise<Result<WorkResult>> tryNext() noexcept; typedef WorkResult (DrvOutputSubstitutionGoal::*GoalState)(bool inBuildSlot);
kj::Promise<Result<WorkResult>> realisationFetched() noexcept; GoalState state;
kj::Promise<Result<WorkResult>> outPathValid() noexcept;
kj::Promise<Result<WorkResult>> finished() noexcept;
kj::Promise<Result<WorkResult>> workImpl() noexcept override; WorkResult init(bool inBuildSlot);
WorkResult tryNext(bool inBuildSlot);
WorkResult realisationFetched(bool inBuildSlot);
WorkResult outPathValid(bool inBuildSlot);
WorkResult finished();
Finished timedOut(Error && ex) override { abort(); };
std::string key() override;
WorkResult work(bool inBuildSlot) override;
JobCategory jobCategory() const override { JobCategory jobCategory() const override {
return JobCategory::Substitution; return JobCategory::Substitution;

View file

@ -6,33 +6,27 @@
namespace nix { namespace nix {
static auto runWorker(Worker & worker, auto mkGoals)
{
return worker.run(mkGoals);
}
void Store::buildPaths(const std::vector<DerivedPath> & reqs, BuildMode buildMode, std::shared_ptr<Store> evalStore) void Store::buildPaths(const std::vector<DerivedPath> & reqs, BuildMode buildMode, std::shared_ptr<Store> evalStore)
{ {
auto aio = kj::setupAsyncIo(); Worker worker(*this, evalStore ? *evalStore : *this);
Worker worker(*this, evalStore ? *evalStore : *this, aio);
auto goals = runWorker(worker, [&](GoalFactory & gf) { auto goals = worker.run([&](GoalFactory & gf) {
Worker::Targets goals; Goals goals;
for (auto & br : reqs) for (auto & br : reqs)
goals.emplace(gf.makeGoal(br, buildMode)); goals.insert(gf.makeGoal(br, buildMode));
return goals; return goals;
}); });
StringSet failed; StringSet failed;
std::shared_ptr<Error> ex; std::shared_ptr<Error> ex;
for (auto & [i, result] : goals) { for (auto & i : goals) {
if (result.ex) { if (i->ex) {
if (ex) if (ex)
logError(result.ex->info()); logError(i->ex->info());
else else
ex = result.ex; ex = i->ex;
} }
if (result.exitCode != Goal::ecSuccess) { if (i->exitCode != Goal::ecSuccess) {
if (auto i2 = dynamic_cast<DerivationGoal *>(i.get())) if (auto i2 = dynamic_cast<DerivationGoal *>(i.get()))
failed.insert(printStorePath(i2->drvPath)); failed.insert(printStorePath(i2->drvPath));
else if (auto i2 = dynamic_cast<PathSubstitutionGoal *>(i.get())) else if (auto i2 = dynamic_cast<PathSubstitutionGoal *>(i.get()))
@ -54,17 +48,15 @@ std::vector<KeyedBuildResult> Store::buildPathsWithResults(
BuildMode buildMode, BuildMode buildMode,
std::shared_ptr<Store> evalStore) std::shared_ptr<Store> evalStore)
{ {
auto aio = kj::setupAsyncIo(); Worker worker(*this, evalStore ? *evalStore : *this);
Worker worker(*this, evalStore ? *evalStore : *this, aio);
std::vector<std::pair<const DerivedPath &, GoalPtr>> state; std::vector<std::pair<const DerivedPath &, GoalPtr>> state;
auto goals = runWorker(worker, [&](GoalFactory & gf) { auto goals = worker.run([&](GoalFactory & gf) {
Worker::Targets goals; Goals goals;
for (const auto & req : reqs) { for (const auto & req : reqs) {
auto goal = gf.makeGoal(req, buildMode); auto goal = gf.makeGoal(req, buildMode);
state.push_back({req, goal.first}); goals.insert(goal);
goals.emplace(std::move(goal)); state.push_back({req, goal});
} }
return goals; return goals;
}); });
@ -72,7 +64,7 @@ std::vector<KeyedBuildResult> Store::buildPathsWithResults(
std::vector<KeyedBuildResult> results; std::vector<KeyedBuildResult> results;
for (auto & [req, goalPtr] : state) for (auto & [req, goalPtr] : state)
results.emplace_back(goals[goalPtr].result.restrictTo(req)); results.emplace_back(goalPtr->buildResult.restrictTo(req));
return results; return results;
} }
@ -80,17 +72,14 @@ std::vector<KeyedBuildResult> Store::buildPathsWithResults(
BuildResult Store::buildDerivation(const StorePath & drvPath, const BasicDerivation & drv, BuildResult Store::buildDerivation(const StorePath & drvPath, const BasicDerivation & drv,
BuildMode buildMode) BuildMode buildMode)
{ {
auto aio = kj::setupAsyncIo(); Worker worker(*this, *this);
Worker worker(*this, *this, aio);
try { try {
auto goals = runWorker(worker, [&](GoalFactory & gf) { auto goals = worker.run([&](GoalFactory & gf) -> Goals {
Worker::Targets goals; return Goals{gf.makeBasicDerivationGoal(drvPath, drv, OutputsSpec::All{}, buildMode)};
goals.emplace(gf.makeBasicDerivationGoal(drvPath, drv, OutputsSpec::All{}, buildMode));
return goals;
}); });
auto [goal, result] = *goals.begin(); auto goal = *goals.begin();
return result.result.restrictTo(DerivedPath::Built { return goal->buildResult.restrictTo(DerivedPath::Built {
.drvPath = makeConstantStorePathRef(drvPath), .drvPath = makeConstantStorePathRef(drvPath),
.outputs = OutputsSpec::All {}, .outputs = OutputsSpec::All {},
}); });
@ -108,20 +97,16 @@ void Store::ensurePath(const StorePath & path)
/* If the path is already valid, we're done. */ /* If the path is already valid, we're done. */
if (isValidPath(path)) return; if (isValidPath(path)) return;
auto aio = kj::setupAsyncIo(); Worker worker(*this, *this);
Worker worker(*this, *this, aio);
auto goals = runWorker(worker, [&](GoalFactory & gf) { auto goals =
Worker::Targets goals; worker.run([&](GoalFactory & gf) { return Goals{gf.makePathSubstitutionGoal(path)}; });
goals.emplace(gf.makePathSubstitutionGoal(path)); auto goal = *goals.begin();
return goals;
});
auto [goal, result] = *goals.begin();
if (result.exitCode != Goal::ecSuccess) { if (goal->exitCode != Goal::ecSuccess) {
if (result.ex) { if (goal->ex) {
result.ex->withExitStatus(worker.failingExitStatus()); goal->ex->withExitStatus(worker.failingExitStatus());
throw std::move(*result.ex); throw std::move(*goal->ex);
} else } else
throw Error(worker.failingExitStatus(), "path '%s' does not exist and cannot be created", printStorePath(path)); throw Error(worker.failingExitStatus(), "path '%s' does not exist and cannot be created", printStorePath(path));
} }
@ -130,32 +115,27 @@ void Store::ensurePath(const StorePath & path)
void Store::repairPath(const StorePath & path) void Store::repairPath(const StorePath & path)
{ {
auto aio = kj::setupAsyncIo(); Worker worker(*this, *this);
Worker worker(*this, *this, aio);
auto goals = runWorker(worker, [&](GoalFactory & gf) { auto goals = worker.run([&](GoalFactory & gf) {
Worker::Targets goals; return Goals{gf.makePathSubstitutionGoal(path, Repair)};
goals.emplace(gf.makePathSubstitutionGoal(path, Repair));
return goals;
}); });
auto [goal, result] = *goals.begin(); auto goal = *goals.begin();
if (result.exitCode != Goal::ecSuccess) { if (goal->exitCode != Goal::ecSuccess) {
/* Since substituting the path didn't work, if we have a valid /* Since substituting the path didn't work, if we have a valid
deriver, then rebuild the deriver. */ deriver, then rebuild the deriver. */
auto info = queryPathInfo(path); auto info = queryPathInfo(path);
if (info->deriver && isValidPath(*info->deriver)) { if (info->deriver && isValidPath(*info->deriver)) {
worker.run([&](GoalFactory & gf) { worker.run([&](GoalFactory & gf) {
Worker::Targets goals; return Goals{gf.makeGoal(
goals.emplace(gf.makeGoal(
DerivedPath::Built{ DerivedPath::Built{
.drvPath = makeConstantStorePathRef(*info->deriver), .drvPath = makeConstantStorePathRef(*info->deriver),
// FIXME: Should just build the specific output we need. // FIXME: Should just build the specific output we need.
.outputs = OutputsSpec::All{}, .outputs = OutputsSpec::All{},
}, },
bmRepair bmRepair
)); )};
return goals;
}); });
} else } else
throw Error(worker.failingExitStatus(), "cannot repair path '%s'", printStorePath(path)); throw Error(worker.failingExitStatus(), "cannot repair path '%s'", printStorePath(path));

View file

@ -1,73 +1,18 @@
#include "goal.hh" #include "goal.hh"
#include "async-collect.hh"
#include "worker.hh"
#include <boost/outcome/try.hpp>
#include <kj/time.h>
namespace nix { namespace nix {
bool CompareGoalPtrs::operator() (const GoalPtr & a, const GoalPtr & b) const {
std::string s1 = a->key();
std::string s2 = b->key();
return s1 < s2;
}
void Goal::trace(std::string_view s) void Goal::trace(std::string_view s)
{ {
debug("%1%: %2%", name, s); debug("%1%: %2%", name, s);
} }
kj::Promise<void> Goal::waitForAWhile()
{
trace("wait for a while");
/* If we are polling goals that are waiting for a lock, then wake
up after a few seconds at most. */
return worker.aio.provider->getTimer().afterDelay(settings.pollInterval.get() * kj::SECONDS);
}
kj::Promise<Result<Goal::WorkResult>> Goal::work() noexcept
try {
BOOST_OUTCOME_CO_TRY(auto result, co_await workImpl());
trace("done");
cleanup();
co_return std::move(result);
} catch (...) {
co_return result::failure(std::current_exception());
}
kj::Promise<Result<void>>
Goal::waitForGoals(kj::Array<std::pair<GoalPtr, kj::Promise<Result<WorkResult>>>> dependencies) noexcept
try {
auto left = dependencies.size();
for (auto & [dep, p] : dependencies) {
p = p.then([this, dep, &left](auto _result) -> Result<WorkResult> {
BOOST_OUTCOME_TRY(auto result, _result);
left--;
trace(fmt("waitee '%s' done; %d left", dep->name, left));
if (result.exitCode != Goal::ecSuccess) ++nrFailed;
if (result.exitCode == Goal::ecNoSubstituters) ++nrNoSubstituters;
if (result.exitCode == Goal::ecIncompleteClosure) ++nrIncompleteClosure;
return std::move(result);
}).eagerlyEvaluate(nullptr);
}
auto collectDeps = asyncCollect(std::move(dependencies));
while (auto item = co_await collectDeps.next()) {
auto & [dep, _result] = *item;
BOOST_OUTCOME_CO_TRY(auto result, _result);
waiteeDone(dep);
if (result.exitCode == ecFailed && !settings.keepGoing) {
co_return result::success();
}
}
co_return result::success();
} catch (...) {
co_return result::failure(std::current_exception());
}
} }

View file

@ -1,13 +1,9 @@
#pragma once #pragma once
///@file ///@file
#include "async-semaphore.hh"
#include "result.hh"
#include "types.hh" #include "types.hh"
#include "store-api.hh" #include "store-api.hh"
#include "build-result.hh" #include "build-result.hh"
#include <concepts> // IWYU pragma: keep
#include <kj/async.h>
namespace nix { namespace nix {
@ -21,11 +17,22 @@ class Worker;
* A pointer to a goal. * A pointer to a goal.
*/ */
typedef std::shared_ptr<Goal> GoalPtr; typedef std::shared_ptr<Goal> GoalPtr;
typedef std::weak_ptr<Goal> WeakGoalPtr;
struct CompareGoalPtrs {
bool operator() (const GoalPtr & a, const GoalPtr & b) const;
};
/** /**
* Set of goals. * Set of goals.
*/ */
typedef std::set<GoalPtr> Goals; typedef std::set<GoalPtr, CompareGoalPtrs> Goals;
typedef std::set<WeakGoalPtr, std::owner_less<WeakGoalPtr>> WeakGoals;
/**
* A map of paths to goals (and the other way around).
*/
typedef std::map<StorePath, WeakGoalPtr> WeakGoalMap;
/** /**
* Used as a hint to the worker on how to schedule a particular goal. For example, * Used as a hint to the worker on how to schedule a particular goal. For example,
@ -60,6 +67,17 @@ struct Goal
*/ */
const bool isDependency; const bool isDependency;
/**
* Goals that this goal is waiting for.
*/
Goals waitees;
/**
* Goals waiting for this one to finish. Must use weak pointers
* here to prevent cycles.
*/
WeakGoals waiters;
/** /**
* Number of goals we are/were waiting for that have failed. * Number of goals we are/were waiting for that have failed.
*/ */
@ -82,11 +100,30 @@ struct Goal
*/ */
std::string name; std::string name;
protected: /**
AsyncSemaphore::Token slotToken; * Whether the goal is finished.
*/
std::optional<ExitCode> exitCode;
/**
* Build result.
*/
BuildResult buildResult;
public: public:
struct [[nodiscard]] WorkResult {
struct [[nodiscard]] StillAlive {};
struct [[nodiscard]] WaitForSlot {};
struct [[nodiscard]] WaitForAWhile {};
struct [[nodiscard]] ContinueImmediately {};
struct [[nodiscard]] WaitForGoals {
Goals goals;
};
struct [[nodiscard]] WaitForWorld {
std::set<int> fds;
bool inBuildSlot;
};
struct [[nodiscard]] Finished {
ExitCode exitCode; ExitCode exitCode;
BuildResult result; BuildResult result;
std::shared_ptr<Error> ex; std::shared_ptr<Error> ex;
@ -96,23 +133,24 @@ public:
bool checkMismatch = false; bool checkMismatch = false;
}; };
protected: struct [[nodiscard]] WorkResult : std::variant<
kj::Promise<void> waitForAWhile(); StillAlive,
kj::Promise<Result<void>> WaitForSlot,
waitForGoals(kj::Array<std::pair<GoalPtr, kj::Promise<Result<WorkResult>>>> dependencies) noexcept; WaitForAWhile,
ContinueImmediately,
template<std::derived_from<Goal>... G> WaitForGoals,
kj::Promise<Result<void>> WaitForWorld,
waitForGoals(std::pair<std::shared_ptr<G>, kj::Promise<Result<WorkResult>>>... goals) noexcept Finished>
{ {
return waitForGoals( WorkResult() = delete;
kj::arrOf<std::pair<GoalPtr, kj::Promise<Result<WorkResult>>>>(std::move(goals)...) using variant::variant;
); };
}
virtual kj::Promise<Result<WorkResult>> workImpl() noexcept = 0; /**
* Exception containing an error message, if any.
*/
std::shared_ptr<Error> ex;
public:
explicit Goal(Worker & worker, bool isDependency) explicit Goal(Worker & worker, bool isDependency)
: worker(worker) : worker(worker)
, isDependency(isDependency) , isDependency(isDependency)
@ -123,10 +161,24 @@ public:
trace("goal destroyed"); trace("goal destroyed");
} }
kj::Promise<Result<WorkResult>> work() noexcept; virtual WorkResult work(bool inBuildSlot) = 0;
virtual void waiteeDone(GoalPtr waitee) { } virtual void waiteeDone(GoalPtr waitee) { }
virtual WorkResult handleChildOutput(int fd, std::string_view data)
{
abort();
}
virtual void handleEOF(int fd)
{
}
virtual bool respectsTimeouts()
{
return false;
}
void trace(std::string_view s); void trace(std::string_view s);
std::string getName() const std::string getName() const
@ -134,6 +186,15 @@ public:
return name; return name;
} }
/**
* Callback in case of a timeout. It should wake up its waiters,
* get rid of any running child processes that are being monitored
* by the worker (important!), etc.
*/
virtual Finished timedOut(Error && ex) = 0;
virtual std::string key() = 0;
virtual void cleanup() { } virtual void cleanup() { }
/** /**

View file

@ -1,5 +1,4 @@
#include "child.hh" #include "child.hh"
#include "error.hh"
#include "file-system.hh" #include "file-system.hh"
#include "globals.hh" #include "globals.hh"
#include "hook-instance.hh" #include "hook-instance.hh"
@ -87,7 +86,7 @@ HookInstance::~HookInstance()
toHook.reset(); toHook.reset();
if (pid) pid.kill(); if (pid) pid.kill();
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -1,5 +1,4 @@
#include "local-derivation-goal.hh" #include "local-derivation-goal.hh"
#include "error.hh"
#include "indirect-root-store.hh" #include "indirect-root-store.hh"
#include "machines.hh" #include "machines.hh"
#include "store-api.hh" #include "store-api.hh"
@ -99,9 +98,9 @@ LocalDerivationGoal::~LocalDerivationGoal() noexcept(false)
{ {
/* Careful: we should never ever throw an exception from a /* Careful: we should never ever throw an exception from a
destructor. */ destructor. */
try { deleteTmpDir(false); } catch (...) { ignoreExceptionInDestructor(); } try { deleteTmpDir(false); } catch (...) { ignoreException(); }
try { killChild(); } catch (...) { ignoreExceptionInDestructor(); } try { killChild(); } catch (...) { ignoreException(); }
try { stopDaemon(); } catch (...) { ignoreExceptionInDestructor(); } try { stopDaemon(); } catch (...) { ignoreException(); }
} }
@ -122,6 +121,8 @@ LocalStore & LocalDerivationGoal::getLocalStore()
void LocalDerivationGoal::killChild() void LocalDerivationGoal::killChild()
{ {
if (pid) { if (pid) {
worker.childTerminated(this);
/* If we're using a build user, then there is a tricky race /* If we're using a build user, then there is a tricky race
condition: if we kill the build user before the child has condition: if we kill the build user before the child has
done its setuid() to the build user uid, then it won't be done its setuid() to the build user uid, then it won't be
@ -148,18 +149,17 @@ void LocalDerivationGoal::killSandbox(bool getStats)
} }
kj::Promise<Result<Goal::WorkResult>> LocalDerivationGoal::tryLocalBuild() noexcept Goal::WorkResult LocalDerivationGoal::tryLocalBuild(bool inBuildSlot)
try { {
retry:
#if __APPLE__ #if __APPLE__
additionalSandboxProfile = parsedDrv->getStringAttr("__sandboxProfile").value_or(""); additionalSandboxProfile = parsedDrv->getStringAttr("__sandboxProfile").value_or("");
#endif #endif
if (!slotToken.valid()) { if (!inBuildSlot) {
state = &DerivationGoal::tryToBuild;
outputLocks.unlock(); outputLocks.unlock();
if (worker.localBuilds.capacity() > 0) { if (0U != settings.maxBuildJobs) {
slotToken = co_await worker.localBuilds.acquire(); return WaitForSlot{};
co_return co_await tryToBuild();
} }
if (getMachines().empty()) { if (getMachines().empty()) {
throw Error( throw Error(
@ -214,9 +214,7 @@ retry:
if (!actLock) if (!actLock)
actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting, actLock = std::make_unique<Activity>(*logger, lvlWarn, actBuildWaiting,
fmt("waiting for a free build user ID for '%s'", Magenta(worker.store.printStorePath(drvPath)))); fmt("waiting for a free build user ID for '%s'", Magenta(worker.store.printStorePath(drvPath))));
co_await waitForAWhile(); return WaitForAWhile{};
// we can loop very often, and `co_return co_await` always allocates a new frame
goto retry;
} }
} }
@ -245,29 +243,22 @@ retry:
try { try {
/* Okay, we have to build. */ /* Okay, we have to build. */
auto promise = startBuilder(); auto fds = startBuilder();
/* This state will be reached when we get EOF on the child's
log pipe. */
state = &DerivationGoal::buildDone;
started(); started();
auto r = co_await promise; return WaitForWorld{std::move(fds), true};
if (r.has_value()) {
// all good so far
} else if (r.has_error()) {
co_return r.assume_error();
} else {
co_return r.assume_exception();
}
} catch (BuildError & e) { } catch (BuildError & e) {
outputLocks.unlock(); outputLocks.unlock();
buildUser.reset(); buildUser.reset();
auto report = done(BuildResult::InputRejected, {}, std::move(e)); auto report = done(BuildResult::InputRejected, {}, std::move(e));
report.permanentFailure = true; report.permanentFailure = true;
co_return report; return report;
} }
co_return co_await buildDone();
} catch (...) {
co_return result::failure(std::current_exception());
} }
@ -397,9 +388,7 @@ void LocalDerivationGoal::cleanupPostOutputsRegisteredModeNonCheck()
cleanupPostOutputsRegisteredModeCheck(); cleanupPostOutputsRegisteredModeCheck();
} }
// NOTE this one isn't noexcept because it's called from places that expect std::set<int> LocalDerivationGoal::startBuilder()
// exceptions to signal failure to launch. we should change this some time.
kj::Promise<Outcome<void, Goal::WorkResult>> LocalDerivationGoal::startBuilder()
{ {
if ((buildUser && buildUser->getUIDCount() != 1) if ((buildUser && buildUser->getUIDCount() != 1)
#if __linux__ #if __linux__
@ -788,7 +777,7 @@ kj::Promise<Outcome<void, Goal::WorkResult>> LocalDerivationGoal::startBuilder()
msgs.push_back(std::move(msg)); msgs.push_back(std::move(msg));
} }
return handleChildOutput(); return {builderOutPTY.get()};
} }
@ -1250,7 +1239,7 @@ void LocalDerivationGoal::startDaemon()
NotTrusted, daemon::Recursive); NotTrusted, daemon::Recursive);
debug("terminated daemon connection"); debug("terminated daemon connection");
} catch (SysError &) { } catch (SysError &) {
ignoreExceptionExceptInterrupt(); ignoreException();
} }
}); });
@ -1370,20 +1359,13 @@ void LocalDerivationGoal::runChild()
bool setUser = true; bool setUser = true;
/* Make the contents of netrc and the CA certificate bundle /* Make the contents of netrc available to builtin:fetchurl
available to builtin:fetchurl (which may run under a (which may run under a different uid and/or in a sandbox). */
different uid and/or in a sandbox). */
std::string netrcData; std::string netrcData;
std::string caFileData; try {
if (drv->isBuiltin() && drv->builder == "builtin:fetchurl" && !derivationType->isSandboxed()) { if (drv->isBuiltin() && drv->builder == "builtin:fetchurl" && !derivationType->isSandboxed())
try {
netrcData = readFile(settings.netrcFile); netrcData = readFile(settings.netrcFile);
} catch (SysError &) { } } catch (SysError &) { }
try {
caFileData = readFile(settings.caFile);
} catch (SysError &) { }
}
#if __linux__ #if __linux__
if (useChroot) { if (useChroot) {
@ -1818,7 +1800,7 @@ void LocalDerivationGoal::runChild()
e.second = rewriteStrings(e.second, inputRewrites); e.second = rewriteStrings(e.second, inputRewrites);
if (drv->builder == "builtin:fetchurl") if (drv->builder == "builtin:fetchurl")
builtinFetchurl(drv2, netrcData, caFileData); builtinFetchurl(drv2, netrcData);
else if (drv->builder == "builtin:buildenv") else if (drv->builder == "builtin:buildenv")
builtinBuildenv(drv2); builtinBuildenv(drv2);
else if (drv->builder == "builtin:unpack-channel") else if (drv->builder == "builtin:unpack-channel")

View file

@ -182,7 +182,7 @@ struct LocalDerivationGoal : public DerivationGoal
* Create a LocalDerivationGoal without an on-disk .drv file, * Create a LocalDerivationGoal without an on-disk .drv file,
* possibly a platform-specific subclass * possibly a platform-specific subclass
*/ */
static std::unique_ptr<LocalDerivationGoal> makeLocalDerivationGoal( static std::shared_ptr<LocalDerivationGoal> makeLocalDerivationGoal(
const StorePath & drvPath, const StorePath & drvPath,
const OutputsSpec & wantedOutputs, const OutputsSpec & wantedOutputs,
Worker & worker, Worker & worker,
@ -194,7 +194,7 @@ struct LocalDerivationGoal : public DerivationGoal
* Create a LocalDerivationGoal for an on-disk .drv file, * Create a LocalDerivationGoal for an on-disk .drv file,
* possibly a platform-specific subclass * possibly a platform-specific subclass
*/ */
static std::unique_ptr<LocalDerivationGoal> makeLocalDerivationGoal( static std::shared_ptr<LocalDerivationGoal> makeLocalDerivationGoal(
const StorePath & drvPath, const StorePath & drvPath,
const BasicDerivation & drv, const BasicDerivation & drv,
const OutputsSpec & wantedOutputs, const OutputsSpec & wantedOutputs,
@ -213,12 +213,12 @@ struct LocalDerivationGoal : public DerivationGoal
/** /**
* The additional states. * The additional states.
*/ */
kj::Promise<Result<WorkResult>> tryLocalBuild() noexcept override; WorkResult tryLocalBuild(bool inBuildSlot) override;
/** /**
* Start building a derivation. * Start building a derivation.
*/ */
kj::Promise<Outcome<void, WorkResult>> startBuilder(); std::set<int> startBuilder();
/** /**
* Fill in the environment for the builder. * Fill in the environment for the builder.

View file

@ -3,8 +3,6 @@
#include "nar-info.hh" #include "nar-info.hh"
#include "signals.hh" #include "signals.hh"
#include "finally.hh" #include "finally.hh"
#include <kj/array.h>
#include <kj/vector.h>
namespace nix { namespace nix {
@ -20,6 +18,7 @@ PathSubstitutionGoal::PathSubstitutionGoal(
, repair(repair) , repair(repair)
, ca(ca) , ca(ca)
{ {
state = &PathSubstitutionGoal::init;
name = fmt("substitution of '%s'", worker.store.printStorePath(this->storePath)); name = fmt("substitution of '%s'", worker.store.printStorePath(this->storePath));
trace("created"); trace("created");
maintainExpectedSubstitutions = worker.expectedSubstitutions.addTemporarily(1); maintainExpectedSubstitutions = worker.expectedSubstitutions.addTemporarily(1);
@ -32,29 +31,35 @@ PathSubstitutionGoal::~PathSubstitutionGoal()
} }
Goal::WorkResult PathSubstitutionGoal::done( Goal::Finished PathSubstitutionGoal::done(
ExitCode result, ExitCode result,
BuildResult::Status status, BuildResult::Status status,
std::optional<std::string> errorMsg) std::optional<std::string> errorMsg)
{ {
BuildResult buildResult{.status = status}; buildResult.status = status;
if (errorMsg) { if (errorMsg) {
debug(*errorMsg); debug(*errorMsg);
buildResult.errorMsg = *errorMsg; buildResult.errorMsg = *errorMsg;
} }
return WorkResult{result, std::move(buildResult)}; return Finished{result, std::move(buildResult)};
} }
kj::Promise<Result<Goal::WorkResult>> PathSubstitutionGoal::workImpl() noexcept Goal::WorkResult PathSubstitutionGoal::work(bool inBuildSlot)
try { {
return (this->*state)(inBuildSlot);
}
Goal::WorkResult PathSubstitutionGoal::init(bool inBuildSlot)
{
trace("init"); trace("init");
worker.store.addTempRoot(storePath); worker.store.addTempRoot(storePath);
/* If the path already exists we're done. */ /* If the path already exists we're done. */
if (!repair && worker.store.isValidPath(storePath)) { if (!repair && worker.store.isValidPath(storePath)) {
return {done(ecSuccess, BuildResult::AlreadyValid)}; return done(ecSuccess, BuildResult::AlreadyValid);
} }
if (settings.readOnlyMode) if (settings.readOnlyMode)
@ -62,14 +67,12 @@ try {
subs = settings.useSubstitutes ? getDefaultSubstituters() : std::list<ref<Store>>(); subs = settings.useSubstitutes ? getDefaultSubstituters() : std::list<ref<Store>>();
return tryNext(); return tryNext(inBuildSlot);
} catch (...) {
return {std::current_exception()};
} }
kj::Promise<Result<Goal::WorkResult>> PathSubstitutionGoal::tryNext() noexcept Goal::WorkResult PathSubstitutionGoal::tryNext(bool inBuildSlot)
try { {
trace("trying next substituter"); trace("trying next substituter");
cleanup(); cleanup();
@ -84,7 +87,7 @@ try {
/* Hack: don't indicate failure if there were no substituters. /* Hack: don't indicate failure if there were no substituters.
In that case the calling derivation should just do a In that case the calling derivation should just do a
build. */ build. */
co_return done( return done(
substituterFailed ? ecFailed : ecNoSubstituters, substituterFailed ? ecFailed : ecNoSubstituters,
BuildResult::NoSubstituters, BuildResult::NoSubstituters,
fmt("path '%s' is required, but there is no substituter that can build it", worker.store.printStorePath(storePath))); fmt("path '%s' is required, but there is no substituter that can build it", worker.store.printStorePath(storePath)));
@ -100,28 +103,26 @@ try {
if (sub->storeDir == worker.store.storeDir) if (sub->storeDir == worker.store.storeDir)
assert(subPath == storePath); assert(subPath == storePath);
} else if (sub->storeDir != worker.store.storeDir) { } else if (sub->storeDir != worker.store.storeDir) {
co_return co_await tryNext(); return tryNext(inBuildSlot);
} }
do { try {
try { // FIXME: make async
// FIXME: make async info = sub->queryPathInfo(subPath ? *subPath : storePath);
info = sub->queryPathInfo(subPath ? *subPath : storePath); } catch (InvalidPath &) {
break; return tryNext(inBuildSlot);
} catch (InvalidPath &) { } catch (SubstituterDisabled &) {
} catch (SubstituterDisabled &) { if (settings.tryFallback) {
if (!settings.tryFallback) { return tryNext(inBuildSlot);
throw;
}
} catch (Error & e) {
if (settings.tryFallback) {
logError(e.info());
} else {
throw;
}
} }
co_return co_await tryNext(); throw;
} while (false); } catch (Error & e) {
if (settings.tryFallback) {
logError(e.info());
return tryNext(inBuildSlot);
}
throw;
}
if (info->path != storePath) { if (info->path != storePath) {
if (info->isContentAddressed(*sub) && info->references.empty()) { if (info->isContentAddressed(*sub) && info->references.empty()) {
@ -131,7 +132,7 @@ try {
} else { } else {
printError("asked '%s' for '%s' but got '%s'", printError("asked '%s' for '%s' but got '%s'",
sub->getUri(), worker.store.printStorePath(storePath), sub->printStorePath(info->path)); sub->getUri(), worker.store.printStorePath(storePath), sub->printStorePath(info->path));
co_return co_await tryNext(); return tryNext(inBuildSlot);
} }
} }
@ -152,67 +153,65 @@ try {
{ {
warn("ignoring substitute for '%s' from '%s', as it's not signed by any of the keys in 'trusted-public-keys'", warn("ignoring substitute for '%s' from '%s', as it's not signed by any of the keys in 'trusted-public-keys'",
worker.store.printStorePath(storePath), sub->getUri()); worker.store.printStorePath(storePath), sub->getUri());
co_return co_await tryNext(); return tryNext(inBuildSlot);
} }
/* To maintain the closure invariant, we first have to realise the /* To maintain the closure invariant, we first have to realise the
paths referenced by this one. */ paths referenced by this one. */
kj::Vector<std::pair<GoalPtr, kj::Promise<Result<WorkResult>>>> dependencies; WaitForGoals result;
for (auto & i : info->references) for (auto & i : info->references)
if (i != storePath) /* ignore self-references */ if (i != storePath) /* ignore self-references */
dependencies.add(worker.goalFactory().makePathSubstitutionGoal(i)); result.goals.insert(worker.goalFactory().makePathSubstitutionGoal(i));
if (!dependencies.empty()) {/* to prevent hang (no wake-up event) */ if (result.goals.empty()) {/* to prevent hang (no wake-up event) */
(co_await waitForGoals(dependencies.releaseAsArray())).value(); return referencesValid(inBuildSlot);
} else {
state = &PathSubstitutionGoal::referencesValid;
return result;
} }
co_return co_await referencesValid();
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> PathSubstitutionGoal::referencesValid() noexcept Goal::WorkResult PathSubstitutionGoal::referencesValid(bool inBuildSlot)
try { {
trace("all references realised"); trace("all references realised");
if (nrFailed > 0) { if (nrFailed > 0) {
return {done( return done(
nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed, nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed,
BuildResult::DependencyFailed, BuildResult::DependencyFailed,
fmt("some references of path '%s' could not be realised", worker.store.printStorePath(storePath)))}; fmt("some references of path '%s' could not be realised", worker.store.printStorePath(storePath)));
} }
for (auto & i : info->references) for (auto & i : info->references)
if (i != storePath) /* ignore self-references */ if (i != storePath) /* ignore self-references */
assert(worker.store.isValidPath(i)); assert(worker.store.isValidPath(i));
return tryToRun(); state = &PathSubstitutionGoal::tryToRun;
} catch (...) { return tryToRun(inBuildSlot);
return {std::current_exception()};
} }
kj::Promise<Result<Goal::WorkResult>> PathSubstitutionGoal::tryToRun() noexcept Goal::WorkResult PathSubstitutionGoal::tryToRun(bool inBuildSlot)
try { {
trace("trying to run"); trace("trying to run");
if (!slotToken.valid()) { if (!inBuildSlot) {
slotToken = co_await worker.substitutions.acquire(); return WaitForSlot{};
} }
maintainRunningSubstitutions = worker.runningSubstitutions.addTemporarily(1); maintainRunningSubstitutions = worker.runningSubstitutions.addTemporarily(1);
auto pipe = kj::newPromiseAndCrossThreadFulfiller<void>(); outPipe.create();
outPipe = kj::mv(pipe.fulfiller);
thr = std::async(std::launch::async, [this]() { thr = std::async(std::launch::async, [this]() {
/* Wake up the worker loop when we're done. */
Finally updateStats([this]() { outPipe->fulfill(); });
auto & fetchPath = subPath ? *subPath : storePath; auto & fetchPath = subPath ? *subPath : storePath;
try { try {
ReceiveInterrupts receiveInterrupts; ReceiveInterrupts receiveInterrupts;
/* Wake up the worker loop when we're done. */
Finally updateStats([this]() { outPipe.writeSide.close(); });
Activity act(*logger, actSubstitute, Logger::Fields{worker.store.printStorePath(storePath), sub->getUri()}); Activity act(*logger, actSubstitute, Logger::Fields{worker.store.printStorePath(storePath), sub->getUri()});
PushActivity pact(act.id); PushActivity pact(act.id);
@ -228,39 +227,37 @@ try {
} }
}); });
co_await pipe.promise; state = &PathSubstitutionGoal::finished;
co_return co_await finished(); return WaitForWorld{{outPipe.readSide.get()}, true};
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Goal::WorkResult>> PathSubstitutionGoal::finished() noexcept Goal::WorkResult PathSubstitutionGoal::finished(bool inBuildSlot)
try { {
trace("substitute finished"); trace("substitute finished");
do { worker.childTerminated(this);
try {
slotToken = {};
thr.get();
break;
} catch (std::exception & e) {
printError(e.what());
/* Cause the parent build to fail unless --fallback is given, try {
or the substitute has disappeared. The latter case behaves thr.get();
the same as the substitute never having existed in the } catch (std::exception & e) {
first place. */ printError(e.what());
try {
throw; /* Cause the parent build to fail unless --fallback is given,
} catch (SubstituteGone &) { or the substitute has disappeared. The latter case behaves
} catch (...) { the same as the substitute never having existed in the
substituterFailed = true; first place. */
} try {
throw;
} catch (SubstituteGone &) {
} catch (...) {
substituterFailed = true;
} }
/* Try the next substitute. */ /* Try the next substitute. */
co_return co_await tryNext(); state = &PathSubstitutionGoal::tryNext;
} while (false); return tryNext(inBuildSlot);
}
worker.markContentsGood(storePath); worker.markContentsGood(storePath);
@ -277,9 +274,13 @@ try {
worker.doneNarSize += maintainExpectedNar.delta(); worker.doneNarSize += maintainExpectedNar.delta();
maintainExpectedNar.reset(); maintainExpectedNar.reset();
co_return done(ecSuccess, BuildResult::Substituted); return done(ecSuccess, BuildResult::Substituted);
} catch (...) { }
co_return result::failure(std::current_exception());
Goal::WorkResult PathSubstitutionGoal::handleChildOutput(int fd, std::string_view data)
{
return StillAlive{};
} }
@ -289,9 +290,12 @@ void PathSubstitutionGoal::cleanup()
if (thr.valid()) { if (thr.valid()) {
// FIXME: signal worker thread to quit. // FIXME: signal worker thread to quit.
thr.get(); thr.get();
worker.childTerminated(this);
} }
outPipe.close();
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -46,7 +46,7 @@ struct PathSubstitutionGoal : public Goal
/** /**
* Pipe for the substituter's standard output. * Pipe for the substituter's standard output.
*/ */
kj::Own<kj::CrossThreadPromiseFulfiller<void>> outPipe; Pipe outPipe;
/** /**
* The substituter thread. * The substituter thread.
@ -67,12 +67,15 @@ struct PathSubstitutionGoal : public Goal
NotifyingCounter<uint64_t>::Bump maintainExpectedSubstitutions, NotifyingCounter<uint64_t>::Bump maintainExpectedSubstitutions,
maintainRunningSubstitutions, maintainExpectedNar, maintainExpectedDownload; maintainRunningSubstitutions, maintainExpectedNar, maintainExpectedDownload;
typedef WorkResult (PathSubstitutionGoal::*GoalState)(bool inBuildSlot);
GoalState state;
/** /**
* Content address for recomputing store path * Content address for recomputing store path
*/ */
std::optional<ContentAddress> ca; std::optional<ContentAddress> ca;
WorkResult done( Finished done(
ExitCode result, ExitCode result,
BuildResult::Status status, BuildResult::Status status,
std::optional<std::string> errorMsg = {}); std::optional<std::string> errorMsg = {});
@ -87,15 +90,32 @@ public:
); );
~PathSubstitutionGoal(); ~PathSubstitutionGoal();
kj::Promise<Result<WorkResult>> workImpl() noexcept override; Finished timedOut(Error && ex) override { abort(); };
/**
* We prepend "a$" to the key name to ensure substitution goals
* happen before derivation goals.
*/
std::string key() override
{
return "a$" + std::string(storePath.name()) + "$" + worker.store.printStorePath(storePath);
}
WorkResult work(bool inBuildSlot) override;
/** /**
* The states. * The states.
*/ */
kj::Promise<Result<WorkResult>> tryNext() noexcept; WorkResult init(bool inBuildSlot);
kj::Promise<Result<WorkResult>> referencesValid() noexcept; WorkResult tryNext(bool inBuildSlot);
kj::Promise<Result<WorkResult>> tryToRun() noexcept; WorkResult referencesValid(bool inBuildSlot);
kj::Promise<Result<WorkResult>> finished() noexcept; WorkResult tryToRun(bool inBuildSlot);
WorkResult finished(bool inBuildSlot);
/**
* Callback used by the worker to write to the log.
*/
WorkResult handleChildOutput(int fd, std::string_view data) override;
/* Called by destructor, can't be overridden */ /* Called by destructor, can't be overridden */
void cleanup() override final; void cleanup() override final;

View file

@ -1,4 +1,3 @@
#include "async-collect.hh"
#include "charptr-cast.hh" #include "charptr-cast.hh"
#include "worker.hh" #include "worker.hh"
#include "finally.hh" #include "finally.hh"
@ -7,36 +6,22 @@
#include "local-derivation-goal.hh" #include "local-derivation-goal.hh"
#include "signals.hh" #include "signals.hh"
#include "hook-instance.hh" // IWYU pragma: keep #include "hook-instance.hh" // IWYU pragma: keep
#include <boost/outcome/try.hpp>
#include <kj/vector.h> #include <poll.h>
namespace nix { namespace nix {
namespace { Worker::Worker(Store & store, Store & evalStore)
struct ErrorHandler : kj::TaskSet::ErrorHandler
{
void taskFailed(kj::Exception && e) override
{
printError("unexpected async failure in Worker: %s", kj::str(e).cStr());
abort();
}
} errorHandler;
}
Worker::Worker(Store & store, Store & evalStore, kj::AsyncIoContext & aio)
: act(*logger, actRealise) : act(*logger, actRealise)
, actDerivations(*logger, actBuilds) , actDerivations(*logger, actBuilds)
, actSubstitutions(*logger, actCopyPaths) , actSubstitutions(*logger, actCopyPaths)
, store(store) , store(store)
, evalStore(evalStore) , evalStore(evalStore)
, aio(aio)
/* Make sure that we are always allowed to run at least one substitution.
This prevents infinite waiting. */
, substitutions(std::max<unsigned>(1, settings.maxSubstitutionJobs))
, localBuilds(settings.maxBuildJobs)
, children(errorHandler)
{ {
/* Debugging: prevent recursive workers. */ /* Debugging: prevent recursive workers. */
nrLocalBuilds = 0;
nrSubstitutions = 0;
lastWokenUp = steady_time_point::min();
} }
@ -46,11 +31,7 @@ Worker::~Worker()
goals that refer to this worker should be gone. (Otherwise we goals that refer to this worker should be gone. (Otherwise we
are in trouble, since goals may call childTerminated() etc. in are in trouble, since goals may call childTerminated() etc. in
their destructors). */ their destructors). */
children.clear(); topGoals.clear();
derivationGoals.clear();
drvOutputSubstitutionGoals.clear();
substitutionGoals.clear();
assert(expectedSubstitutions == 0); assert(expectedSubstitutions == 0);
assert(expectedDownloadSize == 0); assert(expectedDownloadSize == 0);
@ -58,158 +39,292 @@ Worker::~Worker()
} }
template<typename ID, std::derived_from<Goal> G> std::shared_ptr<DerivationGoal> Worker::makeDerivationGoalCommon(
std::pair<std::shared_ptr<G>, kj::Promise<Result<Goal::WorkResult>>> Worker::makeGoalCommon(
std::map<ID, CachedGoal<G>> & map,
const ID & key,
InvocableR<std::unique_ptr<G>> auto create,
InvocableR<bool, G &> auto modify
)
{
auto [it, _inserted] = map.try_emplace(key);
// try twice to create the goal. we can only loop if we hit the continue,
// and then we only want to recreate the goal *once*. concurrent accesses
// to the worker are not sound, we want to catch them if at all possible.
for ([[maybe_unused]] auto _attempt : {1, 2}) {
auto & cachedGoal = it->second;
auto & goal = cachedGoal.goal;
if (!goal) {
goal = create();
// do not start working immediately. if we are not yet running we
// may create dependencies as though they were toplevel goals, in
// which case the dependencies will not report build errors. when
// we are running we may be called for this same goal more times,
// and then we want to modify rather than recreate when possible.
auto removeWhenDone = [goal, &map, it] {
// c++ lambda coroutine capture semantics are *so* fucked up.
return [](auto goal, auto & map, auto it) -> kj::Promise<Result<Goal::WorkResult>> {
auto result = co_await goal->work();
// a concurrent call to makeGoalCommon may have reset our
// cached goal and replaced it with a new instance. don't
// remove the goal in this case, otherwise we will crash.
if (goal == it->second.goal) {
map.erase(it);
}
co_return result;
}(goal, map, it);
};
cachedGoal.promise = kj::evalLater(std::move(removeWhenDone)).fork();
children.add(cachedGoal.promise.addBranch().then([this](auto _result) {
if (_result.has_value()) {
auto & result = _result.value();
permanentFailure |= result.permanentFailure;
timedOut |= result.timedOut;
hashMismatch |= result.hashMismatch;
checkMismatch |= result.checkMismatch;
}
}));
} else {
if (!modify(*goal)) {
cachedGoal = {};
continue;
}
}
return {goal, cachedGoal.promise.addBranch()};
}
assert(false && "could not make a goal. possible concurrent worker access");
}
std::pair<std::shared_ptr<DerivationGoal>, kj::Promise<Result<Goal::WorkResult>>> Worker::makeDerivationGoal(
const StorePath & drvPath, const OutputsSpec & wantedOutputs, BuildMode buildMode
)
{
return makeGoalCommon(
derivationGoals,
drvPath,
[&]() -> std::unique_ptr<DerivationGoal> {
return !dynamic_cast<LocalStore *>(&store)
? std::make_unique<DerivationGoal>(
drvPath, wantedOutputs, *this, running, buildMode
)
: LocalDerivationGoal::makeLocalDerivationGoal(
drvPath, wantedOutputs, *this, running, buildMode
);
},
[&](DerivationGoal & g) { return g.addWantedOutputs(wantedOutputs); }
);
}
std::pair<std::shared_ptr<DerivationGoal>, kj::Promise<Result<Goal::WorkResult>>> Worker::makeBasicDerivationGoal(
const StorePath & drvPath, const StorePath & drvPath,
const BasicDerivation & drv,
const OutputsSpec & wantedOutputs, const OutputsSpec & wantedOutputs,
BuildMode buildMode std::function<std::shared_ptr<DerivationGoal>()> mkDrvGoal)
)
{ {
return makeGoalCommon( std::weak_ptr<DerivationGoal> & goal_weak = derivationGoals[drvPath];
derivationGoals, std::shared_ptr<DerivationGoal> goal = goal_weak.lock();
if (!goal) {
goal = mkDrvGoal();
goal_weak = goal;
wakeUp(goal);
} else {
goal->addWantedOutputs(wantedOutputs);
}
return goal;
}
std::shared_ptr<DerivationGoal> Worker::makeDerivationGoal(const StorePath & drvPath,
const OutputsSpec & wantedOutputs, BuildMode buildMode)
{
return makeDerivationGoalCommon(
drvPath, drvPath,
[&]() -> std::unique_ptr<DerivationGoal> { wantedOutputs,
[&]() -> std::shared_ptr<DerivationGoal> {
return !dynamic_cast<LocalStore *>(&store) return !dynamic_cast<LocalStore *>(&store)
? std::make_unique<DerivationGoal>( ? std::make_shared<DerivationGoal>(
drvPath, wantedOutputs, *this, running, buildMode
)
: LocalDerivationGoal::makeLocalDerivationGoal(
drvPath, wantedOutputs, *this, running, buildMode
);
}
);
}
std::shared_ptr<DerivationGoal> Worker::makeBasicDerivationGoal(const StorePath & drvPath,
const BasicDerivation & drv, const OutputsSpec & wantedOutputs, BuildMode buildMode)
{
return makeDerivationGoalCommon(
drvPath,
wantedOutputs,
[&]() -> std::shared_ptr<DerivationGoal> {
return !dynamic_cast<LocalStore *>(&store)
? std::make_shared<DerivationGoal>(
drvPath, drv, wantedOutputs, *this, running, buildMode drvPath, drv, wantedOutputs, *this, running, buildMode
) )
: LocalDerivationGoal::makeLocalDerivationGoal( : LocalDerivationGoal::makeLocalDerivationGoal(
drvPath, drv, wantedOutputs, *this, running, buildMode drvPath, drv, wantedOutputs, *this, running, buildMode
); );
}, }
[&](DerivationGoal & g) { return g.addWantedOutputs(wantedOutputs); }
); );
} }
std::pair<std::shared_ptr<PathSubstitutionGoal>, kj::Promise<Result<Goal::WorkResult>>> std::shared_ptr<PathSubstitutionGoal> Worker::makePathSubstitutionGoal(const StorePath & path, RepairFlag repair, std::optional<ContentAddress> ca)
Worker::makePathSubstitutionGoal(
const StorePath & path, RepairFlag repair, std::optional<ContentAddress> ca
)
{ {
return makeGoalCommon( std::weak_ptr<PathSubstitutionGoal> & goal_weak = substitutionGoals[path];
substitutionGoals, auto goal = goal_weak.lock(); // FIXME
path, if (!goal) {
[&] { return std::make_unique<PathSubstitutionGoal>(path, *this, running, repair, ca); }, goal = std::make_shared<PathSubstitutionGoal>(path, *this, running, repair, ca);
[&](auto &) { return true; } goal_weak = goal;
); wakeUp(goal);
}
return goal;
} }
std::pair<std::shared_ptr<DrvOutputSubstitutionGoal>, kj::Promise<Result<Goal::WorkResult>>> std::shared_ptr<DrvOutputSubstitutionGoal> Worker::makeDrvOutputSubstitutionGoal(const DrvOutput& id, RepairFlag repair, std::optional<ContentAddress> ca)
Worker::makeDrvOutputSubstitutionGoal(
const DrvOutput & id, RepairFlag repair, std::optional<ContentAddress> ca
)
{ {
return makeGoalCommon( std::weak_ptr<DrvOutputSubstitutionGoal> & goal_weak = drvOutputSubstitutionGoals[id];
drvOutputSubstitutionGoals, auto goal = goal_weak.lock(); // FIXME
id, if (!goal) {
[&] { return std::make_unique<DrvOutputSubstitutionGoal>(id, *this, running, repair, ca); }, goal = std::make_shared<DrvOutputSubstitutionGoal>(id, *this, running, repair, ca);
[&](auto &) { return true; } goal_weak = goal;
); wakeUp(goal);
}
return goal;
} }
std::pair<GoalPtr, kj::Promise<Result<Goal::WorkResult>>> Worker::makeGoal(const DerivedPath & req, BuildMode buildMode) GoalPtr Worker::makeGoal(const DerivedPath & req, BuildMode buildMode)
{ {
return std::visit(overloaded { return std::visit(overloaded {
[&](const DerivedPath::Built & bfd) -> std::pair<GoalPtr, kj::Promise<Result<Goal::WorkResult>>> { [&](const DerivedPath::Built & bfd) -> GoalPtr {
if (auto bop = std::get_if<DerivedPath::Opaque>(&*bfd.drvPath)) if (auto bop = std::get_if<DerivedPath::Opaque>(&*bfd.drvPath))
return makeDerivationGoal(bop->path, bfd.outputs, buildMode); return makeDerivationGoal(bop->path, bfd.outputs, buildMode);
else else
throw UnimplementedError("Building dynamic derivations in one shot is not yet implemented."); throw UnimplementedError("Building dynamic derivations in one shot is not yet implemented.");
}, },
[&](const DerivedPath::Opaque & bo) -> std::pair<GoalPtr, kj::Promise<Result<Goal::WorkResult>>> { [&](const DerivedPath::Opaque & bo) -> GoalPtr {
return makePathSubstitutionGoal(bo.path, buildMode == bmRepair ? Repair : NoRepair); return makePathSubstitutionGoal(bo.path, buildMode == bmRepair ? Repair : NoRepair);
}, },
}, req.raw()); }, req.raw());
} }
kj::Promise<Result<Worker::Results>> Worker::updateStatistics()
try {
while (true) {
statisticsUpdateInhibitor = co_await statisticsUpdateSignal.acquire();
// only update progress info while running. this notably excludes updating template<typename K, typename G>
// progress info while destroying, which causes the progress bar to assert static void removeGoal(std::shared_ptr<G> goal, std::map<K, std::weak_ptr<G>> & goalMap)
{
/* !!! inefficient */
for (auto i = goalMap.begin();
i != goalMap.end(); )
if (i->second.lock() == goal) {
auto j = i; ++j;
goalMap.erase(i);
i = j;
}
else ++i;
}
void Worker::goalFinished(GoalPtr goal, Goal::Finished & f)
{
goal->trace("done");
assert(!goal->exitCode.has_value());
goal->exitCode = f.exitCode;
goal->ex = f.ex;
permanentFailure |= f.permanentFailure;
timedOut |= f.timedOut;
hashMismatch |= f.hashMismatch;
checkMismatch |= f.checkMismatch;
for (auto & i : goal->waiters) {
if (GoalPtr waiting = i.lock()) {
assert(waiting->waitees.count(goal));
waiting->waitees.erase(goal);
waiting->trace(fmt("waitee '%s' done; %d left", goal->name, waiting->waitees.size()));
if (f.exitCode != Goal::ecSuccess) ++waiting->nrFailed;
if (f.exitCode == Goal::ecNoSubstituters) ++waiting->nrNoSubstituters;
if (f.exitCode == Goal::ecIncompleteClosure) ++waiting->nrIncompleteClosure;
if (waiting->waitees.empty() || (f.exitCode == Goal::ecFailed && !settings.keepGoing)) {
/* If we failed and keepGoing is not set, we remove all
remaining waitees. */
for (auto & i : waiting->waitees) {
i->waiters.extract(waiting);
}
waiting->waitees.clear();
wakeUp(waiting);
}
waiting->waiteeDone(goal);
}
}
goal->waiters.clear();
removeGoal(goal);
goal->cleanup();
}
void Worker::handleWorkResult(GoalPtr goal, Goal::WorkResult how)
{
std::visit(
overloaded{
[&](Goal::StillAlive) {},
[&](Goal::WaitForSlot) { waitForBuildSlot(goal); },
[&](Goal::WaitForAWhile) { waitForAWhile(goal); },
[&](Goal::ContinueImmediately) { wakeUp(goal); },
[&](Goal::WaitForGoals & w) {
for (auto & dep : w.goals) {
goal->waitees.insert(dep);
dep->waiters.insert(goal);
}
},
[&](Goal::WaitForWorld & w) { childStarted(goal, w.fds, w.inBuildSlot); },
[&](Goal::Finished & f) { goalFinished(goal, f); },
},
how
);
}
void Worker::removeGoal(GoalPtr goal)
{
if (auto drvGoal = std::dynamic_pointer_cast<DerivationGoal>(goal))
nix::removeGoal(drvGoal, derivationGoals);
else if (auto subGoal = std::dynamic_pointer_cast<PathSubstitutionGoal>(goal))
nix::removeGoal(subGoal, substitutionGoals);
else if (auto subGoal = std::dynamic_pointer_cast<DrvOutputSubstitutionGoal>(goal))
nix::removeGoal(subGoal, drvOutputSubstitutionGoals);
else
assert(false);
if (topGoals.find(goal) != topGoals.end()) {
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)
topGoals.clear();
}
}
void Worker::wakeUp(GoalPtr goal)
{
goal->trace("woken up");
awake.insert(goal);
}
void Worker::childStarted(GoalPtr goal, const std::set<int> & fds,
bool inBuildSlot)
{
Child child;
child.goal = goal;
child.goal2 = goal.get();
child.fds = fds;
child.timeStarted = child.lastOutput = steady_time_point::clock::now();
child.inBuildSlot = inBuildSlot;
children.emplace_back(child);
if (inBuildSlot) {
switch (goal->jobCategory()) {
case JobCategory::Substitution:
nrSubstitutions++;
break;
case JobCategory::Build:
nrLocalBuilds++;
break;
default:
abort();
}
}
}
void Worker::childTerminated(Goal * goal)
{
auto i = std::find_if(children.begin(), children.end(),
[&](const Child & child) { return child.goal2 == goal; });
if (i == children.end()) return;
if (i->inBuildSlot) {
switch (goal->jobCategory()) {
case JobCategory::Substitution:
assert(nrSubstitutions > 0);
nrSubstitutions--;
break;
case JobCategory::Build:
assert(nrLocalBuilds > 0);
nrLocalBuilds--;
break;
default:
abort();
}
}
children.erase(i);
/* Wake up goals waiting for a build slot. */
for (auto & j : wantingToBuild) {
GoalPtr goal = j.lock();
if (goal) wakeUp(goal);
}
wantingToBuild.clear();
}
void Worker::waitForBuildSlot(GoalPtr goal)
{
goal->trace("wait for build slot");
bool isSubstitutionGoal = goal->jobCategory() == JobCategory::Substitution;
if ((!isSubstitutionGoal && nrLocalBuilds < settings.maxBuildJobs) ||
(isSubstitutionGoal && nrSubstitutions < settings.maxSubstitutionJobs))
wakeUp(goal); /* we can do it right away */
else
wantingToBuild.insert(goal);
}
void Worker::waitForAWhile(GoalPtr goal)
{
debug("wait for a while");
waitingForAWhile.insert(goal);
}
void Worker::updateStatistics()
{
// only update progress info while running. this notably excludes updating
// progress info while destroying, which causes the progress bar to assert
if (running && statisticsOutdated) {
actDerivations.progress( actDerivations.progress(
doneBuilds, expectedBuilds + doneBuilds, runningBuilds, failedBuilds doneBuilds, expectedBuilds + doneBuilds, runningBuilds, failedBuilds
); );
@ -222,82 +337,221 @@ try {
act.setExpected(actFileTransfer, expectedDownloadSize + doneDownloadSize); act.setExpected(actFileTransfer, expectedDownloadSize + doneDownloadSize);
act.setExpected(actCopyPath, expectedNarSize + doneNarSize); act.setExpected(actCopyPath, expectedNarSize + doneNarSize);
// limit to 50fps. that should be more than good enough for anything we do statisticsOutdated = false;
co_await aio.provider->getTimer().afterDelay(20 * kj::MILLISECONDS);
} }
} catch (...) {
co_return result::failure(std::current_exception());
} }
Worker::Results Worker::run(std::function<Targets (GoalFactory &)> req) Goals Worker::run(std::function<Goals (GoalFactory &)> req)
{ {
auto topGoals = req(goalFactory()); auto _topGoals = req(goalFactory());
assert(!running); assert(!running);
running = true; running = true;
Finally const _stop([&] { running = false; }); Finally const _stop([&] { running = false; });
auto onInterrupt = kj::newPromiseAndCrossThreadFulfiller<Result<Results>>(); updateStatistics();
auto interruptCallback = createInterruptCallback([&] {
return result::failure(std::make_exception_ptr(makeInterrupted()));
});
auto promise = runImpl(std::move(topGoals)) topGoals = _topGoals;
.exclusiveJoin(updateStatistics())
.exclusiveJoin(std::move(onInterrupt.promise));
// TODO GC interface?
if (auto localStore = dynamic_cast<LocalStore *>(&store); localStore && settings.minFree != 0) {
// Periodically wake up to see if we need to run the garbage collector.
promise = promise.exclusiveJoin(boopGC(*localStore));
}
return promise.wait(aio.waitScope).value();
}
kj::Promise<Result<Worker::Results>> Worker::runImpl(Targets topGoals)
try {
debug("entered goal loop"); debug("entered goal loop");
kj::Vector<Targets::value_type> promises(topGoals.size()); while (1) {
for (auto & gp : topGoals) {
promises.add(std::move(gp));
}
Results results; checkInterrupt();
auto collect = AsyncCollect(promises.releaseAsArray()); // TODO GC interface?
while (auto done = co_await collect.next()) { if (auto localStore = dynamic_cast<LocalStore *>(&store))
// propagate goal exceptions outward localStore->autoGC(false);
BOOST_OUTCOME_CO_TRY(auto result, done->second);
results.emplace(done->first, result);
/* If a top-level goal failed, then kill all other goals /* Call every wake goal (in the ordering established by
(unless keepGoing was set). */ CompareGoalPtrs). */
if (result.exitCode == Goal::ecFailed && !settings.keepGoing) { while (!awake.empty() && !topGoals.empty()) {
children.clear(); Goals awake2;
break; for (auto & i : awake) {
GoalPtr goal = i.lock();
if (goal) awake2.insert(goal);
}
awake.clear();
for (auto & goal : awake2) {
checkInterrupt();
/* Make sure that we are always allowed to run at least one substitution.
This prevents infinite waiting. */
const bool inSlot = goal->jobCategory() == JobCategory::Substitution
? nrSubstitutions < std::max(1U, (unsigned int) settings.maxSubstitutionJobs)
: nrLocalBuilds < settings.maxBuildJobs;
handleWorkResult(goal, goal->work(inSlot));
updateStatistics();
if (topGoals.empty()) break; // stuff may have been cancelled
}
}
if (topGoals.empty()) break;
/* Wait for input. */
if (!children.empty() || !waitingForAWhile.empty())
waitForInput();
else {
assert(!awake.empty());
} }
} }
/* If --keep-going is not set, it's possible that the main goal /* If --keep-going is not set, it's possible that the main goal
exited while some of its subgoals were still active. But if exited while some of its subgoals were still active. But if
--keep-going *is* set, then they must all be finished now. */ --keep-going *is* set, then they must all be finished now. */
assert(!settings.keepGoing || children.isEmpty()); assert(!settings.keepGoing || awake.empty());
assert(!settings.keepGoing || wantingToBuild.empty());
assert(!settings.keepGoing || children.empty());
co_return std::move(results); return _topGoals;
} catch (...) {
co_return result::failure(std::current_exception());
} }
kj::Promise<Result<Worker::Results>> Worker::boopGC(LocalStore & localStore) void Worker::waitForInput()
try { {
while (true) { printMsg(lvlVomit, "waiting for children");
co_await aio.provider->getTimer().afterDelay(10 * kj::SECONDS);
localStore.autoGC(false); /* Process output from the file descriptors attached to the
children, namely log output and output path creation commands.
We also use this to detect child termination: if we get EOF on
the logger pipe of a build, we assume that the builder has
terminated. */
bool useTimeout = false;
long timeout = 0;
auto before = steady_time_point::clock::now();
/* If we're monitoring for silence on stdout/stderr, or if there
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)
// Periodicallty wake up to see if we need to run the garbage collector.
nearest = before + std::chrono::seconds(10);
for (auto & i : children) {
if (auto goal = i.goal.lock()) {
if (!goal->respectsTimeouts()) 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 (nearest != steady_time_point::max()) {
timeout = std::max(1L, (long) std::chrono::duration_cast<std::chrono::seconds>(nearest - before).count());
useTimeout = true;
}
/* If we are polling goals that are waiting for a lock, then wake
up after a few seconds at most. */
if (!waitingForAWhile.empty()) {
useTimeout = true;
if (lastWokenUp == steady_time_point::min() || lastWokenUp > before) lastWokenUp = before;
timeout = std::max(1L,
(long) std::chrono::duration_cast<std::chrono::seconds>(
lastWokenUp + std::chrono::seconds(settings.pollInterval) - before).count());
} else lastWokenUp = steady_time_point::min();
if (useTimeout)
vomit("sleeping %d seconds", timeout);
/* Use select() to wait for the input side of any logger pipe to
become `available'. Note that `available' (i.e., non-blocking)
includes EOF. */
std::vector<struct pollfd> pollStatus;
std::map<int, size_t> fdToPollStatus;
for (auto & i : children) {
for (auto & j : i.fds) {
pollStatus.push_back((struct pollfd) { .fd = j, .events = POLLIN });
fdToPollStatus[j] = pollStatus.size() - 1;
}
}
if (poll(pollStatus.data(), pollStatus.size(),
useTimeout ? timeout * 1000 : -1) == -1) {
if (errno == EINTR) return;
throw SysError("waiting for input");
}
auto after = steady_time_point::clock::now();
/* Process all available file descriptors. FIXME: this is
O(children * fds). */
decltype(children)::iterator i;
for (auto j = children.begin(); j != children.end(); j = i) {
i = std::next(j);
checkInterrupt();
GoalPtr goal = j->goal.lock();
assert(goal);
if (!goal->exitCode.has_value() &&
0 != settings.maxSilentTime &&
goal->respectsTimeouts() &&
after - j->lastOutput >= std::chrono::seconds(settings.maxSilentTime))
{
handleWorkResult(
goal,
goal->timedOut(Error(
"%1% timed out after %2% seconds of silence",
goal->getName(),
settings.maxSilentTime
))
);
continue;
}
else if (!goal->exitCode.has_value() &&
0 != settings.buildTimeout &&
goal->respectsTimeouts() &&
after - j->timeStarted >= std::chrono::seconds(settings.buildTimeout))
{
handleWorkResult(
goal,
goal->timedOut(
Error("%1% timed out after %2% seconds", goal->getName(), settings.buildTimeout)
)
);
continue;
}
std::set<int> fds2(j->fds);
std::vector<unsigned char> buffer(4096);
for (auto & k : fds2) {
const auto fdPollStatusId = get(fdToPollStatus, k);
assert(fdPollStatusId);
assert(*fdPollStatusId < pollStatus.size());
if (pollStatus.at(*fdPollStatusId).revents) {
ssize_t rd = ::read(k, buffer.data(), buffer.size());
// FIXME: is there a cleaner way to handle pt close
// than EIO? Is this even standard?
if (rd == 0 || (rd == -1 && errno == EIO)) {
debug("%1%: got EOF", goal->getName());
goal->handleEOF(k);
handleWorkResult(goal, Goal::ContinueImmediately{});
j->fds.erase(k);
} else if (rd == -1) {
if (errno != EINTR)
throw SysError("%s: read failed", goal->getName());
} else {
printMsg(lvlVomit, "%1%: read %2% bytes",
goal->getName(), rd);
std::string_view data(charptr_cast<char *>(buffer.data()), rd);
j->lastOutput = after;
handleWorkResult(goal, goal->handleChildOutput(k, data));
}
}
}
}
if (!waitingForAWhile.empty() && lastWokenUp + std::chrono::seconds(settings.pollInterval) <= after) {
lastWokenUp = after;
for (auto & i : waitingForAWhile) {
GoalPtr goal = i.lock();
if (goal) wakeUp(goal);
}
waitingForAWhile.clear();
} }
} catch (...) {
co_return result::failure(std::current_exception());
} }

View file

@ -1,8 +1,6 @@
#pragma once #pragma once
///@file ///@file
#include "async-semaphore.hh"
#include "concepts.hh"
#include "notifying-counter.hh" #include "notifying-counter.hh"
#include "types.hh" #include "types.hh"
#include "lock.hh" #include "lock.hh"
@ -11,7 +9,6 @@
#include "realisation.hh" #include "realisation.hh"
#include <future> #include <future>
#include <kj/async-io.h>
#include <thread> #include <thread>
namespace nix { namespace nix {
@ -20,22 +17,37 @@ namespace nix {
struct DerivationGoal; struct DerivationGoal;
struct PathSubstitutionGoal; struct PathSubstitutionGoal;
class DrvOutputSubstitutionGoal; class DrvOutputSubstitutionGoal;
class LocalStore;
typedef std::chrono::time_point<std::chrono::steady_clock> steady_time_point; typedef std::chrono::time_point<std::chrono::steady_clock> steady_time_point;
/**
* A mapping used to remember for each child process to what goal it
* belongs, and file descriptors for receiving log data and output
* path creation commands.
*/
struct Child
{
WeakGoalPtr goal;
Goal * goal2; // ugly hackery
std::set<int> fds;
bool inBuildSlot;
/**
* Time we last got output on stdout/stderr
*/
steady_time_point lastOutput;
steady_time_point timeStarted;
};
/* Forward definition. */ /* Forward definition. */
struct HookInstance; struct HookInstance;
class GoalFactory class GoalFactory
{ {
public: public:
virtual std::pair<std::shared_ptr<DerivationGoal>, kj::Promise<Result<Goal::WorkResult>>> virtual std::shared_ptr<DerivationGoal> makeDerivationGoal(
makeDerivationGoal(
const StorePath & drvPath, const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal const StorePath & drvPath, const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal
) = 0; ) = 0;
virtual std::pair<std::shared_ptr<DerivationGoal>, kj::Promise<Result<Goal::WorkResult>>> virtual std::shared_ptr<DerivationGoal> makeBasicDerivationGoal(
makeBasicDerivationGoal(
const StorePath & drvPath, const StorePath & drvPath,
const BasicDerivation & drv, const BasicDerivation & drv,
const OutputsSpec & wantedOutputs, const OutputsSpec & wantedOutputs,
@ -45,14 +57,12 @@ public:
/** /**
* @ref SubstitutionGoal "substitution goal" * @ref SubstitutionGoal "substitution goal"
*/ */
virtual std::pair<std::shared_ptr<PathSubstitutionGoal>, kj::Promise<Result<Goal::WorkResult>>> virtual std::shared_ptr<PathSubstitutionGoal> makePathSubstitutionGoal(
makePathSubstitutionGoal(
const StorePath & storePath, const StorePath & storePath,
RepairFlag repair = NoRepair, RepairFlag repair = NoRepair,
std::optional<ContentAddress> ca = std::nullopt std::optional<ContentAddress> ca = std::nullopt
) = 0; ) = 0;
virtual std::pair<std::shared_ptr<DrvOutputSubstitutionGoal>, kj::Promise<Result<Goal::WorkResult>>> virtual std::shared_ptr<DrvOutputSubstitutionGoal> makeDrvOutputSubstitutionGoal(
makeDrvOutputSubstitutionGoal(
const DrvOutput & id, const DrvOutput & id,
RepairFlag repair = NoRepair, RepairFlag repair = NoRepair,
std::optional<ContentAddress> ca = std::nullopt std::optional<ContentAddress> ca = std::nullopt
@ -64,8 +74,7 @@ public:
* It will be a `DerivationGoal` for a `DerivedPath::Built` or * It will be a `DerivationGoal` for a `DerivedPath::Built` or
* a `SubstitutionGoal` for a `DerivedPath::Opaque`. * a `SubstitutionGoal` for a `DerivedPath::Opaque`.
*/ */
virtual std::pair<GoalPtr, kj::Promise<Result<Goal::WorkResult>>> virtual GoalPtr makeGoal(const DerivedPath & req, BuildMode buildMode = bmNormal) = 0;
makeGoal(const DerivedPath & req, BuildMode buildMode = bmNormal) = 0;
}; };
// elaborate hoax to let goals access factory methods while hiding them from the public // elaborate hoax to let goals access factory methods while hiding them from the public
@ -84,27 +93,61 @@ protected:
*/ */
class Worker : public WorkerBase class Worker : public WorkerBase
{ {
public:
using Targets = std::map<GoalPtr, kj::Promise<Result<Goal::WorkResult>>>;
using Results = std::map<GoalPtr, Goal::WorkResult>;
private: private:
bool running = false; bool running = false;
template<typename G> /* Note: the worker should only have strong pointers to the
struct CachedGoal top-level goals. */
{
std::shared_ptr<G> goal; /**
kj::ForkedPromise<Result<Goal::WorkResult>> promise{nullptr}; * The top-level goals of the worker.
}; */
Goals topGoals;
/**
* Goals that are ready to do some work.
*/
WeakGoals awake;
/**
* Goals waiting for a build slot.
*/
WeakGoals wantingToBuild;
/**
* Child processes currently running.
*/
std::list<Child> children;
/**
* Number of build slots occupied. This includes local builds but does not
* include substitutions or remote builds via the build hook.
*/
unsigned int nrLocalBuilds;
/**
* Number of substitution slots occupied.
*/
unsigned int nrSubstitutions;
/** /**
* Maps used to prevent multiple instantiations of a goal for the * Maps used to prevent multiple instantiations of a goal for the
* same derivation / path. * same derivation / path.
*/ */
std::map<StorePath, CachedGoal<DerivationGoal>> derivationGoals; std::map<StorePath, std::weak_ptr<DerivationGoal>> derivationGoals;
std::map<StorePath, CachedGoal<PathSubstitutionGoal>> substitutionGoals; std::map<StorePath, std::weak_ptr<PathSubstitutionGoal>> substitutionGoals;
std::map<DrvOutput, CachedGoal<DrvOutputSubstitutionGoal>> drvOutputSubstitutionGoals; std::map<DrvOutput, std::weak_ptr<DrvOutputSubstitutionGoal>> drvOutputSubstitutionGoals;
/**
* Goals sleeping for a few seconds (polling a lock).
*/
WeakGoals waitingForAWhile;
/**
* Last time the goals in `waitingForAWhile` where woken up.
*/
steady_time_point lastWokenUp;
/** /**
* Cache for pathContentsGood(). * Cache for pathContentsGood().
@ -132,25 +175,60 @@ private:
*/ */
bool checkMismatch = false; bool checkMismatch = false;
void goalFinished(GoalPtr goal, Goal::Finished & f);
void handleWorkResult(GoalPtr goal, Goal::WorkResult how);
/**
* Put `goal` to sleep until a build slot becomes available (which
* might be right away).
*/
void waitForBuildSlot(GoalPtr goal);
/**
* Wait for a few seconds and then retry this goal. Used when
* waiting for a lock held by another process. This kind of
* polling is inefficient, but POSIX doesn't really provide a way
* to wait for multiple locks in the main select() loop.
*/
void waitForAWhile(GoalPtr goal);
/**
* Wake up a goal (i.e., there is something for it to do).
*/
void wakeUp(GoalPtr goal);
/**
* Wait for input to become available.
*/
void waitForInput();
/**
* Remove a dead goal.
*/
void removeGoal(GoalPtr goal);
/**
* Registers a running child process. `inBuildSlot` means that
* the process counts towards the jobs limit.
*/
void childStarted(GoalPtr goal, const std::set<int> & fds,
bool inBuildSlot);
/** /**
* Pass current stats counters to the logger for progress bar updates. * Pass current stats counters to the logger for progress bar updates.
*/ */
kj::Promise<Result<Results>> updateStatistics(); void updateStatistics();
AsyncSemaphore statisticsUpdateSignal{1}; bool statisticsOutdated = true;
std::optional<AsyncSemaphore::Token> statisticsUpdateInhibitor;
/** /**
* Mark statistics as outdated, such that `updateStatistics` will be called. * Mark statistics as outdated, such that `updateStatistics` will be called.
*/ */
void updateStatisticsLater() void updateStatisticsLater()
{ {
statisticsUpdateInhibitor = {}; statisticsOutdated = true;
} }
kj::Promise<Result<Results>> runImpl(Targets topGoals);
kj::Promise<Result<Results>> boopGC(LocalStore & localStore);
public: public:
const Activity act; const Activity act;
@ -159,13 +237,7 @@ public:
Store & store; Store & store;
Store & evalStore; Store & evalStore;
kj::AsyncIoContext & aio;
AsyncSemaphore substitutions, localBuilds;
private:
kj::TaskSet children;
public:
struct HookState { struct HookState {
std::unique_ptr<HookInstance> instance; std::unique_ptr<HookInstance> instance;
@ -192,7 +264,7 @@ public:
NotifyingCounter<uint64_t> expectedNarSize{[this] { updateStatisticsLater(); }}; NotifyingCounter<uint64_t> expectedNarSize{[this] { updateStatisticsLater(); }};
NotifyingCounter<uint64_t> doneNarSize{[this] { updateStatisticsLater(); }}; NotifyingCounter<uint64_t> doneNarSize{[this] { updateStatisticsLater(); }};
Worker(Store & store, Store & evalStore, kj::AsyncIoContext & aio); Worker(Store & store, Store & evalStore);
~Worker(); ~Worker();
/** /**
@ -203,35 +275,21 @@ public:
* @ref DerivationGoal "derivation goal" * @ref DerivationGoal "derivation goal"
*/ */
private: private:
template<typename ID, std::derived_from<Goal> G> std::shared_ptr<DerivationGoal> makeDerivationGoalCommon(
std::pair<std::shared_ptr<G>, kj::Promise<Result<Goal::WorkResult>>> makeGoalCommon( const StorePath & drvPath, const OutputsSpec & wantedOutputs,
std::map<ID, CachedGoal<G>> & map, std::function<std::shared_ptr<DerivationGoal>()> mkDrvGoal);
const ID & key, std::shared_ptr<DerivationGoal> makeDerivationGoal(
InvocableR<std::unique_ptr<G>> auto create,
InvocableR<bool, G &> auto modify
);
std::pair<std::shared_ptr<DerivationGoal>, kj::Promise<Result<Goal::WorkResult>>> makeDerivationGoal(
const StorePath & drvPath, const StorePath & drvPath,
const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal) override; const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal) override;
std::pair<std::shared_ptr<DerivationGoal>, kj::Promise<Result<Goal::WorkResult>>> makeBasicDerivationGoal( std::shared_ptr<DerivationGoal> makeBasicDerivationGoal(
const StorePath & drvPath, const BasicDerivation & drv, const StorePath & drvPath, const BasicDerivation & drv,
const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal) override; const OutputsSpec & wantedOutputs, BuildMode buildMode = bmNormal) override;
/** /**
* @ref SubstitutionGoal "substitution goal" * @ref SubstitutionGoal "substitution goal"
*/ */
std::pair<std::shared_ptr<PathSubstitutionGoal>, kj::Promise<Result<Goal::WorkResult>>> std::shared_ptr<PathSubstitutionGoal> makePathSubstitutionGoal(const StorePath & storePath, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt) override;
makePathSubstitutionGoal( std::shared_ptr<DrvOutputSubstitutionGoal> makeDrvOutputSubstitutionGoal(const DrvOutput & id, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt) override;
const StorePath & storePath,
RepairFlag repair = NoRepair,
std::optional<ContentAddress> ca = std::nullopt
) override;
std::pair<std::shared_ptr<DrvOutputSubstitutionGoal>, kj::Promise<Result<Goal::WorkResult>>>
makeDrvOutputSubstitutionGoal(
const DrvOutput & id,
RepairFlag repair = NoRepair,
std::optional<ContentAddress> ca = std::nullopt
) override;
/** /**
* Make a goal corresponding to the `DerivedPath`. * Make a goal corresponding to the `DerivedPath`.
@ -239,14 +297,18 @@ private:
* It will be a `DerivationGoal` for a `DerivedPath::Built` or * It will be a `DerivationGoal` for a `DerivedPath::Built` or
* a `SubstitutionGoal` for a `DerivedPath::Opaque`. * a `SubstitutionGoal` for a `DerivedPath::Opaque`.
*/ */
std::pair<GoalPtr, kj::Promise<Result<Goal::WorkResult>>> GoalPtr makeGoal(const DerivedPath & req, BuildMode buildMode = bmNormal) override;
makeGoal(const DerivedPath & req, BuildMode buildMode = bmNormal) override;
public: public:
/**
* Unregisters a running child process.
*/
void childTerminated(Goal * goal);
/** /**
* Loop until the specified top-level goals have finished. * Loop until the specified top-level goals have finished.
*/ */
Results run(std::function<Targets (GoalFactory &)> req); Goals run(std::function<Goals (GoalFactory &)> req);
/*** /***
* The exit status in case of failure. * The exit status in case of failure.

View file

@ -6,7 +6,7 @@
namespace nix { namespace nix {
// TODO: make pluggable. // TODO: make pluggable.
void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData, const std::string & caFileData); void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData);
void builtinUnpackChannel(const BasicDerivation & drv); void builtinUnpackChannel(const BasicDerivation & drv);
} }

View file

@ -7,7 +7,7 @@
namespace nix { namespace nix {
void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData, const std::string & caFileData) void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData)
{ {
/* Make the host's netrc data available. Too bad curl requires /* Make the host's netrc data available. Too bad curl requires
this to be stored in a file. It would be nice if we could just this to be stored in a file. It would be nice if we could just
@ -17,9 +17,6 @@ void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData,
writeFile(settings.netrcFile, netrcData, 0600); writeFile(settings.netrcFile, netrcData, 0600);
} }
settings.caFile = "ca-certificates.crt";
writeFile(settings.caFile, caFileData, 0600);
auto getAttr = [&](const std::string & name) { auto getAttr = [&](const std::string & name) {
auto i = drv.env.find(name); auto i = drv.env.find(name);
if (i == drv.env.end()) throw Error("attribute '%s' missing", name); if (i == drv.env.end()) throw Error("attribute '%s' missing", name);
@ -36,7 +33,10 @@ void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData,
auto fetch = [&](const std::string & url) { auto fetch = [&](const std::string & url) {
/* No need to do TLS verification, because we check the hash of
the result anyway. */
FileTransferRequest request(url); FileTransferRequest request(url);
request.verifyTLS = false;
auto raw = fileTransfer->download(std::move(request)); auto raw = fileTransfer->download(std::move(request));
auto decompressor = makeDecompressionSource( auto decompressor = makeDecompressionSource(

View file

@ -115,7 +115,7 @@ struct curlFileTransfer : public FileTransfer
if (!done) if (!done)
fail(FileTransferError(Interrupted, {}, "download of '%s' was interrupted", request.uri)); fail(FileTransferError(Interrupted, {}, "download of '%s' was interrupted", request.uri));
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
@ -337,7 +337,7 @@ struct curlFileTransfer : public FileTransfer
// wrapping user `callback`s instead is not possible because the // wrapping user `callback`s instead is not possible because the
// Callback api expects std::functions, and copying Callbacks is // Callback api expects std::functions, and copying Callbacks is
// not possible due the promises they hold. // not possible due the promises they hold.
if (code == CURLE_OK && !dataCallback && result.data.length() > 0) { if (code == CURLE_OK && !dataCallback) {
result.data = decompress(encoding, result.data); result.data = decompress(encoding, result.data);
} }

View file

@ -923,8 +923,8 @@ void LocalStore::autoGC(bool sync)
} catch (...) { } catch (...) {
// FIXME: we could propagate the exception to the // FIXME: we could propagate the exception to the
// future, but we don't really care. (what??) // future, but we don't really care.
ignoreExceptionInDestructor(); ignoreException();
} }
}).detach(); }).detach();

View file

@ -269,31 +269,11 @@ Path Settings::getDefaultSSLCertFile()
const std::string nixVersion = PACKAGE_VERSION; const std::string nixVersion = PACKAGE_VERSION;
void to_json(nlohmann::json & j, const SandboxMode & e) NLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, {
{ {SandboxMode::smEnabled, true},
if (e == SandboxMode::smEnabled) { {SandboxMode::smRelaxed, "relaxed"},
j = true; {SandboxMode::smDisabled, false},
} else if (e == SandboxMode::smRelaxed) { });
j = "relaxed";
} else if (e == SandboxMode::smDisabled) {
j = false;
} else {
abort();
}
}
void from_json(const nlohmann::json & j, SandboxMode & e)
{
if (j == true) {
e = SandboxMode::smEnabled;
} else if (j == "relaxed") {
e = SandboxMode::smRelaxed;
} else if (j == false) {
e = SandboxMode::smDisabled;
} else {
throw Error("Invalid sandbox mode '%s'", std::string(j));
}
}
template<> SandboxMode BaseSetting<SandboxMode>::parse(const std::string & str, const ApplyConfigOptions & options) const template<> SandboxMode BaseSetting<SandboxMode>::parse(const std::string & str, const ApplyConfigOptions & options) const
{ {
@ -443,7 +423,7 @@ static bool initLibStoreDone = false;
void assertLibStoreInitialized() { void assertLibStoreInitialized() {
if (!initLibStoreDone) { if (!initLibStoreDone) {
printError("The program must call nix::initNix() before calling any libstore library functions."); printError("The program must call nix::initNix() before calling any libstore library functions.");
std::terminate(); abort();
}; };
} }

View file

@ -14,9 +14,6 @@ namespace nix {
typedef enum { smEnabled, smRelaxed, smDisabled } SandboxMode; typedef enum { smEnabled, smRelaxed, smDisabled } SandboxMode;
void to_json(nlohmann::json & j, const SandboxMode & e);
void from_json(const nlohmann::json & j, SandboxMode & e);
struct MaxBuildJobsSetting : public BaseSetting<unsigned int> struct MaxBuildJobsSetting : public BaseSetting<unsigned int>
{ {
MaxBuildJobsSetting(Config * options, MaxBuildJobsSetting(Config * options,
@ -640,10 +637,10 @@ public:
PathsSetting<std::optional<Path>> diffHook{ PathsSetting<std::optional<Path>> diffHook{
this, std::nullopt, "diff-hook", this, std::nullopt, "diff-hook",
R"( R"(
Path to an executable capable of diffing build results. The hook is Absolute path to an executable capable of diffing build
executed if `run-diff-hook` is true, and the output of a build is results. The hook is executed if `run-diff-hook` is true, and the
known to not be the same. This program is not executed to determine output of a build is known to not be the same. This program is not
if two results are the same. executed to determine if two results are the same.
The diff hook is executed by the same user and group who ran the The diff hook is executed by the same user and group who ran the
build. However, the diff hook does not have write access to the build. However, the diff hook does not have write access to the

View file

@ -481,7 +481,7 @@ LocalStore::~LocalStore()
unlink(fnTempRoots.c_str()); unlink(fnTempRoots.c_str());
} }
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
@ -664,20 +664,6 @@ static void canonicalisePathMetaData_(
if (!(S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode))) if (!(S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode)))
throw Error("file '%1%' has an unsupported type", path); throw Error("file '%1%' has an unsupported type", path);
/* Fail if the file is not owned by the build user. This prevents
us from messing up the ownership/permissions of files
hard-linked into the output (e.g. "ln /etc/shadow $out/foo").
However, ignore files that we chown'ed ourselves previously to
ensure that we don't fail on hard links within the same build
(i.e. "touch $out/foo; ln $out/foo $out/bar"). */
if (uidRange && (st.st_uid < uidRange->first || st.st_uid > uidRange->second)) {
if (S_ISDIR(st.st_mode) || !inodesSeen.count(Inode(st.st_dev, st.st_ino)))
throw BuildError("invalid ownership on file '%1%'", path);
mode_t mode = st.st_mode & ~S_IFMT;
assert(S_ISLNK(st.st_mode) || (st.st_uid == geteuid() && (mode == 0444 || mode == 0555) && st.st_mtime == mtimeStore));
return;
}
#if __linux__ #if __linux__
/* Remove extended attributes / ACLs. */ /* Remove extended attributes / ACLs. */
ssize_t eaSize = llistxattr(path.c_str(), nullptr, 0); ssize_t eaSize = llistxattr(path.c_str(), nullptr, 0);
@ -691,8 +677,6 @@ static void canonicalisePathMetaData_(
if ((eaSize = llistxattr(path.c_str(), eaBuf.data(), eaBuf.size())) < 0) if ((eaSize = llistxattr(path.c_str(), eaBuf.data(), eaBuf.size())) < 0)
throw SysError("querying extended attributes of '%s'", path); throw SysError("querying extended attributes of '%s'", path);
if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
chmod(path.c_str(), st.st_mode | S_IWUSR);
for (auto & eaName: tokenizeString<Strings>(std::string(eaBuf.data(), eaSize), std::string("\000", 1))) { for (auto & eaName: tokenizeString<Strings>(std::string(eaBuf.data(), eaSize), std::string("\000", 1))) {
if (settings.ignoredAcls.get().count(eaName)) continue; if (settings.ignoredAcls.get().count(eaName)) continue;
if (lremovexattr(path.c_str(), eaName.c_str()) == -1) if (lremovexattr(path.c_str(), eaName.c_str()) == -1)
@ -701,6 +685,20 @@ static void canonicalisePathMetaData_(
} }
#endif #endif
/* Fail if the file is not owned by the build user. This prevents
us from messing up the ownership/permissions of files
hard-linked into the output (e.g. "ln /etc/shadow $out/foo").
However, ignore files that we chown'ed ourselves previously to
ensure that we don't fail on hard links within the same build
(i.e. "touch $out/foo; ln $out/foo $out/bar"). */
if (uidRange && (st.st_uid < uidRange->first || st.st_uid > uidRange->second)) {
if (S_ISDIR(st.st_mode) || !inodesSeen.count(Inode(st.st_dev, st.st_ino)))
throw BuildError("invalid ownership on file '%1%'", path);
mode_t mode = st.st_mode & ~S_IFMT;
assert(S_ISLNK(st.st_mode) || (st.st_uid == geteuid() && (mode == 0444 || mode == 0555) && st.st_mtime == mtimeStore));
return;
}
inodesSeen.insert(Inode(st.st_dev, st.st_ino)); inodesSeen.insert(Inode(st.st_dev, st.st_ino));
canonicaliseTimestampAndPermissions(path, st); canonicaliseTimestampAndPermissions(path, st);
@ -1218,11 +1216,11 @@ void LocalStore::addToStore(const ValidPathInfo & info, Source & source,
bool narRead = false; bool narRead = false;
Finally cleanup = [&]() { Finally cleanup = [&]() {
if (!narRead) { if (!narRead) {
NARParseVisitor sink; ParseSink sink;
try { try {
parseDump(sink, source); parseDump(sink, source);
} catch (...) { } catch (...) {
ignoreExceptionExceptInterrupt(); ignoreException();
} }
} }
}; };

View file

@ -73,16 +73,8 @@ struct SimpleUserLock : UserLock
debug("trying user '%s'", i); debug("trying user '%s'", i);
struct passwd * pw = getpwnam(i.c_str()); struct passwd * pw = getpwnam(i.c_str());
if (!pw) { if (!pw)
#ifdef __APPLE__ throw Error("the user '%s' in the group '%s' does not exist", i, settings.buildUsersGroup);
#define APPLE_HINT "\n\nhint: this may be caused by an update to macOS Sequoia breaking existing Lix installations.\n" \
"See the macOS Sequoia page on the Lix wiki for detailed repair instructions: https://wiki.lix.systems/link/81"
#else
#define APPLE_HINT
#endif
throw Error("the user '%s' in the group '%s' does not exist" APPLE_HINT, i, settings.buildUsersGroup);
#undef APPLE_HINT
}
auto fnUserLock = fmt("%s/userpool/%s", settings.nixStateDir,pw->pw_uid); auto fnUserLock = fmt("%s/userpool/%s", settings.nixStateDir,pw->pw_uid);

View file

@ -221,7 +221,6 @@ dependencies = [
aws_s3, aws_s3,
aws_sdk_transfer, aws_sdk_transfer,
nlohmann_json, nlohmann_json,
kj,
] ]
if host_machine.system() == 'freebsd' if host_machine.system() == 'freebsd'

View file

@ -2,7 +2,6 @@
#include "archive.hh" #include "archive.hh"
#include <map> #include <map>
#include <memory>
#include <stack> #include <stack>
#include <algorithm> #include <algorithm>
@ -34,7 +33,7 @@ struct NarAccessor : public FSAccessor
NarMember root; NarMember root;
struct NarIndexer : NARParseVisitor, Source struct NarIndexer : ParseSink, Source
{ {
NarAccessor & acc; NarAccessor & acc;
Source & source; Source & source;
@ -45,12 +44,11 @@ struct NarAccessor : public FSAccessor
uint64_t pos = 0; uint64_t pos = 0;
public:
NarIndexer(NarAccessor & acc, Source & source) NarIndexer(NarAccessor & acc, Source & source)
: acc(acc), source(source) : acc(acc), source(source)
{ } { }
NarMember & createMember(const Path & path, NarMember member) void createMember(const Path & path, NarMember member)
{ {
size_t level = std::count(path.begin(), path.end(), '/'); size_t level = std::count(path.begin(), path.end(), '/');
while (parents.size() > level) parents.pop(); while (parents.size() > level) parents.pop();
@ -64,8 +62,6 @@ struct NarAccessor : public FSAccessor
auto result = parents.top()->children.emplace(baseNameOf(path), std::move(member)); auto result = parents.top()->children.emplace(baseNameOf(path), std::move(member));
parents.push(&result.first->second); parents.push(&result.first->second);
} }
return *parents.top();
} }
void createDirectory(const Path & path) override void createDirectory(const Path & path) override
@ -73,18 +69,29 @@ struct NarAccessor : public FSAccessor
createMember(path, {FSAccessor::Type::tDirectory, false, 0, 0}); createMember(path, {FSAccessor::Type::tDirectory, false, 0, 0});
} }
std::unique_ptr<FileHandle> createRegularFile(const Path & path, uint64_t size, bool executable) override void createRegularFile(const Path & path) override
{ {
auto & memb = createMember(path, {FSAccessor::Type::tRegular, false, 0, 0}); createMember(path, {FSAccessor::Type::tRegular, false, 0, 0});
assert(size <= std::numeric_limits<uint64_t>::max());
memb.size = (uint64_t) size;
memb.start = pos;
memb.isExecutable = executable;
return std::make_unique<FileHandle>();
} }
void closeRegularFile() override
{ }
void isExecutable() override
{
parents.top()->isExecutable = true;
}
void preallocateContents(uint64_t size) override
{
assert(size <= std::numeric_limits<uint64_t>::max());
parents.top()->size = (uint64_t) size;
parents.top()->start = pos;
}
void receiveContents(std::string_view data) override
{ }
void createSymlink(const Path & path, const std::string & target) override void createSymlink(const Path & path, const std::string & target) override
{ {
createMember(path, createMember(path,

View file

@ -31,7 +31,7 @@ struct MakeReadOnly
/* This will make the path read-only. */ /* This will make the path read-only. */
if (path != "") canonicaliseTimestampAndPermissions(path); if (path != "") canonicaliseTimestampAndPermissions(path);
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
}; };

View file

@ -145,7 +145,7 @@ PathLocks::~PathLocks()
try { try {
unlock(); unlock();
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -1,7 +1,6 @@
#pragma once #pragma once
///@file ///@file
#include "error.hh"
#include "file-descriptor.hh" #include "file-descriptor.hh"
namespace nix { namespace nix {
@ -54,7 +53,7 @@ struct FdLock
if (acquired) if (acquired)
lockFile(fd, ltNone, false); lockFile(fd, ltNone, false);
} catch (SysError &) { } catch (SysError &) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
}; };

View file

@ -25,7 +25,7 @@ std::shared_ptr<LocalStore> LocalStore::makeLocalStore(const Params & params)
#endif #endif
} }
std::unique_ptr<LocalDerivationGoal> LocalDerivationGoal::makeLocalDerivationGoal( std::shared_ptr<LocalDerivationGoal> LocalDerivationGoal::makeLocalDerivationGoal(
const StorePath & drvPath, const StorePath & drvPath,
const OutputsSpec & wantedOutputs, const OutputsSpec & wantedOutputs,
Worker & worker, Worker & worker,
@ -34,17 +34,17 @@ std::unique_ptr<LocalDerivationGoal> LocalDerivationGoal::makeLocalDerivationGoa
) )
{ {
#if __linux__ #if __linux__
return std::make_unique<LinuxLocalDerivationGoal>(drvPath, wantedOutputs, worker, isDependency, buildMode); return std::make_shared<LinuxLocalDerivationGoal>(drvPath, wantedOutputs, worker, isDependency, buildMode);
#elif __APPLE__ #elif __APPLE__
return std::make_unique<DarwinLocalDerivationGoal>(drvPath, wantedOutputs, worker, isDependency, buildMode); return std::make_shared<DarwinLocalDerivationGoal>(drvPath, wantedOutputs, worker, isDependency, buildMode);
#elif __FreeBSD__ #elif __FreeBSD__
return std::make_unique<FreeBSDLocalDerivationGoal>(drvPath, wantedOutputs, worker, isDependency, buildMode); return std::make_shared<FreeBSDLocalDerivationGoal>(drvPath, wantedOutputs, worker, isDependency, buildMode);
#else #else
return std::make_unique<FallbackLocalDerivationGoal>(drvPath, wantedOutputs, worker, isDependency, buildMode); return std::make_shared<FallbackLocalDerivationGoal>(drvPath, wantedOutputs, worker, isDependency, buildMode);
#endif #endif
} }
std::unique_ptr<LocalDerivationGoal> LocalDerivationGoal::makeLocalDerivationGoal( std::shared_ptr<LocalDerivationGoal> LocalDerivationGoal::makeLocalDerivationGoal(
const StorePath & drvPath, const StorePath & drvPath,
const BasicDerivation & drv, const BasicDerivation & drv,
const OutputsSpec & wantedOutputs, const OutputsSpec & wantedOutputs,
@ -54,19 +54,19 @@ std::unique_ptr<LocalDerivationGoal> LocalDerivationGoal::makeLocalDerivationGoa
) )
{ {
#if __linux__ #if __linux__
return std::make_unique<LinuxLocalDerivationGoal>( return std::make_shared<LinuxLocalDerivationGoal>(
drvPath, drv, wantedOutputs, worker, isDependency, buildMode drvPath, drv, wantedOutputs, worker, isDependency, buildMode
); );
#elif __APPLE__ #elif __APPLE__
return std::make_unique<DarwinLocalDerivationGoal>( return std::make_shared<DarwinLocalDerivationGoal>(
drvPath, drv, wantedOutputs, worker, isDependency, buildMode drvPath, drv, wantedOutputs, worker, isDependency, buildMode
); );
#elif __FreeBSD__ #elif __FreeBSD__
return std::make_unique<FreeBSDLocalDerivationGoal>( return std::make_shared<FreeBSDLocalDerivationGoal>(
drvPath, drv, wantedOutputs, worker, isDependency, buildMode drvPath, drv, wantedOutputs, worker, isDependency, buildMode
); );
#else #else
return std::make_unique<FallbackLocalDerivationGoal>( return std::make_shared<FallbackLocalDerivationGoal>(
drvPath, drv, wantedOutputs, worker, isDependency, buildMode drvPath, drv, wantedOutputs, worker, isDependency, buildMode
); );
#endif #endif

View file

@ -29,7 +29,7 @@ ref<FSAccessor> RemoteFSAccessor::addToCache(std::string_view hashPart, std::str
/* FIXME: do this asynchronously. */ /* FIXME: do this asynchronously. */
writeFile(makeCacheFile(hashPart, "nar"), nar); writeFile(makeCacheFile(hashPart, "nar"), nar);
} catch (...) { } catch (...) {
ignoreExceptionExceptInterrupt(); ignoreException();
} }
} }
@ -41,7 +41,7 @@ ref<FSAccessor> RemoteFSAccessor::addToCache(std::string_view hashPart, std::str
nlohmann::json j = listNar(narAccessor, "", true); nlohmann::json j = listNar(narAccessor, "", true);
writeFile(makeCacheFile(hashPart, "ls"), j.dump()); writeFile(makeCacheFile(hashPart, "ls"), j.dump());
} catch (...) { } catch (...) {
ignoreExceptionExceptInterrupt(); ignoreException();
} }
} }

View file

@ -1,4 +1,3 @@
#include "error.hh"
#include "serialise.hh" #include "serialise.hh"
#include "signals.hh" #include "signals.hh"
#include "path-with-outputs.hh" #include "path-with-outputs.hh"
@ -856,7 +855,7 @@ RemoteStore::Connection::~Connection()
try { try {
to.flush(); to.flush();
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
@ -986,7 +985,7 @@ void RemoteStore::ConnectionHandle::withFramedSink(std::function<void(Sink & sin
try { try {
std::rethrow_exception(ex); std::rethrow_exception(ex);
} catch (...) { } catch (...) {
ignoreExceptionExceptInterrupt(); ignoreException();
} }
} }
} }

View file

@ -85,7 +85,7 @@ SQLite::~SQLite()
if (db && sqlite3_close(db) != SQLITE_OK) if (db && sqlite3_close(db) != SQLITE_OK)
SQLiteError::throw_(db, "closing database"); SQLiteError::throw_(db, "closing database");
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
@ -124,7 +124,7 @@ SQLiteStmt::~SQLiteStmt()
if (stmt && sqlite3_finalize(stmt) != SQLITE_OK) if (stmt && sqlite3_finalize(stmt) != SQLITE_OK)
SQLiteError::throw_(db, "finalizing statement '%s'", sql); SQLiteError::throw_(db, "finalizing statement '%s'", sql);
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
@ -248,7 +248,7 @@ SQLiteTxn::~SQLiteTxn()
if (active && sqlite3_exec(db, "rollback;", 0, 0, 0) != SQLITE_OK) if (active && sqlite3_exec(db, "rollback;", 0, 0, 0) != SQLITE_OK)
SQLiteError::throw_(db, "aborting transaction"); SQLiteError::throw_(db, "aborting transaction");
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -379,48 +379,6 @@ void Store::addMultipleToStore(
} }
} }
namespace {
/**
* If the NAR archive contains a single file at top-level, then save
* the contents of the file to `s`. Otherwise assert.
*/
struct RetrieveRegularNARVisitor : NARParseVisitor
{
struct MyFileHandle : public FileHandle
{
Sink & sink;
void receiveContents(std::string_view data) override
{
sink(data);
}
private:
MyFileHandle(Sink & sink) : sink(sink) {}
friend struct RetrieveRegularNARVisitor;
};
Sink & sink;
RetrieveRegularNARVisitor(Sink & sink) : sink(sink) { }
std::unique_ptr<FileHandle> createRegularFile(const Path & path, uint64_t size, bool executable) override
{
return std::unique_ptr<MyFileHandle>(new MyFileHandle{sink});
}
void createDirectory(const Path & path) override
{
assert(false && "RetrieveRegularNARVisitor::createDirectory must not be called");
}
void createSymlink(const Path & path, const std::string & target) override
{
assert(false && "RetrieveRegularNARVisitor::createSymlink must not be called");
}
};
}
/* /*
The aim of this function is to compute in one pass the correct ValidPathInfo for The aim of this function is to compute in one pass the correct ValidPathInfo for
@ -455,7 +413,7 @@ ValidPathInfo Store::addToStoreSlow(std::string_view name, const Path & srcPath,
/* Note that fileSink and unusualHashTee must be mutually exclusive, since /* Note that fileSink and unusualHashTee must be mutually exclusive, since
they both write to caHashSink. Note that that requisite is currently true they both write to caHashSink. Note that that requisite is currently true
because the former is only used in the flat case. */ because the former is only used in the flat case. */
RetrieveRegularNARVisitor fileSink { caHashSink }; RetrieveRegularNARSink fileSink { caHashSink };
TeeSink unusualHashTee { narHashSink, caHashSink }; TeeSink unusualHashTee { narHashSink, caHashSink };
auto & narSink = method == FileIngestionMethod::Recursive && hashAlgo != HashType::SHA256 auto & narSink = method == FileIngestionMethod::Recursive && hashAlgo != HashType::SHA256
@ -471,7 +429,7 @@ ValidPathInfo Store::addToStoreSlow(std::string_view name, const Path & srcPath,
information to narSink. */ information to narSink. */
TeeSource tapped { fileSource, narSink }; TeeSource tapped { fileSource, narSink };
NARParseVisitor blank; ParseSink blank;
auto & parseSink = method == FileIngestionMethod::Flat auto & parseSink = method == FileIngestionMethod::Flat
? fileSink ? fileSink
: blank; : blank;
@ -1163,7 +1121,7 @@ std::map<StorePath, StorePath> copyPaths(
// not be within our control to change that, and we might still want // not be within our control to change that, and we might still want
// to at least copy the output paths. // to at least copy the output paths.
if (e.missingFeature == Xp::CaDerivations) if (e.missingFeature == Xp::CaDerivations)
ignoreExceptionExceptInterrupt(); ignoreException();
else else
throw; throw;
} }

View file

@ -334,7 +334,7 @@ Generator<Entry> parse(Source & source)
} }
static WireFormatGenerator restore(NARParseVisitor & sink, Generator<nar::Entry> nar) static WireFormatGenerator restore(ParseSink & sink, Generator<nar::Entry> nar)
{ {
while (auto entry = nar.next()) { while (auto entry = nar.next()) {
co_yield std::visit( co_yield std::visit(
@ -347,13 +347,16 @@ static WireFormatGenerator restore(NARParseVisitor & sink, Generator<nar::Entry>
}, },
[&](nar::File f) { [&](nar::File f) {
return [](auto f, auto & sink) -> WireFormatGenerator { return [](auto f, auto & sink) -> WireFormatGenerator {
auto handle = sink.createRegularFile(f.path, f.size, f.executable); sink.createRegularFile(f.path);
sink.preallocateContents(f.size);
if (f.executable) {
sink.isExecutable();
}
while (auto block = f.contents.next()) { while (auto block = f.contents.next()) {
handle->receiveContents(std::string_view{block->data(), block->size()}); sink.receiveContents(std::string_view{block->data(), block->size()});
co_yield *block; co_yield *block;
} }
handle->close(); sink.closeRegularFile();
}(std::move(f), sink); }(std::move(f), sink);
}, },
[&](nar::Symlink sl) { [&](nar::Symlink sl) {
@ -374,12 +377,12 @@ static WireFormatGenerator restore(NARParseVisitor & sink, Generator<nar::Entry>
} }
} }
WireFormatGenerator parseAndCopyDump(NARParseVisitor & sink, Source & source) WireFormatGenerator parseAndCopyDump(ParseSink & sink, Source & source)
{ {
return restore(sink, nar::parse(source)); return restore(sink, nar::parse(source));
} }
void parseDump(NARParseVisitor & sink, Source & source) void parseDump(ParseSink & sink, Source & source)
{ {
auto parser = parseAndCopyDump(sink, source); auto parser = parseAndCopyDump(sink, source);
while (parser.next()) { while (parser.next()) {
@ -387,99 +390,11 @@ void parseDump(NARParseVisitor & sink, Source & source)
} }
} }
/* struct RestoreSink : ParseSink
* Note [NAR restoration security]:
* It's *critical* that NAR restoration will never overwrite anything even if
* duplicate filenames are passed in. It is inevitable that not all NARs are
* fit to actually successfully restore to the target filesystem; errors may
* occur due to collisions, and this *must* cause the NAR to be rejected.
*
* Although the filenames are blocked from being *the same bytes* by a higher
* layer, filesystems have other ideas on every platform:
* - The store may be on a case-insensitive filesystem like APFS, ext4 with
* casefold directories, zfs with casesensitivity=insensitive
* - The store may be on a Unicode normalizing (or normalization-insensitive)
* filesystem like APFS (where files are looked up by
* hash(normalize(fname))), HFS+ (where file names are always normalized to
* approximately NFD), or zfs with normalization=formC, etc.
*
* It is impossible to know the version of Unicode being used by the underlying
* filesystem, thus it is *impossible* to stop these collisions.
*
* Overwriting files as a result of invalid NARs will cause a security bug like
* CppNix's CVE-2024-45593 (GHSA-h4vv-h3jq-v493)
*/
/**
* This code restores NARs from disk.
*
* See Note [NAR restoration security] for security invariants in this procedure.
*
*/
struct NARRestoreVisitor : NARParseVisitor
{ {
Path dstPath; Path dstPath;
AutoCloseFD fd;
private:
class MyFileHandle : public FileHandle
{
AutoCloseFD fd;
MyFileHandle(AutoCloseFD && fd, uint64_t size, bool executable) : FileHandle(), fd(std::move(fd))
{
if (executable) {
makeExecutable();
}
maybePreallocateContents(size);
}
void makeExecutable()
{
struct stat st;
if (fstat(fd.get(), &st) == -1)
throw SysError("fstat");
if (fchmod(fd.get(), st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1)
throw SysError("fchmod");
}
void maybePreallocateContents(uint64_t len)
{
if (!archiveSettings.preallocateContents)
return;
#if HAVE_POSIX_FALLOCATE
if (len) {
errno = posix_fallocate(fd.get(), 0, len);
/* Note that EINVAL may indicate that the underlying
filesystem doesn't support preallocation (e.g. on
OpenSolaris). Since preallocation is just an
optimisation, ignore it. */
if (errno && errno != EINVAL && errno != EOPNOTSUPP && errno != ENOSYS)
throw SysError("preallocating file of %1% bytes", len);
}
#endif
}
public:
~MyFileHandle() = default;
virtual void close() override
{
/* Call close explicitly to make sure the error is checked */
fd.close();
}
void receiveContents(std::string_view data) override
{
writeFull(fd.get(), data);
}
friend struct NARRestoreVisitor;
};
public:
void createDirectory(const Path & path) override void createDirectory(const Path & path) override
{ {
Path p = dstPath + path; Path p = dstPath + path;
@ -487,13 +402,49 @@ public:
throw SysError("creating directory '%1%'", p); throw SysError("creating directory '%1%'", p);
}; };
std::unique_ptr<FileHandle> createRegularFile(const Path & path, uint64_t size, bool executable) override void createRegularFile(const Path & path) override
{ {
Path p = dstPath + path; Path p = dstPath + path;
AutoCloseFD fd = AutoCloseFD{open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0666)}; fd = AutoCloseFD{open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0666)};
if (!fd) throw SysError("creating file '%1%'", p); if (!fd) throw SysError("creating file '%1%'", p);
}
return std::unique_ptr<MyFileHandle>(new MyFileHandle(std::move(fd), size, executable)); void closeRegularFile() override
{
/* Call close explicitly to make sure the error is checked */
fd.close();
}
void isExecutable() override
{
struct stat st;
if (fstat(fd.get(), &st) == -1)
throw SysError("fstat");
if (fchmod(fd.get(), st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1)
throw SysError("fchmod");
}
void preallocateContents(uint64_t len) override
{
if (!archiveSettings.preallocateContents)
return;
#if HAVE_POSIX_FALLOCATE
if (len) {
errno = posix_fallocate(fd.get(), 0, len);
/* Note that EINVAL may indicate that the underlying
filesystem doesn't support preallocation (e.g. on
OpenSolaris). Since preallocation is just an
optimisation, ignore it. */
if (errno && errno != EINVAL && errno != EOPNOTSUPP && errno != ENOSYS)
throw SysError("preallocating file of %1% bytes", len);
}
#endif
}
void receiveContents(std::string_view data) override
{
writeFull(fd.get(), data);
} }
void createSymlink(const Path & path, const std::string & target) override void createSymlink(const Path & path, const std::string & target) override
@ -506,7 +457,7 @@ public:
void restorePath(const Path & path, Source & source) void restorePath(const Path & path, Source & source)
{ {
NARRestoreVisitor sink; RestoreSink sink;
sink.dstPath = path; sink.dstPath = path;
parseDump(sink, source); parseDump(sink, source);
} }
@ -517,9 +468,10 @@ WireFormatGenerator copyNAR(Source & source)
// FIXME: if 'source' is the output of dumpPath() followed by EOF, // FIXME: if 'source' is the output of dumpPath() followed by EOF,
// we should just forward all data directly without parsing. // we should just forward all data directly without parsing.
static NARParseVisitor parseSink; /* null sink; just parse the NAR */ static ParseSink parseSink; /* null sink; just parse the NAR */
return parseAndCopyDump(parseSink, source); return parseAndCopyDump(parseSink, source);
} }
} }

View file

@ -76,47 +76,45 @@ WireFormatGenerator dumpString(std::string_view s);
/** /**
* \todo Fix this API, it sucks. * \todo Fix this API, it sucks.
* A visitor for NAR parsing that performs filesystem (or virtual-filesystem)
* actions to restore a NAR.
*
* Methods of this may arbitrarily fail due to filename collisions.
*/ */
struct NARParseVisitor struct ParseSink
{ {
/** virtual void createDirectory(const Path & path) { };
* A type-erased file handle specific to this particular NARParseVisitor.
*/ virtual void createRegularFile(const Path & path) { };
struct FileHandle virtual void closeRegularFile() { };
virtual void isExecutable() { };
virtual void preallocateContents(uint64_t size) { };
virtual void receiveContents(std::string_view data) { };
virtual void createSymlink(const Path & path, const std::string & target) { };
};
/**
* If the NAR archive contains a single file at top-level, then save
* the contents of the file to `s`. Otherwise barf.
*/
struct RetrieveRegularNARSink : ParseSink
{
bool regular = true;
Sink & sink;
RetrieveRegularNARSink(Sink & sink) : sink(sink) { }
void createDirectory(const Path & path) override
{ {
FileHandle() {} regular = false;
FileHandle(FileHandle const &) = delete;
FileHandle & operator=(FileHandle &) = delete;
/** Puts one block of data into the file */
virtual void receiveContents(std::string_view data) { }
/**
* Explicitly closes the file. Further operations may throw an assert.
* This exists so that closing can fail and throw an exception without doing so in a destructor.
*/
virtual void close() { }
virtual ~FileHandle() = default;
};
virtual void createDirectory(const Path & path) { }
/**
* Creates a regular file in the extraction output with the given size and executable flag.
* The size is guaranteed to be the true size of the file.
*/
[[nodiscard]]
virtual std::unique_ptr<FileHandle> createRegularFile(const Path & path, uint64_t size, bool executable)
{
return std::make_unique<FileHandle>();
} }
virtual void createSymlink(const Path & path, const std::string & target) { } void receiveContents(std::string_view data) override
{
sink(data);
}
void createSymlink(const Path & path, const std::string & target) override
{
regular = false;
}
}; };
namespace nar { namespace nar {
@ -162,8 +160,8 @@ Generator<Entry> parse(Source & source);
} }
WireFormatGenerator parseAndCopyDump(NARParseVisitor & sink, Source & source); WireFormatGenerator parseAndCopyDump(ParseSink & sink, Source & source);
void parseDump(NARParseVisitor & sink, Source & source); void parseDump(ParseSink & sink, Source & source);
void restorePath(const Path & path, Source & source); void restorePath(const Path & path, Source & source);

View file

@ -1,101 +0,0 @@
#pragma once
/// @file
#include <kj/async.h>
#include <kj/common.h>
#include <kj/vector.h>
#include <list>
#include <optional>
#include <type_traits>
namespace nix {
template<typename K, typename V>
class AsyncCollect
{
public:
using Item = std::conditional_t<std::is_void_v<V>, K, std::pair<K, V>>;
private:
kj::ForkedPromise<void> allPromises;
std::list<Item> results;
size_t remaining;
kj::ForkedPromise<void> signal;
kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> notify;
void oneDone(Item item)
{
results.emplace_back(std::move(item));
remaining -= 1;
KJ_IF_MAYBE (n, notify) {
(*n)->fulfill();
notify = nullptr;
}
}
kj::Promise<void> collectorFor(K key, kj::Promise<V> promise)
{
if constexpr (std::is_void_v<V>) {
return promise.then([this, key{std::move(key)}] { oneDone(std::move(key)); });
} else {
return promise.then([this, key{std::move(key)}](V v) {
oneDone(Item{std::move(key), std::move(v)});
});
}
}
kj::ForkedPromise<void> waitForAll(kj::Array<std::pair<K, kj::Promise<V>>> & promises)
{
kj::Vector<kj::Promise<void>> wrappers;
for (auto & [key, promise] : promises) {
wrappers.add(collectorFor(std::move(key), std::move(promise)));
}
return kj::joinPromisesFailFast(wrappers.releaseAsArray()).fork();
}
public:
AsyncCollect(kj::Array<std::pair<K, kj::Promise<V>>> && promises)
: allPromises(waitForAll(promises))
, remaining(promises.size())
, signal{nullptr}
{
}
kj::Promise<std::optional<Item>> next()
{
if (remaining == 0 && results.empty()) {
return {std::nullopt};
}
if (!results.empty()) {
auto result = std::move(results.front());
results.pop_front();
return {{std::move(result)}};
}
if (notify == nullptr) {
auto pair = kj::newPromiseAndFulfiller<void>();
notify = std::move(pair.fulfiller);
signal = pair.promise.fork();
}
return signal.addBranch().exclusiveJoin(allPromises.addBranch()).then([this] {
return next();
});
}
};
/**
* Collect the results of a list of promises, in order of completion.
* Once any input promise is rejected all promises that have not been
* resolved or rejected will be cancelled and the exception rethrown.
*/
template<typename K, typename V>
AsyncCollect<K, V> asyncCollect(kj::Array<std::pair<K, kj::Promise<V>>> promises)
{
return AsyncCollect<K, V>(std::move(promises));
}
}

View file

@ -1,122 +0,0 @@
#pragma once
/// @file
/// @brief A semaphore implementation usable from within a KJ event loop.
#include <cassert>
#include <kj/async.h>
#include <kj/common.h>
#include <kj/exception.h>
#include <kj/list.h>
#include <kj/source-location.h>
#include <memory>
#include <optional>
namespace nix {
class AsyncSemaphore
{
public:
class [[nodiscard("destroying a semaphore guard releases the semaphore immediately")]] Token
{
struct Release
{
void operator()(AsyncSemaphore * sem) const
{
sem->unsafeRelease();
}
};
std::unique_ptr<AsyncSemaphore, Release> parent;
public:
Token() = default;
Token(AsyncSemaphore & parent, kj::Badge<AsyncSemaphore>) : parent(&parent) {}
bool valid() const
{
return parent != nullptr;
}
};
private:
struct Waiter
{
kj::PromiseFulfiller<Token> & fulfiller;
kj::ListLink<Waiter> link;
kj::List<Waiter, &Waiter::link> & list;
Waiter(kj::PromiseFulfiller<Token> & fulfiller, kj::List<Waiter, &Waiter::link> & list)
: fulfiller(fulfiller)
, list(list)
{
list.add(*this);
}
~Waiter()
{
if (link.isLinked()) {
list.remove(*this);
}
}
};
const unsigned capacity_;
unsigned used_ = 0;
kj::List<Waiter, &Waiter::link> waiters;
void unsafeRelease()
{
used_ -= 1;
while (used_ < capacity_ && !waiters.empty()) {
used_ += 1;
auto & w = waiters.front();
w.fulfiller.fulfill(Token{*this, {}});
waiters.remove(w);
}
}
public:
explicit AsyncSemaphore(unsigned capacity) : capacity_(capacity) {}
KJ_DISALLOW_COPY_AND_MOVE(AsyncSemaphore);
~AsyncSemaphore()
{
assert(waiters.empty() && "destroyed a semaphore with active waiters");
}
std::optional<Token> tryAcquire()
{
if (used_ < capacity_) {
used_ += 1;
return Token{*this, {}};
} else {
return {};
}
}
kj::Promise<Token> acquire()
{
if (auto t = tryAcquire()) {
return std::move(*t);
} else {
return kj::newAdaptedPromise<Token, Waiter>(waiters);
}
}
unsigned capacity() const
{
return capacity_;
}
unsigned used() const
{
return used_;
}
unsigned available() const
{
return capacity_ - used_;
}
};
}

View file

@ -144,7 +144,6 @@ struct BrotliDecompressionSource : Source
std::unique_ptr<char[]> buf; std::unique_ptr<char[]> buf;
size_t avail_in = 0; size_t avail_in = 0;
const uint8_t * next_in; const uint8_t * next_in;
std::exception_ptr inputEofException = nullptr;
Source * inner; Source * inner;
std::unique_ptr<BrotliDecoderState, void (*)(BrotliDecoderState *)> state; std::unique_ptr<BrotliDecoderState, void (*)(BrotliDecoderState *)> state;
@ -168,42 +167,23 @@ struct BrotliDecompressionSource : Source
while (len && !BrotliDecoderIsFinished(state.get())) { while (len && !BrotliDecoderIsFinished(state.get())) {
checkInterrupt(); checkInterrupt();
while (avail_in == 0 && inputEofException == nullptr) { while (avail_in == 0) {
try { try {
avail_in = inner->read(buf.get(), BUF_SIZE); avail_in = inner->read(buf.get(), BUF_SIZE);
} catch (EndOfFile &) { } catch (EndOfFile &) {
// No more data, but brotli may still have output remaining
// from the last call.
inputEofException = std::current_exception();
break; break;
} }
next_in = charptr_cast<const uint8_t *>(buf.get()); next_in = charptr_cast<const uint8_t *>(buf.get());
} }
BrotliDecoderResult res = BrotliDecoderDecompressStream( if (!BrotliDecoderDecompressStream(
state.get(), &avail_in, &next_in, &len, &out, nullptr state.get(), &avail_in, &next_in, &len, &out, nullptr
); ))
{
switch (res) {
case BROTLI_DECODER_RESULT_SUCCESS:
// We're done here!
goto finish;
case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
// Grab more input. Don't try if we already have exhausted our input stream.
if (inputEofException != nullptr) {
std::rethrow_exception(inputEofException);
} else {
continue;
}
case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:
// Need more output space: we can only get another buffer by someone calling us again, so get out.
goto finish;
case BROTLI_DECODER_RESULT_ERROR:
throw CompressionError("error while decompressing brotli file"); throw CompressionError("error while decompressing brotli file");
} }
} }
finish:
if (begin != out) { if (begin != out) {
return out - begin; return out - begin;
} else { } else {

View file

@ -49,7 +49,7 @@ unsigned int getMaxCPU()
auto period = cpuMaxParts[1]; auto period = cpuMaxParts[1];
if (quota != "max") if (quota != "max")
return std::ceil(std::stoi(quota) / std::stof(period)); return std::ceil(std::stoi(quota) / std::stof(period));
} catch (Error &) { ignoreExceptionInDestructor(lvlDebug); } } catch (Error &) { ignoreException(lvlDebug); }
#endif #endif
return 0; return 0;

View file

@ -4,7 +4,6 @@
#include "position.hh" #include "position.hh"
#include "terminal.hh" #include "terminal.hh"
#include "strings.hh" #include "strings.hh"
#include "signals.hh"
#include <iostream> #include <iostream>
#include <optional> #include <optional>
@ -417,7 +416,7 @@ std::ostream & showErrorInfo(std::ostream & out, const ErrorInfo & einfo, bool s
return out; return out;
} }
void ignoreExceptionInDestructor(Verbosity lvl) void ignoreException(Verbosity lvl)
{ {
/* Make sure no exceptions leave this function. /* Make sure no exceptions leave this function.
printError() also throws when remote is closed. */ printError() also throws when remote is closed. */
@ -430,15 +429,4 @@ void ignoreExceptionInDestructor(Verbosity lvl)
} catch (...) { } } catch (...) { }
} }
void ignoreExceptionExceptInterrupt(Verbosity lvl)
{
try {
throw;
} catch (const Interrupted & e) {
throw;
} catch (std::exception & e) {
printMsg(lvl, "error (ignored): %1%", e.what());
}
}
} }

View file

@ -204,22 +204,7 @@ public:
/** /**
* Exception handling in destructors: print an error message, then * Exception handling in destructors: print an error message, then
* ignore the exception. * ignore the exception.
*
* If you're not in a destructor, you usually want to use `ignoreExceptionExceptInterrupt()`.
*
* This function might also be used in callbacks whose caller may not handle exceptions,
* but ideally we propagate the exception using an exception_ptr in such cases.
* See e.g. `PackBuilderContext`
*/ */
void ignoreExceptionInDestructor(Verbosity lvl = lvlError); void ignoreException(Verbosity lvl = lvlError);
/**
* Not destructor-safe.
* Print an error message, then ignore the exception.
* If the exception is an `Interrupted` exception, rethrow it.
*
* This may be used in a few places where Interrupt can't happen, but that's ok.
*/
void ignoreExceptionExceptInterrupt(Verbosity lvl = lvlError);
} }

View file

@ -247,7 +247,7 @@ constexpr std::array<ExperimentalFeatureDetails, numXpFeatures> xpFeatureDetails
.tag = Xp::ReplAutomation, .tag = Xp::ReplAutomation,
.name = "repl-automation", .name = "repl-automation",
.description = R"( .description = R"(
Makes the repl not use editline, print ENQ (U+0005) when ready for a command, and take commands followed by newline. Makes the repl not use readline/editline, print ENQ (U+0005) when ready for a command, and take commands followed by newline.
)", )",
}, },
}}; }};

View file

@ -146,7 +146,7 @@ AutoCloseFD::~AutoCloseFD()
try { try {
close(); close();
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -18,19 +18,15 @@ namespace fs = std::filesystem;
namespace nix { namespace nix {
Path getCwd() {
char buf[PATH_MAX];
if (!getcwd(buf, sizeof(buf))) {
throw SysError("cannot get cwd");
}
return Path(buf);
}
Path absPath(Path path, std::optional<PathView> dir, bool resolveSymlinks) Path absPath(Path path, std::optional<PathView> dir, bool resolveSymlinks)
{ {
if (path.empty() || path[0] != '/') { if (path.empty() || path[0] != '/') {
if (!dir) { if (!dir) {
path = concatStrings(getCwd(), "/", path); char buf[PATH_MAX];
if (!getcwd(buf, sizeof(buf))) {
throw SysError("cannot get cwd");
}
path = concatStrings(buf, "/", path);
} else { } else {
path = concatStrings(*dir, "/", path); path = concatStrings(*dir, "/", path);
} }
@ -522,7 +518,7 @@ AutoDelete::~AutoDelete()
} }
} }
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -29,13 +29,6 @@ namespace nix {
struct Sink; struct Sink;
struct Source; struct Source;
/**
* Get the current working directory.
*
* Throw an error if the current directory cannot get got.
*/
Path getCwd();
/** /**
* @return An absolutized path, resolving paths relative to the * @return An absolutized path, resolving paths relative to the
* specified directory, or the current directory otherwise. The path * specified directory, or the current directory otherwise. The path
@ -210,7 +203,7 @@ inline Paths createDirs(PathView path)
} }
/** /**
* Create a symlink. Throws if the symlink exists. * Create a symlink.
*/ */
void createSymlink(const Path & target, const Path & link); void createSymlink(const Path & target, const Path & link);

View file

@ -136,17 +136,11 @@ inline std::string fmt(const char * s)
template<typename... Args> template<typename... Args>
inline std::string fmt(const std::string & fs, const Args &... args) inline std::string fmt(const std::string & fs, const Args &... args)
try { {
boost::format f(fs); boost::format f(fs);
fmt_internal::setExceptions(f); fmt_internal::setExceptions(f);
(f % ... % args); (f % ... % args);
return f.str(); return f.str();
} catch (boost::io::format_error & fe) {
// I don't care who catches this, we do not put up with boost format errors
// Give me a stack trace and a core dump
std::cerr << "nix::fmt threw format error. Original format string: '";
std::cerr << fs << "'; number of arguments: " << sizeof...(args) << "\n";
std::terminate();
} }
/** /**
@ -180,13 +174,15 @@ public:
std::cerr << "HintFmt received incorrect number of format args. Original format string: '"; std::cerr << "HintFmt received incorrect number of format args. Original format string: '";
std::cerr << format << "'; number of arguments: " << sizeof...(args) << "\n"; std::cerr << format << "'; number of arguments: " << sizeof...(args) << "\n";
// And regardless of the coredump give me a damn stacktrace. // And regardless of the coredump give me a damn stacktrace.
std::terminate(); printStackTrace();
abort();
} }
} catch (boost::io::format_error & ex) { } catch (boost::io::format_error & ex) {
// Same thing, but for anything that happens in the member initializers. // Same thing, but for anything that happens in the member initializers.
std::cerr << "HintFmt received incorrect format string. Original format string: '"; std::cerr << "HintFmt received incorrect format string. Original format string: '";
std::cerr << format << "'; number of arguments: " << sizeof...(args) << "\n"; std::cerr << format << "'; number of arguments: " << sizeof...(args) << "\n";
std::terminate(); printStackTrace();
abort();
} }
HintFmt(const HintFmt & hf) : fmt(hf.fmt) {} HintFmt(const HintFmt & hf) : fmt(hf.fmt) {}

View file

@ -352,7 +352,7 @@ Activity::~Activity()
try { try {
logger.stopActivity(id); logger.stopActivity(id);
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -53,8 +53,6 @@ libutil_headers = files(
'archive.hh', 'archive.hh',
'args/root.hh', 'args/root.hh',
'args.hh', 'args.hh',
'async-collect.hh',
'async-semaphore.hh',
'backed-string-view.hh', 'backed-string-view.hh',
'box_ptr.hh', 'box_ptr.hh',
'canon-path.hh', 'canon-path.hh',
@ -107,7 +105,6 @@ libutil_headers = files(
'regex-combinators.hh', 'regex-combinators.hh',
'regex.hh', 'regex.hh',
'repair-flag.hh', 'repair-flag.hh',
'result.hh',
'serialise.hh', 'serialise.hh',
'shlex.hh', 'shlex.hh',
'signals.hh', 'signals.hh',

View file

@ -1,24 +0,0 @@
#pragma once
/// @file
#include <boost/outcome/std_outcome.hpp>
#include <boost/outcome/std_result.hpp>
#include <boost/outcome/success_failure.hpp>
#include <exception>
namespace nix {
template<typename T, typename E = std::exception_ptr>
using Result = boost::outcome_v2::std_result<T, E>;
template<typename T, typename D, typename E = std::exception_ptr>
using Outcome = boost::outcome_v2::std_outcome<T, D, E>;
namespace result {
using boost::outcome_v2::success;
using boost::outcome_v2::failure;
}
}

View file

@ -83,7 +83,7 @@ void BufferedSink::flush()
FdSink::~FdSink() FdSink::~FdSink()
{ {
try { flush(); } catch (...) { ignoreExceptionInDestructor(); } try { flush(); } catch (...) { ignoreException(); }
} }

View file

@ -77,11 +77,6 @@ struct Source
* Store up to len in the buffer pointed to by data, and * Store up to len in the buffer pointed to by data, and
* return the number of bytes stored. It blocks until at least * return the number of bytes stored. It blocks until at least
* one byte is available. * one byte is available.
*
* Should not return 0 (generally you want to throw EndOfFile), but nothing
* stops that.
*
* \throws EndOfFile if there is no more data.
*/ */
virtual size_t read(char * data, size_t len) = 0; virtual size_t read(char * data, size_t len) = 0;
@ -549,7 +544,7 @@ struct FramedSource : Source
} }
} }
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
@ -595,7 +590,7 @@ struct FramedSink : nix::BufferedSink
to << 0; to << 0;
to.flush(); to.flush();
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }

View file

@ -12,18 +12,13 @@ std::atomic<bool> _isInterrupted = false;
thread_local std::function<bool()> interruptCheck; thread_local std::function<bool()> interruptCheck;
Interrupted makeInterrupted()
{
return Interrupted("interrupted by the user");
}
void _interrupted() void _interrupted()
{ {
/* Block user interrupts while an exception is being handled. /* Block user interrupts while an exception is being handled.
Throwing an exception while another exception is being handled Throwing an exception while another exception is being handled
kills the program! */ kills the program! */
if (!std::uncaught_exceptions()) { if (!std::uncaught_exceptions()) {
throw makeInterrupted(); throw Interrupted("interrupted by the user");
} }
} }
@ -83,7 +78,7 @@ void triggerInterrupt()
try { try {
callback(); callback();
} catch (...) { } catch (...) {
ignoreExceptionInDestructor(); ignoreException();
} }
} }
} }

View file

@ -16,13 +16,10 @@ namespace nix {
/* User interruption. */ /* User interruption. */
class Interrupted;
extern std::atomic<bool> _isInterrupted; extern std::atomic<bool> _isInterrupted;
extern thread_local std::function<bool()> interruptCheck; extern thread_local std::function<bool()> interruptCheck;
Interrupted makeInterrupted();
void _interrupted(); void _interrupted();
void inline checkInterrupt() void inline checkInterrupt()

View file

@ -200,18 +200,8 @@ std::string showBytes(uint64_t bytes);
/** /**
* Provide an addition operator between `std::string` and `std::string_view` * Provide an addition operator between strings and string_views
* inexplicably omitted from the standard library. * inexplicably omitted from the standard library.
*
* > The reason for this is given in n3512 string_ref: a non-owning reference
* to a string, revision 2 by Jeffrey Yasskin:
* >
* > > I also omitted operator+(basic_string, basic_string_ref) because LLVM
* > > returns a lightweight object from this overload and only performs the
* > > concatenation lazily. If we define this overload, we'll have a hard time
* > > introducing that lightweight concatenation later.
*
* See: https://stackoverflow.com/a/47735624
*/ */
inline std::string operator + (const std::string & s1, std::string_view s2) inline std::string operator + (const std::string & s1, std::string_view s2)
{ {

View file

@ -109,8 +109,9 @@ void ThreadPool::doWork(bool mainThread)
try { try {
std::rethrow_exception(exc); std::rethrow_exception(exc);
} catch (std::exception & e) { } catch (std::exception & e) {
if (!dynamic_cast<ThreadPoolShutDown*>(&e)) if (!dynamic_cast<Interrupted*>(&e) &&
ignoreExceptionExceptInterrupt(); !dynamic_cast<ThreadPoolShutDown*>(&e))
ignoreException();
} catch (...) { } catch (...) {
} }
} }

View file

@ -1 +1,5 @@
fs.copyfile('unpack-channel.nix') configure_file(
input : 'unpack-channel.nix',
output : 'unpack-channel.nix',
copy : true,
)

View file

@ -639,7 +639,7 @@ struct CmdDevelop : Common, MixEnvironment
throw Error("package 'nixpkgs#bashInteractive' does not provide a 'bin/bash'"); throw Error("package 'nixpkgs#bashInteractive' does not provide a 'bin/bash'");
} catch (Error &) { } catch (Error &) {
ignoreExceptionExceptInterrupt(); ignoreException();
} }
// Override SHELL with the one chosen for this environment. // Override SHELL with the one chosen for this environment.

View file

@ -16,7 +16,6 @@
#include "eval-cache.hh" #include "eval-cache.hh"
#include "markdown.hh" #include "markdown.hh"
#include "terminal.hh" #include "terminal.hh"
#include "signals.hh"
#include <limits> #include <limits>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
@ -368,11 +367,9 @@ struct CmdFlakeCheck : FlakeCommand
auto reportError = [&](const Error & e) { auto reportError = [&](const Error & e) {
try { try {
throw e; throw e;
} catch (Interrupted & e) {
throw;
} catch (Error & e) { } catch (Error & e) {
if (settings.keepGoing) { if (settings.keepGoing) {
ignoreExceptionExceptInterrupt(); ignoreException();
hasErrors = true; hasErrors = true;
} }
else else

View file

@ -39,8 +39,14 @@ struct CmdFmt : SourceExprCommand {
Strings programArgs{app.program}; Strings programArgs{app.program};
// Propagate arguments from the CLI // Propagate arguments from the CLI
for (auto &i : args) { if (args.empty()) {
programArgs.push_back(i); // Format the current flake out of the box
programArgs.push_back(".");
} else {
// User wants more power, let them decide which paths to include/exclude
for (auto &i : args) {
programArgs.push_back(i);
}
} }
runProgramInStore(store, UseSearchPath::DontUse, app.program, programArgs); runProgramInStore(store, UseSearchPath::DontUse, app.program, programArgs);

View file

@ -353,9 +353,6 @@ void mainWrapped(int argc, char * * argv)
argv++; argc--; argv++; argc--;
} }
// Clean up the progress bar if shown using --log-format in a legacy command too.
// Otherwise, this is a harmless no-op.
Finally f([] { logger->pause(); });
{ {
auto legacy = (*RegisterLegacyCommand::commands)[programName]; auto legacy = (*RegisterLegacyCommand::commands)[programName];
if (legacy) return legacy(argc, argv); if (legacy) return legacy(argc, argv);
@ -364,6 +361,7 @@ void mainWrapped(int argc, char * * argv)
evalSettings.pureEval = true; evalSettings.pureEval = true;
setLogFormat(LogFormat::bar); setLogFormat(LogFormat::bar);
Finally f([] { logger->pause(); });
settings.verboseBuild = false; settings.verboseBuild = false;
// FIXME: stop messing about with log verbosity depending on if it is interactive use // FIXME: stop messing about with log verbosity depending on if it is interactive use
if (isatty(STDERR_FILENO)) { if (isatty(STDERR_FILENO)) {

View file

@ -82,10 +82,6 @@ struct CmdPathInfo : StorePathsCommand, MixJSON
void run(ref<Store> store, StorePaths && storePaths) override void run(ref<Store> store, StorePaths && storePaths) override
{ {
// Wipe the progress bar to prevent interference with the output.
// It's not needed any more because expensive evaluation or builds are already done here.
logger->pause();
size_t pathLen = 0; size_t pathLen = 0;
for (auto & storePath : storePaths) for (auto & storePath : storePaths)
pathLen = std::max(pathLen, store->printStorePath(storePath).size()); pathLen = std::max(pathLen, store->printStorePath(storePath).size());

View file

@ -144,10 +144,13 @@ test "$(<<<"$out" grep -E '^error:' | wc -l)" = 1
# --keep-going and FOD # --keep-going and FOD
out="$(nix build -f fod-failing.nix -L 2>&1)" && status=0 || status=$? out="$(nix build -f fod-failing.nix -L 2>&1)" && status=0 || status=$?
test "$status" = 1 test "$status" = 1
# at least one "hash mismatch" error, one "build of ... failed" # one "hash mismatch" error, one "build of ... failed"
test "$(<<<"$out" grep -E '^error:' | wc -l)" -ge 2 test "$(<<<"$out" grep -E '^error:' | wc -l)" = 2
<<<"$out" grepQuiet -E "hash mismatch in fixed-output derivation '.*-x.\\.drv'" <<<"$out" grepQuiet -E "hash mismatch in fixed-output derivation '.*-x1\\.drv'"
<<<"$out" grepQuiet -E "likely URL: " <<<"$out" grepQuiet -vE "hash mismatch in fixed-output derivation '.*-x3\\.drv'"
<<<"$out" grepQuiet -vE "hash mismatch in fixed-output derivation '.*-x2\\.drv'"
<<<"$out" grepQuiet -E "likely URL: https://meow.puppy.forge/puppy.tar.gz"
<<<"$out" grepQuiet -vE "likely URL: https://kitty.forge/cat.tar.gz"
<<<"$out" grepQuiet -E "error: build of '.*-x[1-4]\\.drv\\^out', '.*-x[1-4]\\.drv\\^out', '.*-x[1-4]\\.drv\\^out', '.*-x[1-4]\\.drv\\^out' failed" <<<"$out" grepQuiet -E "error: build of '.*-x[1-4]\\.drv\\^out', '.*-x[1-4]\\.drv\\^out', '.*-x[1-4]\\.drv\\^out', '.*-x[1-4]\\.drv\\^out' failed"
out="$(nix build -f fod-failing.nix -L x1 x2 x3 --keep-going 2>&1)" && status=0 || status=$? out="$(nix build -f fod-failing.nix -L x1 x2 x3 --keep-going 2>&1)" && status=0 || status=$?
@ -164,9 +167,9 @@ test "$(<<<"$out" grep -E '^error:' | wc -l)" = 4
out="$(nix build -f fod-failing.nix -L x4 2>&1)" && status=0 || status=$? out="$(nix build -f fod-failing.nix -L x4 2>&1)" && status=0 || status=$?
test "$status" = 1 test "$status" = 1
test "$(<<<"$out" grep -E '^error:' | wc -l)" -ge 2 test "$(<<<"$out" grep -E '^error:' | wc -l)" = 2
<<<"$out" grepQuiet -E "error: [12] dependencies of derivation '.*-x4\\.drv' failed to build" <<<"$out" grepQuiet -E "error: 1 dependencies of derivation '.*-x4\\.drv' failed to build"
<<<"$out" grepQuiet -E "hash mismatch in fixed-output derivation '.*-x[23]\\.drv'" <<<"$out" grepQuiet -E "hash mismatch in fixed-output derivation '.*-x2\\.drv'"
out="$(nix build -f fod-failing.nix -L x4 --keep-going 2>&1)" && status=0 || status=$? out="$(nix build -f fod-failing.nix -L x4 --keep-going 2>&1)" && status=0 || status=$?
test "$status" = 1 test "$status" = 1

View file

@ -53,17 +53,8 @@ out=$(nix eval --impure --raw --expr "builtins.fetchGit { url = \"file://$repo\"
[[ $status == 1 ]] [[ $status == 1 ]]
[[ $out =~ 'Cannot find Git revision' ]] [[ $out =~ 'Cannot find Git revision' ]]
# allow revs as refs (for 2.3 compat)
[[ $(nix eval --raw --expr "builtins.readFile (builtins.fetchGit { url = \"file://$repo\"; rev = \"$devrev\"; allRefs = true; } + \"/differentbranch\")") = 'different file' ]] [[ $(nix eval --raw --expr "builtins.readFile (builtins.fetchGit { url = \"file://$repo\"; rev = \"$devrev\"; allRefs = true; } + \"/differentbranch\")") = 'different file' ]]
rm -rf "$TEST_ROOT/test-home"
[[ $(nix eval --raw --expr "builtins.readFile (builtins.fetchGit { url = \"file://$repo\"; rev = \"$devrev\"; allRefs = true; } + \"/differentbranch\")") = 'different file' ]]
rm -rf "$TEST_ROOT/test-home"
out=$(nix eval --raw --expr "builtins.readFile (builtins.fetchGit { url = \"file://$repo\"; rev = \"$devrev\"; ref = \"lolkek\"; } + \"/differentbranch\")" 2>&1) || status=$?
[[ $status == 1 ]]
[[ $out =~ 'Cannot find Git revision' ]]
# In pure eval mode, fetchGit without a revision should fail. # In pure eval mode, fetchGit without a revision should fail.
[[ $(nix eval --impure --raw --expr "builtins.readFile (fetchGit \"file://$repo\" + \"/hello\")") = world ]] [[ $(nix eval --impure --raw --expr "builtins.readFile (fetchGit \"file://$repo\" + \"/hello\")") = world ]]
(! nix eval --raw --expr "builtins.readFile (fetchGit \"file://$repo\" + \"/hello\")") (! nix eval --raw --expr "builtins.readFile (fetchGit \"file://$repo\" + \"/hello\")")
@ -237,12 +228,6 @@ export _NIX_FORCE_HTTP=1
rev_tag1_nix=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = \"file://$repo\"; ref = \"refs/tags/tag1\"; }).rev") rev_tag1_nix=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = \"file://$repo\"; ref = \"refs/tags/tag1\"; }).rev")
rev_tag1=$(git -C $repo rev-parse refs/tags/tag1) rev_tag1=$(git -C $repo rev-parse refs/tags/tag1)
[[ $rev_tag1_nix = $rev_tag1 ]] [[ $rev_tag1_nix = $rev_tag1 ]]
# Allow fetching tags w/o specifying refs/tags
rm -rf "$TEST_ROOT/test-home"
rev_tag1_nix_alt=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = \"file://$repo\"; ref = \"tag1\"; }).rev")
[[ $rev_tag1_nix_alt = $rev_tag1 ]]
rev_tag2_nix=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = \"file://$repo\"; ref = \"refs/tags/tag2\"; }).rev") rev_tag2_nix=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = \"file://$repo\"; ref = \"refs/tags/tag2\"; }).rev")
rev_tag2=$(git -C $repo rev-parse refs/tags/tag2) rev_tag2=$(git -C $repo rev-parse refs/tags/tag2)
[[ $rev_tag2_nix = $rev_tag2 ]] [[ $rev_tag2_nix = $rev_tag2 ]]
@ -269,33 +254,3 @@ git -C "$repo" add hello .gitignore
git -C "$repo" commit -m 'Bla1' git -C "$repo" commit -m 'Bla1'
cd "$repo" cd "$repo"
path11=$(nix eval --impure --raw --expr "(builtins.fetchGit ./.).outPath") path11=$(nix eval --impure --raw --expr "(builtins.fetchGit ./.).outPath")
# test behavior if both branch and tag with same name exist
repo="$TEST_ROOT/git"
rm -rf "$repo"/.git
git init "$repo"
git -C "$repo" config user.email "foobar@example.com"
git -C "$repo" config user.name "Foobar"
touch "$repo"/test
echo "hello world" > "$repo"/test
git -C "$repo" checkout -b branch
git -C "$repo" add test
git -C "$repo" commit -m "Init"
git -C "$repo" tag branch
echo "goodbye world" > "$repo"/test
git -C "$repo" add test
git -C "$repo" commit -m "Update test"
path12=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = \"file://$repo\"; ref = \"branch\"; }).outPath")
[[ "$(cat "$path12"/test)" =~ 'hello world' ]]
[[ "$(cat "$repo"/test)" =~ 'goodbye world' ]]
path13=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = \"file://$repo\"; ref = \"refs/heads/branch\"; }).outPath")
[[ "$(cat "$path13"/test)" =~ 'goodbye world' ]]
path14=$(nix eval --impure --raw --expr "(builtins.fetchGit { url = \"file://$repo\"; ref = \"refs/tags/branch\"; }).outPath")
[[ "$path14" = "$path12" ]]

View file

@ -26,10 +26,7 @@ cat << EOF > flake.nix
}; };
} }
EOF EOF
# No arguments check nix fmt ./file ./folder | grep 'Formatting: ./file ./folder'
[[ "$(nix fmt)" = "Formatting(0):" ]]
# Argument forwarding check
nix fmt ./file ./folder | grep 'Formatting(2): ./file ./folder'
nix flake check nix flake check
nix flake show | grep -P "package 'formatter'" nix flake show | grep -P "package 'formatter'"

View file

@ -1,3 +1,3 @@
#!/usr/bin/env bash #!/usr/bin/env bash
echo "Formatting(${#}):" "${@}" echo Formatting: "${@}"

Some files were not shown because too many files have changed in this diff Show more