Skip to content

Rearchitect WSL compatibility from SIGCONT to keepalive process - #4676

Closed
ridiculousfish wants to merge 7 commits into
fish-shell:masterfrom
ridiculousfish:unblock3
Closed

ridiculousfish wants to merge 7 commits into
fish-shell:masterfrom
ridiculousfish:unblock3

Conversation

@ridiculousfish

Copy link
Copy Markdown
Member

This merges a sequence of commits that undoes the SIGCONT orchestration used for WSL compatibility. The essential problem is this: In Unix and Linux, exited processes are still valid until it is reaped; you can, say, make an exited process a group leader. But in Windows, when a process exits, it is gone, and most syscalls (other than, say, waitpid) fail for it. This is known as the WSL Rick Grimes problem.

This manifests as various race conditions in WSL between a parent operating on a child, and the child exiting. Prior to this merge, these were addressed by having the child wait for the parent to send it a SIGCONT. This resolved the race.

This merge removes this approach and replaces it with a simpler mechanism that leverages the existing keepalive machinery. A keepalive process is created for all platforms when we have a pipeline that contains a builtin. This is necessary to keep the whole process group alive. The fix is, on WSL, we always create a keepalive and make it the group leader. Because the keepalive does not call exec and its lifetime is bound to a C++ stack frame, it is easy to resolve the race.

This improves performance a bit (except on WSL), since child processes no longer have to synchronize with the parent process, but the big win is simplicity. This removes the notion of the single global stopped child, of which there could only be one, and which had be resumed at the right time(s), of which there were several.

@ridiculousfish
ridiculousfish requested a review from mqudsi January 21, 2018 10:27
@ridiculousfish

Copy link
Copy Markdown
Member Author

@mqudsi interested in your thoughts / objections on this.

@faho

faho commented Jan 21, 2018

Copy link
Copy Markdown
Member

Also see #4653.

The problem with the keepalive process is that it has its own pgroup, so if fish needs to stay in the foreground for a job (because a builtin is first or last in the pipeline), it won't work. E.g. read | cat shows this issue.

I'd imagine that in that case we don't need or want to create a keepalive even on WSL because fish can just stay the pgroup leader.

the WSL Rick Grimes problem

😄

@zanchey

zanchey commented Jan 21, 2018

Copy link
Copy Markdown
Member

I'd like to take a moment to enjoy microsoft/WSL#2786

@ridiculousfish ridiculousfish changed the title Unblock3 Rearchitect WSL compatibility from SIGCONT to keepalive process Jan 22, 2018
Comment thread src/exec.cpp

// This is the parent process. Store away information on the child, and possibly
// fice it control over the terminal.
// give it control over the terminal.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went nuts trying to figure out what fice was supposed to mean!

Comment thread src/common.cpp
/// and checking if "Microsoft" is in the first line.
/// See https://github.com/Microsoft/WSL/issues/423
bool is_windows_subsystem_for_linux() {
ASSERT_IS_NOT_FORKED_CHILD();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this here? From experience trying to clean up the fork code, these asserts can be misleading.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you say more about how they're misleading? The problem I'm trying to address here is that this function is not safe to call after fork, because it can allocate memory. The assert hopes to be both documentation and a runtime check.

Comment thread src/exec.cpp
const int fg = j->get_flag(JOB_FOREGROUND);
j->set_flag(JOB_FOREGROUND, false);

// Main loop may need to perform a blocking read from previous command's output.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not having this comment here made figuring out hangs in the job loop very difficult. Can we just a put a nice //Note that this call may block while the builtin performs IO or something?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea.

Comment thread src/exec.cpp
// fice it control over the terminal.
// give it control over the terminal.
p->pid = pid;
set_child_group(j, p->pid);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to either set pgrep_set = true here or drop pgrp_set entirely. We can probably do the latter now.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I had dropped it in a later commit that wasn't part of this PR, oops.

Comment thread src/postfork.cpp Outdated
}
} else {
// This is probably stays unused in the child.
// The child does not actually use this field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can drop the else branch completely since we're cleaning up the 2012 getpgid logic above? We just called assigned the value of j->pgid to own pgid, and that call didn't fail, so there's no need for the kernel context switch here again since the goal is to optimize.

Comment thread src/postfork.cpp
if (j->pgid == -2) {
j->pgid = child_pid;
}
// The parent sets the child's group. This incurs the well-known unavoidable race with the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder to either of us: clean up the comments above the set_child_group function to reflect the new behavior. (GitHub won't let me comment there)

Comment thread src/postfork.cpp
// set it failed. This was added in commit 4e912ef8 from 2012-02-27.
failure = failure && getpgid(p->pid) != j->pgid;
if (failure) { //!OCLINT(collapsible if statements)
if (setpgid(p->pid, j->pgid) < 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for reference and in case @ridiculousfish has any feedback on its initial purpose: while the EPERM check was added by myself to get around the WSL issue, the EINTR retry logic was from before. To me, EINTR retries make sense in blocking calls that might take a while to execute (such as waitpid) but for one-off calls like this I think littering EINTR checks everywhere is something we can do without so this should be ok?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, this got removed in a later commit.

@mqudsi

mqudsi commented Jan 24, 2018

Copy link
Copy Markdown
Contributor

I'm happy (yet also sad in a way that only a developer can empathize!) to see the complexity of my synchronization code for process control thrown away. At first I was afraid you had reverted the entirety of the changes to the job control loop in one fell swoop, but I'm glad to see it was only surgically altered and the remainder of the fixes remain.

Do we actually have a documented guarantee somewhere that on non-WSL unixes you may always join a process group that consisted of only one process that has now terminated? What is the pgrp reaping logic here - they can't persist indefinitely, but do they last so long as the parent process exists (that could still end up being hundreds or thousands of pgrps in the lifetime of a shell, so that doesn't make sense either). I should probably dig through my copy of the unix programmers handbook or grep through the kernel sources..

@mqudsi

mqudsi commented Jan 24, 2018

Copy link
Copy Markdown
Contributor

The problem with the keepalive process is that it has its own pgroup, so if fish needs to stay in the foreground for a job (because a builtin is first or last in the pipeline), it won't work. E.g. read | cat shows this issue.

OK, so here's what happened to me. A few months ago I tried to tackle that and other problems at the root, so I decided to be a hero and replace all non-fork-and-exec fork calls with threads instead, and then I decided to fix read | cat by extending that Herculean effort to include running all builtins in threads, making it possible to fork-and-exec a builtin when called as the head of a command so the keepalive logic could be dropped entirely. The problem was that some code actually used forking as a way of duplicating the internal state of the parser and other fish components instead of granularly cloning the individual objects that needed to be forked (in the git meaning of "fork", not the fork(3) meaning).

That led me down the Dodgsonian rabbit hole of trying to clean up multithreaded access to core fish resources, marshalled across threads, processes, builtins, and functions. At one point in this dark descent into despair and madness, I wound up trying to replicate threads just for the sake of seeing what else needed to be done by forking all builtins.. and then I was wondering why the shell wouldn't exit when the exit builtin was called 😲

Thankfully I pushed all that to GitHub a few weeks before I accidentally blew away my fish directory yesterday. The (broken) fruits of my effort are here: master...mqudsi:async_exec

There are some commits there that I want to cherry-pick into master, and I think I'm going to drop the idea of trying to run builtins in a thread to work around the blocking read | cat issue by changing the behavior of the buffered io_chain_t variant to use some form of non-blocking writes.

@faho faho added this to the fish-3.0 milestone Jan 24, 2018
@ridiculousfish
ridiculousfish force-pushed the unblock3 branch 2 times, most recently from f7a2eda to 9fdd9a0 Compare February 2, 2018 21:17
@ridiculousfish

Copy link
Copy Markdown
Member Author

@mqudsi great questions!

Do we actually have a documented guarantee somewhere that on non-WSL unixes you may always join a process group that consisted of only one process that has now terminated?

I don't think this is explicitly spelled out, but IMO it's implied by the Unix process mode and the usual way that setpgid is used (in parent and child) by other shells. There's no error path for "process has terminated" for example.

Something I don't understand is why bash isn't affected by this though.

What is the pgrp reaping logic here - they can't persist indefinitely, but do they last so long as the parent process exists (that could still end up being hundreds or thousands of pgrps in the lifetime of a shell, so that doesn't make sense either).

You are asking what does the kernel do? pgrps are reaped as they become empty. POSIX fork: "The child process ID also shall not match any active process group ID."

Basically a pid serves double-duty as both a process identifier and a process group identifier. A process may exit and be reaped, yet its pid will not be recycled until its process group is empty.

A few months ago I tried to tackle that and other problems at the root, so I decided to be a hero and replace all non-fork-and-exec fork calls with threads instead

Heh. I know that feeling, see my ancient and borderline absurd multithreaded_execution branch, or my several attempts to use a nodejs-style asynchronous execution. Maybe fish should adopt libuv...

@ridiculousfish

Copy link
Copy Markdown
Member Author

@faho:

The problem with the keepalive process is that it has its own pgroup, so if fish needs to stay in the foreground for a job (because a builtin is first or last in the pipeline), it won't work. E.g. read | cat shows this issue. I'd imagine that in that case we don't need or want to create a keepalive even on WSL because fish can just stay the pgroup leader.

Great observation, you're right. I can make that change.

Have WSL use a keepalive whenever the first process is external.
This works around the fact that WSL prohibits setting an exited
process as the group leader.
This is to investigate alternatives to the existing kill(SIGSTOP)
WSL compatibility thing.
keepalive processes are typically killed by the main shell process.
However if the main shell exits the keepalive may linger. In WSL
keepalives are used more often, and the lingering keepalives are both
leaks and prevent the tests from finishing.

Have keepalives poll for their parent process ID and exit when it
changes, so they can clean themselves up. The polling frequency can be
low.
This removes support for blocking children via signals, which was used
to orchestrate processes on WSL. Now we use the keepalive mechanism
instead.
@mqudsi

mqudsi commented Feb 3, 2018

Copy link
Copy Markdown
Contributor

@ridiculousfish I think I have a good handle on the "regular" sequence of events pertaining to process group management, but my question is actually about this specific case (which led me to the initial restructuring): fish launches a new process and uses its process id as the pgrp. This process then exits before fish gets a chance/gets around/is scheduled by the process scheduler to launch a second command in this chain that should be assigned to the newly-created process group.

In this case, the kernel cannot know that we plan on launching a new process into that process group, at that moment, the pid has terminated and the pgid is now empty. What guarantee do we have that this pgid is not reaped before we can place the next command in the job into this process group?

i.e. my concern is that WSL is simply manifesting a case that already exists by simply being more zealous with the process group reaping following the same constraints that Linux/macOS/BSD would, only doing so faster or more often.

@faho

faho commented Feb 3, 2018

Copy link
Copy Markdown
Member

What guarantee do we have that this pgid is not reaped before we can place the next command in the job into this process group?

This is a bit subtle, but POSIX basically says that a pgroup stays active until the last process has left (via setpgid()) or is reaped (after waitpid()) at least in my reading. See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_299 and the linked paragraphs.

So it should be possible to have fish not reap its children (man the unix terminology can be macabre sometimes) while trying to launch a job.

@ridiculousfish

Copy link
Copy Markdown
Member Author

@mqudsi good question:

fish launches a new process and uses its process id as the pgrp. This process then exits before fish gets a chance/gets around/is scheduled by the process scheduler to launch a second command in this chain that should be assigned to the newly-created process group...What guarantee do we have that this pgid is not reaped before we can place the next command in the job into this process group?

For pipes that use external commands only, we do this by ensuring we do not reap any of the children until the whole pipeline is set up. It's not obvious that this is true - basically you have to follow along in exec_job and show that if every process type is EXTERNAL then there's no paths that call waitpid until the function finishes.

For pipes that use functions, we are vulnerable to the scenario you describe. So instead we create a keepalive process and ensure it does not exit (and therefore is not eligible to be reaped) until the whole process chain is complete.

@ridiculousfish

Copy link
Copy Markdown
Member Author

Merge-committed as 56a46a0, thanks for the thoughtful comments

@ridiculousfish

Copy link
Copy Markdown
Member Author

@faho I ended up not making the change to avoid creating the keepalive when functions are first or last in the process, because we don't actually make fish the pgroup leader in that case. If you do end up making fish the leader then we can tweak that logic.

@ridiculousfish
ridiculousfish deleted the unblock3 branch February 7, 2018 21:00
@mqudsi

mqudsi commented Feb 8, 2018 •

Copy link
Copy Markdown
Contributor

@faho

or is reaped (after waitpid())

That's what I was missing. Thank you.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Apr 17, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants