In some of my build scripts I've been using mount namespaces as a mechanism to safely mount without ever leaving these mounts behind when the script terminates. Unshared mount points are implicitly unmounted when the last process in that namespace exits.
My scripts usually include a stansa such as this:
#!/bin/bash
self_ns=$(ls -lh /proc/self/ns/mnt)
init_ns=$(ls -lh /proc/$PPID/ns/mnt)
if [ "${self_ns#*mnt:}" = "${init_ns#*mnt:}" ] ; then
unshare --mount $0 "$@"
exit $?
fi
While this has worked fine for me for some time I've recently run into a problem on a jenkins build server.
I believe the issue there is that the build script itself is being executed inside a jenkins chroot environment. So when the script executes unshare --mount ...
, it fails with the error:
unshare: cannot change root filesystem propagation: Invalid argument
Unfortunately I really don't understand this restriction or how to get round it. When I try a chroot on the command line I can't replicate this error. I don't know what the jenkins plugin has done to cause this.
The most important thing is that these mount points are removed on exit every time without fail.
mount --make-rprivate /
. Which is something you want. Or at least you wantmount --make-rslave /
. The exact thingunshare
does here is controlled by the--propagation
option. – sourcejedi Nov 26 '19 at 15:58man 2 mount
, but I don't think any of those explain your problem. – sourcejedi Nov 26 '19 at 16:15unshare
itself fails. But I haven't been able to construct a chroot environment that does the same from the command line. – Philip Couling Nov 26 '19 at 16:16unshare --mount bash
. If I first bind mount (--private) this directory elsewhere and then do the chroot there,unshare --mount
then works. I don't know what this means, but I hope this can help find the cause or a workaround (adding a bind mount in the pipeline). – A.B Nov 26 '19 at 21:01mount --bind --make-private / /mnt
Thenchroot /mnt unshare --mount bash -c 'echo hello'
but notunshare --mount bash -c 'echo hello'
. Okay that's a viable work around, whatever the cause was. – Philip Couling Nov 28 '19 at 11:39