Skip to content

Overhaul process reaping and terminal control - #5219

Merged
mqudsi merged 17 commits into
fish-shell:masterfrom
mqudsi:keep_zombies
Oct 27, 2018
Merged

mqudsi merged 17 commits into
fish-shell:masterfrom
mqudsi:keep_zombies

Conversation

@mqudsi

@mqudsi mqudsi commented Sep 29, 2018 •

Copy link
Copy Markdown
Contributor

I believe this finally safely does away with the keepalive process. I think the problem is that we were waiting on all child processes in process_mark_finished_children which caused premature reaping of terminated processes before their process group could be joined by new processes in the same job.

Additionally, there was a deadlock in try_select that didn't show up until that change was made.

This should fix #4178 (which manifests in two entirely different ways depending on whether connected over SSH and FreeBSD vs Linux) and quite likely some other issues as well.

This branch should likely be squash-merged.


Partially addresses #206.

Closes #3805. Closes #3952. Closes #4178. Closes #4238. Closes #4929. Closes #5210.

@mqudsi

mqudsi commented Sep 30, 2018 •

Copy link
Copy Markdown
Contributor Author

Also fixes #3952

EDIT: No, it doesn't.

EDIT: It does now. 🎉

@mqudsi

mqudsi commented Sep 30, 2018

Copy link
Copy Markdown
Contributor Author

Also fixes #3805

@mqudsi

mqudsi commented Sep 30, 2018

Copy link
Copy Markdown
Contributor Author

Also fixes #5210

@faho faho added the bug Something that's not working as intended label Sep 30, 2018
@faho faho added this to the fish-3.0 milestone Sep 30, 2018
@mqudsi

mqudsi commented Sep 30, 2018

Copy link
Copy Markdown
Contributor Author

@ridiculousfish @krader1961 any thoughts?

I've installed this branch as my main driver on my FreeBSD, WSL, and now macOS as it appears to include some highly platform-specific behavior. Would appreciate if others could try it out for a few days, you never know where edge cases can pop up.

@faho

faho commented Sep 30, 2018

Copy link
Copy Markdown
Member

Instead of reaping all child processes when we receive a SIGCHLD, try
reaping only processes belonging to process groups from
fully-constructed jobs.

This basic idea seems entirely logical to me, and I struggle to think how that would make it any worse. Are there cases where that now doesn't reap a process at all? Is it a problem to leave unreaped jobs around for a bit?

I don't think so, but this stuff is full of weird edges and spooky corners.


I've done some cursory testing, and I can confirm that #5210 seems to be solved. I can't confirm #3952, and that should still be an issue.

The case there is:

sudo echo lol | grep lol

with grep being a function. The big problem is that that is two separate jobs, because fish forgets the current job as soon as it executes the function. Which is something separate from the keepalive stuff, but not made worse by it either.

@faho

faho commented Sep 30, 2018

Copy link
Copy Markdown
Member

I can confirm #3805 as fixed, pgroup-wise.

@mqudsi

mqudsi commented Sep 30, 2018 •

Copy link
Copy Markdown
Contributor Author

Thanks for testing, @faho.

There is no problem in keeping the zombie processes unreaped until the job is constructed, but the problem is whether or not the reaping function is executed at the right places, because when a process is reaped it changes the internal state of the job, and select_try would hang when it is waiting for IO that never comes becomes and it deadlocks waiting for the job to change state (which never happens).

Previously a process from one job would be reaped when the other job was being monitored, causing the select_try to "get lucky" and progress.


That's weird, I tested #3952 it yesterday (it even came up in the autosuggest from history) but you're right, it is indeed not fixed.

mqudsi@ZBook /m/c/U/m/r/fish-shell> function grep
                                        command grep --color=auto
                                    end
mqudsi@ZBook /m/c/U/m/r/fish-shell> sudo echo lol | grep lol
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.

@faho

faho commented Sep 30, 2018 •

Copy link
Copy Markdown
Member

That's weird, I tested #3952 it yesterday (it even came up in the autosuggest from history) but you're right, it is indeed not fixed.

There is a timing component to it, so you probably just got an unlucky false-positive.

@mqudsi

mqudsi commented Sep 30, 2018

Copy link
Copy Markdown
Contributor Author

I also changed the debug levels of some tracing output so that -d3 can be used for sanely debugging job status and progression.

@faho

faho commented Sep 30, 2018

Copy link
Copy Markdown
Member

I also changed the debug levels of some tracing output so that -d3 can be used for sanely debugging job status and progression.

Ooh yes. Last I looked, the most spammy part was input - "checking X against mapping Y" or something - but I think I already increased the level on that.

I still believe something like #4818 or a file-based thing (fish --debug=input,reader to get messages from input.cpp and reader.cpp) would be better, but we're a bit too chatty in low levels in general.

@mqudsi

mqudsi commented Sep 30, 2018 •

Copy link
Copy Markdown
Contributor Author

😄 Yeah, it was the key binding mapping that would print page after page of output.

I like the file-based debug idea.

Comment thread src/input.cpp Resolved
Comment thread src/parse_execution.cpp Resolved
Comment thread src/postfork.cpp Resolved
Comment thread src/proc.cpp Resolved
Comment thread src/proc.cpp Resolved
Comment thread src/reader.cpp Resolved
Comment thread src/reader.cpp Resolved
@ridiculousfish

Copy link
Copy Markdown
Member

I'd be totally thrilled to eliminate the keepalive process. I hope this works!!

I think I understand the theory of this PR. Before we would create a keep-alive process, and kill it once the job is constructed. With this PR, we no longer construct a keep-alive. Rather we allow the pgroup to become a zombie, and just delay reaping it by never calling waitpid(), only waiting on certain processes. That's pretty clever. I understand old WSL did not support this (zombies were not a WSL thing), but this was recently improved to make zombie processes real, so this might really work.

The tricky part is that waitpid() is not like select(): you can wait for THIS PARTICULAR child, or wait for ANY child, but not wait for a set of children. If you disallow waiting for ANY child, you might wind up waiting on a long-lived background process and thereby hang. So how do we ensure we aren't waiting for a background process?

I think the reason this works is as follows: parser_t puts new jobs at the beginning of the job list, and there can only be one constructed foreground job. We only call wait() after adding a foreground job, so we never end up waiting on a background job. So that's working by accident the job list happens to put new jobs at the beginning. Yet I think this has hit onto something really great.

I'd like to see the following:

  1. process_mark_finished_children currently takes one parameter, wants_await. Let's change it to block_on_foreground. If that's set, this happens:
    a. It asserts that there's at most one job that's foreground AND constructed.
    b. If there is such a job, wait on that job with WNOHANG = 0 (i.e. allow it to block).
    c. For every background job, wait with WNOHANG set.

  2. This PR currently has 9 commits, some of which seem to be fixes for previous commits. Can you please clean this up into reviewable chunks? For example I see commented-out code like // needs_keepalive = true, we shouldn't have that sort of thing (we shouldn't have needs_keepalive at all if this works!) git rebase -i is a good tool for this sort of cleanup.

  3. There's multiple uses of -2 to mean a not-yet constructed job, I think it's time to introduce a constant for this!

  4. proc_wait_any() invoked from builtin_wait is going to be a problem. In particular if you call builtin wait from within a function and the function is in a pipeline, you may end up reaping the keepalive process. (We'll want to add a test case for this.)

@zanchey

zanchey commented Oct 1, 2018

Copy link
Copy Markdown
Member

There's multiple uses of -2 to mean a not-yet constructed job, I think it's time to introduce a constant for this!

I think that's my fault, and yes - well past time.

@mqudsi

mqudsi commented Oct 1, 2018 •

Copy link
Copy Markdown
Contributor Author

Thanks for chiming in, everyone.

@ridiculousfish I'm with you on your suggestions for further improving this, but just some notes.

Rather we allow the pgroup to become a zombie, and just delay reaping it by never calling waitpid(), only waiting on certain processes.

Well, I'm still calling waitpid, but rather than calling waitpid(-1, ...) to wait on any child process after a SIGCHLD is raised, we iterate through all constructed jobs and selectively waitpid on the job's pgid (line 427 in proc.cpp, waitpid(-1 * j->pgid, ...)) guaranteeing that even if SIGCHLD were raised by the death of a child process belonging to a still-in-construction job, that particular process won't be reaped. The downside is that some SIGCHLD signals are ignored which ended up causing a deadlock in select_try when a child process dies before the job is fully constructed and it ended up being never reaped. However, we have logic in place elsewhere that detected the case where a process group has become empty, which was then enhanced with the ability to mark the job as complete, thereby working around that limitation.

If you disallow waiting for ANY child, you might wind up waiting on a long-lived background process and thereby hang. So how do we ensure we aren't waiting for a background process?

select_try selectively calls process_mark_finished_children with a parameter that will dictate whether any calls to waitpid are made. The logic there in firing process_mark_finished_children (somehow) avoids that situation.

So that's working by accident the job list happens to put new jobs at the beginning.

I see where you're going with that. I'm not entirely sure it's simple chance as the existing code runs waitpid in a loop (with NOHANG though) where after each child process is reaped, it goes on to the next job/process in the list, so it's actually not getting lucky in that the first child collected is not a long-running task and then proceeding on its merry way.

I won't even pretend to fully understand the marriage between process_mark_finished_children and select_try, there's a lot of voodoo there. But the mixture of the logic in the two appears to be responsible for protecting against these horror cases.

I'd like to see the following:

  1. process_mark_finished_children currently takes one parameter, wants_await. Let's change it to block_on_foreground. If that's set, this happens:
    a. It asserts that there's at most one job that's foreground AND constructed.
    b. If there is such a job, wait on that job with WNOHANG = 0 (i.e. allow it to block).
    c. For every background job, wait with WNOHANG set.

This is much cleaner than the current logic, and it actually makes sense. Just a note that there is an existing assert somewhere about "maximum one foreground job" (though I don't think it considers fully constructed vs in construction), as I triggered that at some point in this branch before implementing the code that properly catches a fully-terminated pgroup and marking the job as complete in such a case.

  1. This PR currently has 9 commits, some of which seem to be fixes for previous commits. Can you please clean this up into reviewable chunks? [..] git rebase -i is a good tool for this sort of cleanup.

The original plan was to merge this via a squash commit, hence the liberal unrebased commits and the the chatty commit messages. If we end up making changes beyond what's already been changed then it definitely should be rebased, yes.

  1. [..] For example I see commented-out code like // needs_keepalive = true, we shouldn't have that sort of thing (we shouldn't have needs_keepalive at all if this works!)

Well, no released version of WSL aside from current slow- and fast-track Windows Insider builds feature the fix in question so we'll want to keep the keepalive process around at least until the next feature update. (The latest released stable update is at 17134, the fix is in 17713.) But agreed on the commented-out code.

  1. There's multiple uses of -2 to mean a not-yet constructed job, I think it's time to introduce a constant for this!

All for that. And converting c-bools to either proper booleans or flags combined with job_t::has_flag() (or eliminating flags entirely in favor of booleans. Perhaps the latter as the only reason to use flags is either mutual exclusivity or memory constraints and it's not really envisionable that we'll ever have enough jobs (and not run into other problems first) such that the memory overhead of individual 8-bit boolean fields will be a problem).

  1. proc_wait_any() invoked from builtin_wait is going to be a problem. In particular if you call builtin wait from within a function and the function is in a pipeline, you may end up reaping the keepalive process. (We'll want to add a test case for this.)

Very good catch! Ironically, I don't think that's a problem right now because of another fish job control bug where functions trigger additional jobs, but that's definitely something to keep in mind. We'd probably have to convert that function into a synchronized lock-step routine wherein it sets a flag that causes process_mark_finished_children to release a condition variable allowing the wait to proceed (I'm presuming proc_wait_any() would be called from a forked child as otherwise we'd have bigger problems). Note that we've avoided any and all IPC between forked fish instances, given the lack of named mutexes and condition variables in the pthreads api we'd probably have to stick a mutex in a shared memory section (or else try to introduce a shared variable that persists across fork sessions, taking into account multiple simultaneous wait forks, shudder) and use that for synchronization. Ugh.

mqudsi added a commit to mqudsi/fish-shell that referenced this pull request Oct 2, 2018
Per @ridiculousfish's suggestions in fish-shell#5219,
`process_mark_finished_children()` has been updated to work in an easier-
to-follow manner. Its behavior is now straight forward, it always checks
for finished processes but only blocks if `block_on_fg` is true.

We're not using the SIGCHLD count in s_sigchld_generation_cnt for
anything any more, as it's not actually a reliable metric since we can
experience one SIGCHLD as a result of two processes exiting (see fish-shell#1768),
but only reap one of them if the other is in a not-fully-constructed job
(see fish-shell#5219), a state we cannot possibly detect without calling
`waitpid()` on all child processes, which we are explicitly avoiding.
mqudsi added a commit to mqudsi/fish-shell that referenced this pull request Oct 2, 2018
Per @ridiculousfish's suggestions in fish-shell#5219,
`process_mark_finished_children()` has been updated to work in an easier-
to-follow manner. Its behavior is now straight forward, it always checks
for finished processes but only blocks if `block_on_fg` is true.

We're not using the SIGCHLD count in s_sigchld_generation_cnt for
anything any more, as it's not actually a reliable metric since we can
experience one SIGCHLD as a result of two processes exiting (see fish-shell#1768),
but only reap one of them if the other is in a not-fully-constructed job
(see fish-shell#5219), a state we cannot possibly detect without calling
`waitpid()` on all child processes, which we are explicitly avoiding.
@mqudsi
mqudsi force-pushed the keep_zombies branch 4 times, most recently from c0316b7 to f3dc9d6 Compare October 2, 2018 21:54
@faho

faho commented Oct 20, 2018 •

Copy link
Copy Markdown
Member

Okay, I got a nice reproducible crash here:

echo a >somefile
grep a somefile | grep c | grep d

results in:

<W> fish: Could not send job 2 ('command grep --color=auto $argv') with pgid 14699 to foreground
tcsetpgrp: Kein passender Prozess gefunden
<W> fish: Could not send job 2 ('command grep --color=auto $argv') with pgid 14699 to foreground
tcsetpgrp: Kein passender Prozess gefunden
<E> fish: /tmp/makepkg/fish-shell-git/src/fish-shell/src/proc.cpp:411: failed assertion: job_fg == nullptr && "More than one active, fully-constructed foreground job!"
<E> fish: Backtrace:
<E> fish: 0   job_reap(bool) + 0
<E> fish: 1   job_t::continue_job(bool) + 1032
<E> fish: 2   exec_job(parser_t&, job_t*) + 7028
<E> fish: 3   parse_execution_context_t::run_1_job(tnode_t<grammar::job>, block_t const*) + 3156
<E> fish: 4   parse_execution_context_t::run_job_conjunction(tnode_t<grammar::job_conjunction>, block_t const*) + 196
<E> fish: 5   parse_execution_result_t parse_execution_context_t::run_job_list<grammar::job_list>(tnode_t<grammar::job_list>, block_t const*) + 193
<E> fish: 6   parse_execution_context_t::eval_node(tnode_t<grammar::job_list>, block_t const*, io_chain_t const&) + 1380
<E> fish: 7   int parser_t::eval_node<grammar::job_list>(std::shared_ptr<parsed_source_t const>, tnode_t<grammar::job_list>, io_chain_t const&, block_type_t) + 392
<E> fish: 8   parser_t::eval(std::shared_ptr<parsed_source_t const>, io_chain_t const&, block_type_t) + 146
<E> fish: 9   parser_t::eval(std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, io_chain_t const&, block_type_t) + 224
<E> fish: 10  /usr/bin/fish(+0xaae43) [0x560f269c0e43]
<E> fish: 11  /usr/bin/fish(+0xaf557) [0x560f269c5557]
<E> fish: 12  /usr/bin/fish(+0xafee8) [0x560f269c5ee8]
<E> fish: 13  expand_string(std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::vector<completion_t, std::allocator<completion_t> >*, int, std::vector<parse_error_t, std::allocator<parse_error_t> >*) + 647
<E> fish: 14  parse_execution_context_t::expand_arguments_from_nodes(std::vector<tnode_t<grammar::argument>, std::allocator<tnode_t<grammar::argument> > > const&, std::vector<std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > >*, parse_execution_context_t::globspec_t) + 450
<E> fish: 15  parse_execution_context_t::populate_plain_process(job_t*, process_t*, tnode_t<grammar::plain_statement>) + 1011
<E> fish: 16  parse_execution_context_t::populate_job_process(job_t*, process_t*, tnode_t<grammar::statement>) + 231
<E> fish: 17  parse_execution_context_t::populate_job_from_job_node(job_t*, tnode_t<grammar::job>, block_t const*) + 322
<E> fish: 18  parse_execution_context_t::run_1_job(tnode_t<grammar::job>, block_t const*) + 1053
<E> fish: 19  parse_execution_context_t::run_job_conjunction(tnode_t<grammar::job_conjunction>, block_t const*) + 196
<E> fish: 20  parse_execution_context_t::run_if_statement(tnode_t<grammar::if_statement>, block_t const*) + 315
<E> fish: 21  parse_execution_context_t::run_1_job(tnode_t<grammar::job>, block_t const*) + 2739
<E> fish: 22  parse_execution_context_t::run_job_conjunction(tnode_t<grammar::job_conjunction>, block_t const*) + 196
<E> fish: 23  parse_execution_result_t parse_execution_context_t::run_job_list<grammar::job_list>(tnode_t<grammar::job_list>, block_t const*) + 193
<E> fish: 24  parse_execution_context_t::eval_node(tnode_t<grammar::job_list>, block_t const*, io_chain_t const&) + 1380
<E> fish: 25  int parser_t::eval_node<grammar::job_list>(std::shared_ptr<parsed_source_t const>, tnode_t<grammar::job_list>, io_chain_t const&, block_type_t) + 392
<E> fish: 26  void internal_exec_helper<grammar::job_list>(parser_t&, std::shared_ptr<parsed_source_t const>, tnode_t<grammar::job_list>, io_chain_t const&) + 194
<E> fish: 27  exec_job(parser_t&, job_t*) + 8134
<E> fish: 28  parse_execution_context_t::run_1_job(tnode_t<grammar::job>, block_t const*) + 1870
<E> fish: 29  parse_execution_context_t::run_job_conjunction(tnode_t<grammar::job_conjunction>, block_t const*) + 196
<E> fish: 30  parse_execution_result_t parse_execution_context_t::run_job_list<grammar::job_list>(tnode_t<grammar::job_list>, block_t const*) + 193
<E> fish: 31  parse_execution_context_t::eval_node(tnode_t<grammar::job_list>, block_t const*, io_chain_t const&) + 1380
<E> fish: 32  int parser_t::eval_node<grammar::job_list>(std::shared_ptr<parsed_source_t const>, tnode_t<grammar::job_list>, io_chain_t const&, block_type_t) + 392
<E> fish: 33  parser_t::eval(std::shared_ptr<parsed_source_t const>, io_chain_t const&, block_type_t) + 146
<E> fish: 34  parser_t::eval(std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, io_chain_t const&, block_type_t) + 224
<E> fish: 35  /usr/bin/fish(+0xaae43) [0x560f269c0e43]
<E> fish: 36  /usr/bin/fish(+0xaf557) [0x560f269c5557]
<E> fish: 37  /usr/bin/fish(+0xafee8) [0x560f269c5ee8]
<E> fish: 38  expand_string(std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::vector<completion_t, std::allocator<completion_t> >*, int, std::vector<parse_error_t, std::allocator<parse_error_t> >*) + 647
<E> fish: 39  parse_execution_context_t::expand_arguments_from_nodes(std::vector<tnode_t<grammar::argument>, std::allocator<tnode_t<grammar::argument> > > const&, std::vector<std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > >*, parse_execution_context_t::globspec_t) + 450
<E> fish: 40  parse_execution_context_t::populate_plain_process(job_t*, process_t*, tnode_t<grammar::plain_statement>) + 1011
<E> fish: 41  parse_execution_context_t::populate_job_process(job_t*, process_t*, tnode_t<grammar::statement>) + 231
<E> fish: 42  parse_execution_context_t::populate_job_from_job_node(job_t*, tnode_t<grammar::job>, block_t const*) + 322
<E> fish: 43  parse_execution_context_t::run_1_job(tnode_t<grammar::job>, block_t const*) + 1053
<E> fish: 44  parse_execution_context_t::run_job_conjunction(tnode_t<grammar::job_conjunction>, block_t const*) + 196
<E> fish: 45  parse_execution_result_t parse_execution_context_t::run_job_list<grammar::job_list>(tnode_t<grammar::job_list>, block_t const*) + 193
<E> fish: 46  parse_execution_context_t::eval_node(tnode_t<grammar::job_list>, block_t const*, io_chain_t const&) + 1380
<E> fish: 47  int parser_t::eval_node<grammar::job_list>(std::shared_ptr<parsed_source_t const>, tnode_t<grammar::job_list>, io_chain_t const&, block_type_t) + 392
<E> fish: 48  void internal_exec_helper<grammar::job_list>(parser_t&, std::shared_ptr<parsed_source_t const>, tnode_t<grammar::job_list>, io_chain_t const&) + 194
<E> fish: 49  exec_job(parser_t&, job_t*) + 8134
<E> fish: 50  parse_execution_context_t::run_1_job(tnode_t<grammar::job>, block_t const*) + 1870
<E> fish: 51  parse_execution_context_t::run_job_conjunction(tnode_t<grammar::job_conjunction>, block_t const*) + 196
<E> fish: 52  parse_execution_result_t parse_execution_context_t::run_job_list<grammar::job_list>(tnode_t<grammar::job_list>, block_t const*) + 193
<E> fish: 53  parse_execution_context_t::eval_node(tnode_t<grammar::job_list>, block_t const*, io_chain_t const&) + 1380
<E> fish: 54  int parser_t::eval_node<grammar::job_list>(std::shared_ptr<parsed_source_t const>, tnode_t<grammar::job_list>, io_chain_t const&, block_type_t) + 392
<E> fish: 55  parser_t::eval(std::shared_ptr<parsed_source_t const>, io_chain_t const&, block_type_t) + 146
<E> fish: 56  parser_t::eval(std::__cxx11::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, io_chain_t const&, block_type_t) + 224
<E> fish: 57  /usr/bin/fish(+0xaae43) [0x560f269c0e43]
<E> fish: 58  /usr/bin/fish(+0xf7f73) [0x560f26a0df73]
<E> fish: 59  reader_readline(int) + 171
<E> fish: 60  reader_read(int, io_chain_t const&) + 525
<E> fish: 61  main + 4064
<E> fish: 62  __libc_start_main + 243
<E> fish: 63  _start + 46

The trick seems to be having three greps simultaneously - two doesn't suffice, and the file needs to match, presumably so the other greps actually get started fast enough.

@mqudsi

mqudsi commented Oct 20, 2018 •

Copy link
Copy Markdown
Contributor Author

I'm presuming grep is a function?

Are you on the latest version of the code? I fixed that a few days ago, it was caused by sharing pgrps across function jobs.

mqudsi@ZBook /m/c/U/m/r/fish-shell> echo $version
2.7.1-1566-g88222589
mqudsi@ZBook /m/c/U/m/r/fish-shell> echo a > somefile
mqudsi@ZBook /m/c/U/m/r/fish-shell> grep a somefile | grep c | grep d | grep e | grep f
mqudsi@ZBook /m/c/U/m/r/fish-shell> 

@faho

faho commented Oct 20, 2018 •

Copy link
Copy Markdown
Member

I'm presuming grep is a function?

Yup, the standard --color=auto thing.

Are you on the latest version of the code?

It turns out I wasn't. I checked github, but that says you added commits "22 days ago" and "3 days ago" respectively. It does not like this rebasing stuff.

Could you therefore post a quick comment that you added something when you do?

I fixed that a few days ago, it was caused by sharing pgrps across function jobs.

I can confirm the fix. (for the grep crash, that is. The source/killpg business still happens)

@mqudsi

mqudsi commented Oct 20, 2018

Copy link
Copy Markdown
Contributor Author

Yeah, GitHub loses it when rebasing. I just pushed a commit that fixed a regression that wasn't there the last time you tried it (fish high cpu when another program has control of the terminal). I previously also committed a fix for a hang when piping an external command to a function when the external command produces more output than can fit within the OS pipe buffer and that entire chain is in the foreground and buffering was at play, previously we would block on the foreground process with reading from the pipe causing the prior command to block waiting for the pipe to unblock.

I just pushed again with a fix with the killpg warning. It was a bug introduced in 1b1bc28 but didn't surface until the changes to job control, fish would detect that the script calling exec hadn't terminated and try killing it too.

@mqudsi

mqudsi commented Oct 20, 2018

Copy link
Copy Markdown
Contributor Author

Sorry, there was a typo in the killpg fix. Fixed now.

@faho

faho commented Oct 24, 2018

Copy link
Copy Markdown
Member

So, @mqudsi, @ridiculousfish, @zanchey: Can we merge this now?

I'd love to, since then we might get some testing in. It's also one of the few things left in the 3.0 milestone.

@mqudsi

mqudsi commented Oct 25, 2018

Copy link
Copy Markdown
Contributor Author

I guess the point of a pull request is for code review and for testing we're going to have to merge this into master sooner or later (thanks @comfortablynick for trying it out).

I don't like making tentative changes to master that might need to be reverted, but I guess the need for testing here wins out over aesthetic cleanliness of master history. I can rebase, give it a once-over, and merge it into master and if there are any problems that bubble up, we can address them or temporarily revert, I suppose.

Reminding myself: I should add test cases for some of the transient bugs I ran into developing this branch. The problem is that I'm still not 100% on how the expect tests work and what type of deviations from the explicitly scripted responses it accepts.

mqudsi added 17 commits October 27, 2018 17:58
* Instead of reaping all child processes when we receive a SIGCHLD, try
reaping only processes belonging to process groups from fully-
constructed jobs, which should eliminate the need for the keepalive
process entirely (WSL's lack of zombies not withstanding) as now
completed processes are not reaped until the job has been fully
constructed (i.e.  all processes launched), which means their process
group should still be around for new processes to join.

* When `tcgetpgrp()` calls return 0, attempt to `tcsetpgrp()` before
invoking failure handling code.

* When forking a builtin and not running interactively, do not bail if
unable to set/restore terminal attributes.

Fixes fish-shell#4178. Fixes fish-shell#3805. Fixes fish-shell#5210.
We never insert elements into the middle of a job list, only move
elements to the top. While that can be done "efficiently" with a list, it
can be done faster with a deque, which also won't thrash the cache when
enumerating over jobs.

This speeds up enumeration in the critical path in
`process_mark_finished_children()`.
Per @ridiculousfish's suggestions in fish-shell#5219,
`process_mark_finished_children()` has been updated to work in an easier-
to-follow manner. Its behavior is now straight forward, it always checks
for finished processes but only blocks if `block_on_fg` is true.

We're not using the SIGCHLD count in s_sigchld_generation_cnt for
anything any more, as it's not actually a reliable metric since we can
experience one SIGCHLD as a result of two processes exiting (see fish-shell#1768),
but only reap one of them if the other is in a not-fully-constructed job
(see fish-shell#5219), a state we cannot possibly detect without calling
`waitpid()` on all child processes, which we are explicitly avoiding.
* Debug level 3: describe all commands being executed (this is, after all,
a shell and one can argue that this is the most important debug
information avaliable)
* Debug level 4: details of execution, mainly fork vs no-fork and io
handling

Also introduced j->preview() to print a short descriptor of the job
based on the head of the first process so we don't overwhelm with
needless repitition, but also so that we don't have to rely on
distinguishing between repeated, non-unique/non-monotonic job ids that
are often recycled within a single "execution cycle" (pressing enter
once).
* Convert JOB_* enums to scoped enums
* Convert standalone job_is_* functions to member functions
* Convert standalone job_{promote, signal, continue} to member functions
* Convert standolen job_get{,_from_pid} to `job_t` static functions
* Reduce usage of JOB_* enums outside of proc.cpp by using new
  `job_t::is_foo()` const helper methods instead.

This patch is only a refactor and should not change any functionality or
behavior (both observed and unobserved).
* Use the newly-introduced signal_block_t RAII wrapper
* Remove EINTR loops as all signals are blocked
* Clean up control flow thanks to RAII wrappers
* Rename parameter to clarify what it does and update docs accordingly
* Update outdated comments referencing SIGSTOP code that was removed a
  long time ago.
* Remove no-op CHECK_BLOCK() call
Convert `select_try()` to return a well-defined enum describing its
state, and handle each of the three possible cases with clear reasons
why we are blocking or not blocking in each subsequent call to
`process_mark_finished_children()`.
The old code was rather haphazard with regards to error control, and
would make mutable changes before operations that could fail without any
viable error handling options.
Windows 10 17763 Redstone 5 (October 2018 Update) officially brings
zombie support (first introduced in 17713) to the general public.

See https://docs.microsoft.com/en-us/windows/wsl/release-notes#build-17763-1809
Handle EPERM (WSL only?) and EINTR by retrying.
Use SIGCHLD to determine whether or not waitpid(2) calls can be elided,
but only with extreme caution. If we receive SIGCHLD but are not able to
reap all jobs, we need to iterate through them again.

For this to work, we need to make sure that we reap all children that we
can reap after a SIGCHLD, i.e. it's not OK to just reap the first and
return or else we can never clear the dirty state flag.

In all cases, as expensive as a call to waitpid() may be, if a child
process is available for reaping it is always cheaper to wait on it then
reap it than to call select_try() and end up timing out.
When a function is encountered by exec_job, a new context is created for
its execution from the ground up, with a new job and all, ultimately
resulting in a recursive call to exec_job from the same (main) thread.

Since each time exec_job encounters a new job with external commands
that needs terminal control it creates a new pgrp and gives it control
of the terminal (tcsetpgrp & co), this effectively takes control away
from the previously spawned external commands which may be (and likely
are) expecting to still have terminal access.

This commit attempts to detect when such a situation arises by handling
recursive calls to exec_job (which can only happen if the pipeline
included a function) by borrowing the pgrp from the (necessarily still
active) parent job and spawning new external commands into it.

When a parent job spawns new jobs due to the evaluation of a new
function (which shouldn't be the case in the first place), we end up
with two distinct jobs sharing one pgrp (to fix fish-shell#3952). This can lead to
early termination of a pgrp if finished parent job children are reaped
before future processes in either the parent or future child jobs can
join it.

While the parent job is under construction, require that waitpid(2)
calls for the child job be done by process id and not job pgrp.

Closes fish-shell#3952.
This was introduced in 1b1bc28 but did
not cause any problems until the job control refactor, which caused it
to attempt to signal the calling `exec` builtin's own (invalid) pgrp
with SIGHUP.

Also improved debugging for `j->signal()` failures by printing the
signal we tried sending in case of error, rename the function to
`hup_background_jobs`, and move it from `reader.h`/`reader.cpp` to
`proc.h`/`proc.cpp`.
@mqudsi

mqudsi commented Oct 27, 2018

Copy link
Copy Markdown
Contributor Author

It's done! 😬

@JoshCheek

Copy link
Copy Markdown

❤️ Ty for this!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

bug Something that's not working as intended enhancement

Projects

None yet

5 participants