Tmux session does not always open with expected mount bindings - tmux

I want to run unshare, mount a few directories, and run a tmux session in the new mount namespace. Here is my setup
$ cat run
#!/bin/bash
mount --bind ~/a ~/b
tmux
$ unshare -r --mount ~/run
When I run this command, I get dropped into the tmux session but without the binding. What is more strange to me is that if I rerun the mount command in the tmux session and exit, the next time I run unshare -r --mount ~/run the binding is there!
I could get consistent behavior by always running the mount command in the tmux session but I would like to understand why the behavior depends on if the binding existed in a previous session.
Replacing tmux with /bin/bash to poke at the mounted directory shows that the binding always happens, as expected. Once running the mount command in tmux, all subsequent runs have the binding until I move ~/a. Then the problem is back.

I am now unable to reproduce my own problem. I suspect the solution was to power cycle. I do not think I had done so between installing tmux and running into this issue, so that may have been the root cause.

Related

Is it possible to quit tmux, while "keeping" the window in the terminal

Use case
I run command over a bastion in SSH and since the connection can be dropped we are using tmux or screen.
For short commands I'm using send-keys, let's say I'm using a command like kubectl get pods. I'd like to keep the output of this command but terminate the tmux session.
Using remain-on-exit is not what I'm looking for as it keeps a dead window.
I've seen those question already
https://unix.stackexchange.com/questions/17116/prevent-pane-window-from-closing-when-command-completes-tmux
TMUX: how to make new window stay when start shell-command quits?
I'd like to keep the output of this command but terminate the tmux session.
I use this in my ~/.tmux.conf, and now when I exit my running shell, pane output is saved to unique log file:
set -g remain-on-exit
set-hook pane-died 'capture-pane -S - -E - ; save-buffer "$HOME/logs/tmux/tmux-saved.#{host_short}-#{session_id}:#{window_id}:#{pane_id}-#{pane_pid}-#{client_activity}.log"; delete-buffer; kill-pane'
I'm not sure it's exactly what you are looking for, but you could use the capture-pane command to save the contents of a pane (subject to what is still in the pane's history) to a file.

How to start two tmux sessions with different environments?

The naive way to do this is not working. Try this:
Start a first tmux session.
$ export ENVIRONMENT="production"
$ tmux
You can then verify that inside the session ENVIRONMENT is production
Then, in a second terminal start another session
$ export ENVIRONMENT="staging"
$ tmux
Surprisingly in this session ENVIRONMENT is also production! This is very unintuitive!
What is going on here?
How can I achive this? I like all windows in a session to "inherit" the ENVIRONMENT variable.
The "simplest" solution is to create a new tmux server with the different environment.
$ ENVIRONMENT=production tmux -L prod-tmux
and
$ ENVIRONMENT=staging tmux -L staging-tmux
You'll always need to specify which socket, prod-tmux or staging-tmux, to use whenever you reconnect to an existing session.
The next solution would be to use one server, but modify the environment of each session in that server. Something like
$ tmux new-session -d -s production
$ tmux new-session -d -s staging
$ tmux set-environment -t production ENVIRONMENT production
$ tmux set-environment -t staging ENVIRONMENT staging
Note that ENVIRONMENT would not be set in the process running in the initial window for each session, but will be for any subsequent window created. (Unless the server inherited ENVIRONMENT when it first started.)
When you run tmux, it first looks for an existing server (either the default server, or the one specified by either the -L or -S options). If there is no server, one is started, and the server's environment is inherited from the current environment.
If there is a server, tmux simply requests the server to execute a tmux command (by default, new-session, or whatever command is specified by an argument to tmux) command, then exits. The environment of the tmux command itself isn't relevant, unless the requested command is documented to read from it (cf. set-environment).
The server manages a group of windows, each of which represents a process created by the server (not the tmux command itself). A session is just a logical group of windows, also managed by the server.
Newer versions of tmux seem to support this natively! I do devops support for multiple clients and wanted to set a separate bash history file for each client. The following works very well for me! It sets the working directory, to the client/project dir, and sets the bash history file path
tmux new -c ~/Documents/code/CLIENT/ -e HISTFILE=~/Documents/code/CLIENT/.bash_history -s CLIENT -d
Based on the excellent answer by #chepner we can solve this issue by adding aliases to define different tmux commands for different servers. For example we could append the following to ~/.bashrc.
# somewhere in ~/.bashrc
alias tmux-s1='tmux -L s1'
alias tmux-s2='tmux -L s2'
alias tmux-s3='tmux -L s3'
alias tmux-s4='tmux -L s4'
alias tmux-s5='tmux -L s5'
Now we can use tmux-s1, tmux-s2, etc... the same way we would normally use the tmux command except each variant will be associated with a different server. When we create a session for a server that has no active sessions then the current environment variables will be used to initialize the server. To reattach to the session we will need the alias for the server that the session was created with.
Example
$ export ENVIRONMENT="production"
$ tmux-s1 ls
no server running on /tmp/tmux-12345/s1
$ tmux-s1
############### now attached to session 0 on server s1 ################
$ echo $ENVIRONMENT
production
################### (ctrl+b,d) detach from session ####################
[detached (from session 0)]
$ tmux-s1 ls
0: 1 windows (created Sun Nov 17 18:13:18 2019) [80x20]
$ export ENVIRONMENT="staging"
$ tmux-s2 ls
no server running on /tmp/tmux-12345/s2
$ tmux-s2
############### now attached to session 0 on server s2 ################
$ echo $ENVIRONMENT
staging
################### (ctrl+b,d) detach from session ####################
[detached (from session 0)]
$ tmux-s2 ls
0: 1 windows (created Sun Nov 17 18:13:22 2019) [80x20]

Byobu unable to attach to running tmux

I´m a happy user of byobu, but recently I noted that I cannot attach anymore to open sessions.
With ps aux | grep tmux I can clearly see many tmux processes, but unfortunatly, when I try to attach with:
tmux attach
byobu attach
I get no results but a no session error. Moreover, with byobu-select-session I got a failed to connect to server instead.
There is a commant to connect tmux to a given socket, which I found using
lsof -U | grep '^tmux'. But still no session attached. My session files are in /tmp/user/tmux-1000/default, but I can see some sockets being used.
From ps aux I can see that byobu launches tmux with: tmux -2 -f /usr/share/byobu/profiles/tmuxrc new-session -n - /usr/bin/byobu-shell
Unfortunately, either with byobu -S path or byobu -L socketname I am not able to attach to previously open session, and byobu simply start a new session.
I run into a similar situation caused by accidentally removing the tmux socket in /tmp. The method described here solved the problem for me (either killall -SIGUSR1 tmux or kill -USR1 $PID_FOR_RUNNING_TMUX).

How to copy a tmux session from one machine to another?

Is it possible to export/import tmux sessions?
At the university we have identical machines (same binaries and file structure) and sometimes I want to move a tmux session from one machine to another. Is there a way to do this?
As pointed on the comments, it is very unlikely that you would be able to restore all the state of tmux session.
If your purpose is to access the tmux session from a different machine (hostB), while the tmux session is still running on the original machine (hostA), you could simple access it through ssh:
hostB $ ssh hostA
hostA $ tmux attach
The link you mentioned contains a discussion about how to re-create a tmux session. If you are interested in starting a similar tmux session, you should try tmuxinator:
# ~/.tmuxinator/sample.yml
name: sample
root: ~/
windows:
- editor:
layout: main-vertical
panes:
- vim
- guard
- server: ssh serverX
- logs: tail -f log/development.log
By issuing mux start sample you will have a tmux session with three windows:
the first with two panes, the first one running vim
the second with a ssh to a given server
the third displaying the tail of a log file
Using this file you could start similar sessions on different machines.

How to change an environment variable and apply to all windows in a tmux session

I wonder is there any easy way that I can change an bash environment variable and apply to windows in a tmux session?
I've googled and didn't found a solution so I post the question here.
Thanks!!
You can't directly change the environment variables.
However, you can make shell terminals inside a tmux instance pick up new variables. This requires a few steps.
First, tmux can update environment variables in itself. The update-environment configuration directive does this. Any variable listed here will be auto-udpated - connecting to a tmux session updates the session's environment variable with the value from the client you just connected. So if you run tmux attach, and have SSH_AUTH_SOCK set, then the tmux session will get the new value of SSH_AUTH_SOCK.
However, that only updates the session's variables, so only new panes/windows will get the values. Existing windows will still have the old values. As #IgnacioVazquez-Abrams said, there is not a direct fix to this.
However, you can fix it in many programs. Sufficiently recent versions of tmux have a show-environment command, which queries the session for the current values of an environment variable. This allows you to get the environment variable from within a program after it has been with the update-environment logic.
For instance, you can have some shells pick up the new value. In ZSH, I do this with a precmd hook in ~/.zshrc:
_update_ssh_agent() {
local var
var=$(tmux show-environment |grep '^SSH_AUTH_SOCK=')
if [ "$?" -eq 0 ]; then
eval "$var"
fi
}
if [[ -n "$TMUX" ]]; then
add-zsh-hook precmd _update_ssh_agent
fi
This makes it so that shells inside tmux sessions update the SSH agent every time they go to display a new prompt. After I reconnect, all I have to do is hit enter at a prompt and it grabs the new SSH agent connection.
Bash also has a pre-command mechanism, although I do not know how to configure it off-hand. You could additionally configure more programs to use show-environment to update themselves, such as vim or emacs. However, you will need to configure each program you might want to do this with separately.
No.
And there isn't even a hard way; manipulating the environment variables of another process is non-portable at best.
So this is an old question, but came up when I was searching for what I wanted to do, so here's another solution.
When tmux is started, it copies the environment into a global environment. When new windows are created, it merges the global environment with the session environment to set the environment for that window. We can view these environments with:
tmux show-environment [-g] [-t target-session]
Even better, we can also update the environments, even from within the windows' own tmux session:
tmux set-environment [-gru] [-t target-session] name [value]
For a full explanation of the flags, see the tmux man page.
This feature was exactly what I wanted. Unfortunately it won't update the environment of existing shells, but we could easily loop over tmux showenv -g to re-export the tmux environment that might be set by another process.
Here was my use-case:
With the way I have my shell configuration set up, I export my environment in a login shell, and then exec into a tmux session. I figure since env vars don't change often, I don't need to source them in new non-login shells every time. However, when they do change, I don't want to restart my entire tmux session to have new tmux windows know about the change. While using the update-environment option and re-attaching solves a session restart, it's cumbersome to maintain an explicit list of potentially malleable env vars in my tmux configuration.
With the following function, we can update our environment variables in something like ~/.shenv for example, and instead of sourcing the file (. ~/.shenv), we can promote the file (promote ~/.shenv) for new tmux windows to inherit from this updated environment.
promote() {
sourced="$1"; shift
. "$sourced"
env - \
"HOME=$HOME" \
sh -c ". $sourced; env" | cut -d= -f1 | while read -r var; do
val="$(eval "echo \"\$$var\"")"
tmux set-environment -gt local "$var" "$val"
done
}
What's happening here is we're sourcing our file from within a shell with an empty environment (apart from the HOME we add), and print out our new env vars. We pipe those into a cut to extract the variable of each line, storing it in a variable called var. After some meta magic with eval to get the indirect value of that variable from the current shell, we update our tmux target session. In this case, local is the name of our tmux session.
After wrestling with different solutions, I came up with this bash function added to my .bashrc file:
if [[ -n $TMUX ]]; then
_fix_ssh_agent_in_tmux () { if [[ ! -S $SSH_AUTH_SOCK ]]; then eval export $(tmux show-env | grep SSH_AUTH_SOCK); fi }
ssh () { _fix_ssh_agent_in_tmux; command ssh $#; }
scp () { _fix_ssh_agent_in_tmux; command scp $#; }
rsync () { _fix_ssh_agent_in_tmux; command rsync $#; }
fi
If the shell is running within tmux, it redefines 'ssh' to a bash function that tests and fixes SSH_AUTH_SOCK before actually running the real ssh command.
Note that tmux show-env -g also returns a value for SSH_AUTH_SOCK but that one is stale, I assume it's from whenever the tmux server started. The command above queries the current tmux session' environment which seems to be correct.
I'm using tmux 2.6 (ships with with Ubuntu 18.04) and it seems to work well.

Resources