mutagen-io / mutagen

Fast file synchronization and network forwarding for remote development
https://mutagen.io
Other
3.42k stars 152 forks source link

Enable `sudo` on `agent.connect()` when `MUTAGEN_USE_SUDO` environment var set to `1` #505

Open mikeschinkel opened 2 months ago

mikeschinkel commented 2 months ago

While trying to fix Mutagen for my use-case, I specifically decided to do the least work possible so I did not consider any refactoring which I might have had a been a member of the Mutagen team, so please judge my PR accordingly.

I found one problem followed by another. First, I needed to make Mutagen run the agent as sudo, and then I needed to use visudo to make /var/lib/docker/volumes/*/_data available to me (note the wildcard in the path). The specific text I used in visudo was:

mikeschinkel ALL=(ALL) NOPASSWD: /home/mikeschinkel/.mutagen/agents/*/mutagen-agent

Of course sudo should ONLY be used when someone specifically requests it and this PR handles that.

To use sudo only when specifically requested and not when others who use Mutagen do not need or want sudo I considered adding a configuration item — and even did so and got it working — but then realized it was not synchronization vs. forwarding specific. I also decided I could do it with fewer code changes by just using an environment variableMUTAGEN_USE_SUDO — so that is what I did.

I modified ./pkg/agent/dial.go and adding the following code just before the command, composed with fmt.Sprintf():

// Add sudo if env var says to add sudo
var sudo string
if os.Getenv("MUTAGEN_USE_SUDO") == "1" {
  sudo = fmt.Sprintf("test ! -f '%s' && printf '%s' >&2 || sudo ", agentInvocationPath, notInstalledFlag)
}

The above code first tests to see if the agent exists and if it does not it prints the value of notInstalledFlag — or "Agent not installed" — to stdErr. This allows a test for that value later in the func.

If that is returned my code then causes agent.connect() to immediately return to its caller while setting TryInstall and CmdExe to true to cause the installer to try to install the agent. I had to add that last bit because there were numerous times during my testing where I found Mutagen would simply give up and never retry to install when the agent was not installed.

Hopefully you will find this useful and that it will meet the needs of others with similar scenarios to the one I experienced. But if you do not, I will at least have a custom Mutagen that meets my needs.

mikeschinkel commented 1 month ago

Sorry for the multiple force-pushes. This was the first time I had to create a signed commit and it took a few tries to get it all working.