Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

linux%20administration/systemd-automount/ #5

Open
utterances-bot opened this issue Mar 15, 2021 · 29 comments
Open

linux%20administration/systemd-automount/ #5

utterances-bot opened this issue Mar 15, 2021 · 29 comments

Comments

@utterances-bot
Copy link

On-Demand NFS and Samba Connections in Linux with Systemd Automount - Ray Against the Machine

If you have a NAS, you probably want to be able to connect to it automatically each time you log into your Linux machine. Adding an entry to your fstab is great for desktops with persistent ethernet connections, but you quickly run into trouble using this method on a laptop that’s frequently jumping on and off the network. Your distribution’s file manager may have a way to do this, but wouldn’t it be nice to have a consistent method accross all modern distributions? Systemd to the rescue!

https://rayagainstthemachine.net/linux%20administration/systemd-automount/

Copy link

Hello Ray,

great post thanks for publishing it. I am just using NFS at home, because I have no windows computers.
I am new to systemd, but it is very powerful and start getting to use and to know it.

QUESTIONS:
following entries in my nfs-mount.mount I will NOT need (found them on other post)

[Unit]
Requires=systemd-networkd.service
After=network-online.target
Wants=network-online.target

instead for the automount i need the entry
[Unit]
Requires=network-online.target

COMMENTS:
If you do not specify the Entry
[Mount]
Where=/mnt/nfs/nfsshare

it will create the folder for you automatically (how that works with the permissions I have not tested yet, but that should be part of the exports entry (?) of the server having the NFS Share).

and last but not least the name of the file has to be the same as the path of the client you mount the NFS Share to it, just instead of / you use -
taking your example under

[Mount]
Where=/mnt/nfs/nfsshare <- the name has to be mnt-nfs-nfsshare.mount (and .automount) as it is shown in your example. But I did it not that way in the beginning.

@skoobasteeve
Copy link
Owner

skoobasteeve commented Mar 15, 2021

[Unit]
Requires=systemd-networkd.service
After=network-online.target
Wants=network-online.target

@uniquegch If you were ONLY using the .mount file and wanted your shares mounted automatically on every boot, you would still include the above lines to ensure that systemd doesn't try to mount before your system connects to the network. I don't include them since I'm using .automount files to only mount the shares when I open their path in in the file manager.

If you do not specify the Entry
[Mount]
Where=/mnt/nfs/nfsshare

it will create the folder for you automatically (how that works with the permissions I have not tested yet, but that should be part of the exports entry (?) of the server having the NFS Share).

This I've never tried but seems pretty cool assuming it works, in theory permissions would be handled by the export entry. Personally I prefer to specify exactly where everything goes and leave nothing to chance :).

Where=/mnt/nfs/nfsshare <- the name has to be mnt-nfs-nfsshare.mount (and .automount) as it is shown in your example. But I did it not that way in the beginning.

One of those weird systemd-isms that you'd only know by reading docs and blog posts!

Copy link

@skoobasteeve thanks for the detailed reply.

I adjusted the .mount file and created the .automount file for the NFS share, following this post.

Scenario

3 active raspberry pis with Mopidy, snapclient / snapserver and Iris installed (as multi room audio system) for playing music. the NFS share has all the ripped CDs (about 150) on my internal cloud.
I was curious to see if and when the NFS share with the music is being mounted when starting the pi with snapserver daemon and the mounting happend during the boot or more like (I assume) when the mopidy daemon started containing in the config file the path to the NFS share.

#Steps I did#

  • I unmounted the NFS share (it was shown in df -h, after that not anymore)
  • started the webbrowser,
  • entering IP@:6680/Iris
  • clicked on the section Album,
  • selected one Album randomly, (at this point the NFS mount was not shown in refreshed df -h)
  • clicked on a song to play and it played because the automat got triggered.

that is AWESOME.

@skoobasteeve
Copy link
Owner

@uniquegch that setup sounds so cool! I've been wanting an excuse to do a multi-room audio setup but alas I only have one room to work with 🙄. Currently using an RPi with Volumio and an NFS share and I like it a lot.

@Oxmel
Copy link

Oxmel commented May 2, 2021

@skoobasteeve Thank you for this really useful article. I had no idea one could mount on boot / on-demand a network share with systemd before stumbling upon your blog post.

Also, thanks to @uniquegch for having asked that question. I'm basically on the same boat (new to systemd, trying to use Mopidy with a cifs share) and your discussion has been a great help.

Copy link

charles-steiger commented Jun 8, 2021

@skoobasteeve

Your article is incredibly helpful. Thanks so much!

I have an observation and question.

  1. Observation: I believe this is a typo in the NFS instructions:

Existing example command has 'mnt-smb-nfsshare.automount'
$ sudo nano /etc/systemd/system/mnt-smb-nfsshare.automount

Maybe it should be 'mnt-nfs-nfsshare.automount'?
$ sudo nano /etc/systemd/system/mnt-nfs-nfsshare.automount

Please disregard the below question. As it turns out, the issue was on my NFS server filesystem permissions. 🤣 It was a good exercise for me.
2. Question: When I mount an NFS share, it works as expected; however, the mount point has uid=root and gid=root. I am learning a lot about Linux, but not sure what to do. I did review the article you mentioned, about systemd.unit, and searched a bit, but was wondering, is there some directive I need in the systemd unit file that will specify the uid and gid when the NFS share is mounted?

Example of ls -ld on mount point before mounted by systemd (note using uid and gid in this example instead of the username):
drwxr-xr-x 16 1000 1000 16 May 30 10:21 /mnt/point

Example of ls -ld on mount point after successfully mounted by systemd:
drwxr-xr-x 16 root root 16 May 30 10:21 /mnt/point

Thanks in advance for any help! Take care!

Copy link
Owner

@charles-steiger Thanks for catching that typo! Just fixed and found another in the process 🤣.

NFS is simpler on the client side but you have to make sure your permissions are correct server side.
Glad you got it working in the end!

Copy link

uniquegch commented Jun 14, 2021

Hello Ray,
I am interested in using NFS Version 4 with kerberos. But not sure on how to write the .mount and automount file.

Here from the website Nfsv4 configuration I took the example

Exporting directories
/export gss/krb5(rw,fsid=0,insecure,no_subtree_check) if server has internet access, the world can access it
/export gss/krb5i(rw,fsid=0,insecure,no_subtree_check)
/export gss/krb5p(rw,fsid=0,insecure,no_subtree_check)

that would the mount command on the client.
mount -t nfs4 -o sec=krb5 yourserver:/export /mnt/nfs4/

how would I write -o sec=krb5(i,p) in the mount files?

Thanks

@skoobasteeve
Copy link
Owner

skoobasteeve commented Jun 22, 2021

@uniquegch Not sure if you were able to resolve this by now, but in the mount file you should be able to place it under the Options section:

Options=defaults,sec=krb5(i,p)

Let me know if that works for you, I'm not running NFSv4 at home so i can't test.

Copy link

Can you update your automount instructions to more closely follow the systemd standards?

From the upstream project itself:

https://github.com/systemd/systemd

"Note that automount units are separate from the mount itself, so you should not set After= or Requires= for mount dependencies here. (...) Doing so may result in an ordering cycle."

In your guide for the automount files, you have Requires=network-online.target as an entry.

Copy link
Owner

@flansuse Thanks for pointing that out! After testing on my end I've removed that line from the instructions.

Copy link

rpgdev commented Apr 8, 2022

Is this supposed to work for system users as well? I'm trying to access a samba share with a system user and I'm having issues despite it being accessible to a regular user. User created with the following command: sudo useradd -r -m user

@skoobasteeve
Copy link
Owner

@rpgdev Were you able to resolve this?

@rpgdev
Copy link

rpgdev commented Apr 26, 2022

I had to make use of the cifs options in the automount and assign the uid and gid of that user but now other users, even ones belonging to that same gid don't seem to write to it.. so I still have the same problem I guess just swapped users.

Copy link

viertelb commented Jul 6, 2022

Thanks for the article. I did not know about the automount option. However, it does not solve my problem, which is that the NFS server might suspend if not used for some time. The mount stays on and thus an ls on the mountpoint - or even on the directory the mountpoint is in - will result in a hang. I was trying to find an option so that the client recognises an unresponsive mount. There is the soft option, but it is generally not recommended. Then there was hard/intr but the intr latter it is deprecated and in modern kernels ignored. Do you know about an option that will recognise the mountpoint beeing unresponsive and then unmount the mountpoint?

@skoobasteeve
Copy link
Owner

skoobasteeve commented Jul 7, 2022

@viertelb I don't know of any setting that accounts for a server going offline regularly. I suppose you could make a shortcut to stop the .mount service when you're done accessing the server. The command would be:

sudo systemctl stop nfs-service-name.mount

Out of curiosity, what kind of server are you accessing that spins down?

@viertelb
Copy link

It's probably not a good setup, but I have a snapraid server as an archive for large files and I just spin it up now and then.

@skoobasteeve
Copy link
Owner

@viertelb If you wanted to get creative, you could create a systemd timer that runs a script every X minutes to check if the server is online. If the server is online, it will mount the NFS share, and if it's offline, it will un-mount it. Something like this:

#!/bin/bash

nfs_server="10.0.10.179"

if ping -c 3 $nfs_server > /dev/null; then
    echo "NFS server is online!"
    systemctl start nfs-server-path.mount
else
    echo "NFS server is offline :("
    systemctl stop nfs-server-path.mount
fi

It's a little hacky but might be worth trying out.

Copy link

ktindle commented Oct 5, 2022

I've set up cifs automount successfully in Mint 20.3. Upgraded to 21.0. Now, the automount happens and systemd-resolved always returns SERVFAIL. No DNS. There is an autolaunch to the dbus with the gvfsd-dnssd daemon, and you're baked until a shutdown/restart. A script I wrote to mount the shares without involving systemd works and does not trigger the death of DNS- because it does not autolaunch that GNOME daemon. It might be possible to play with /etc/systemd/resolved.conf- here, I mean in the [Resolve] section add an IP for the "DNS=" line. But it's quite possible that what you are doing here is just not going to work in Mint 21.

@ivanmara555
Copy link

Hello Ray.

I would like to propose a simpler solution for non-persistent connections (on demand) based also on systemd, which does the same.

  1. create mount points on client host:
mkdir /mnt/smb.router.lan
mkdir /mnt/nfs.router.lan
  1. add this lines to /etc/fstab (key phrase: noauto):
# smb mount on demand
//router.lan/data /mnt/smb.router.lan cifs noatime,guest,uid=1000,gid=1000,noperm,actimeo=600,_netdev,noauto,x-systemd.automount,x-systemd.mount-timeout=5,x-systemd.idle-timeout=1min30sec 0 0

# nfs mount on demand
router.lan:/ /mnt/nfs.router.lan nfs noatime,nocto,actimeo=600,_netdev,noauto,x-systemd.automount,x-systemd.mount-timeout=5,x-systemd.idle-timeout=1min30sec 0 0
  1. reload systemd configurations:
systemctl daemon-reload
systemctl restart remote-fs.target
  1. use shared folders on demand.

How it works? After systemd reloading or reboot, systemd parse fstab and automatically recreates the units specified in your article (*.mount and *.automount) in folder:
/run/systemd/generator/
and the mechanism begins to work.

details in:
man systemd.automount (fstab)
man systemd.mount (fstab, recommendations for humans) ... )))
man systemd.unit (Unit File Load Path)

Copy link
Owner

@ivanmara555 I didn't know about the option to fstab with automount files. Very cool! I'll try it out the next time I reconfigure a system.

Copy link

rpgdev commented Feb 15, 2023

This approach for some reason affected my network when the targets were accessed and the shares mounted---it disconnected my network. After upgrading my system it seemed to be affecting my loopback interface in a way that it didn't get its address (127.0.0.1). I stoped the mounts and disabled them, restarted and haven't gotten the issue again.. Will try the fstab option proposed below once I figure out what all the modifiers mean.

Copy link

Hi,

thank you for this guide. I used it to automount my SMB share.
When the first mount is established, for some reason I loose connection to the internet. Restarting the connection fixes the issue and it seems not to return on reboot.

The second problem is more annoying though. For some reason the mounted share appears twice inside the file manager. Both have slighlty different symbols but show the same content. Right clicking and showing properties will open one window, acting like it's the same for both. If I show mounts on desktop the symbols appear there twice too.

Checking the mount command, shows that it is mounted twice:

systemd-1 on [MOUNTPOINT]

//my.server/smbshare on [MOUNTPOINT]

both mount on the same mount point. I don't really understand why. The only change I made, was to mount to /media/smb instead of /mnt/smb. This way I could be sure it would show up inside the file manager.

Do you have an explanation for this?

@ivanmara555
Copy link

ivanmara555 commented Sep 22, 2023

@Feelefant what metod are you use, fstab or manually create target files ? Before using systemd you must debug connection with mount command and necessary options for you situation.

Your linux distribution ?

Copy link

@ivanmara555 I manually created the unit files. I'm using Linux Mint. As it turns out there is a problem with the file manager under Linux Mint, which shows mounted shares twice if mounted to /home or /media. I now mounted on /mnt and created a bookmark to the share. That works fine.

My internet connection broke down again once, after reboot. I have to observe that. If it happens more often this problem will need fixing too.

@ivanmara555
Copy link

@Feelefant try apt full-update system

Then try fstab systemd mechanism as simpler and more transparent from my instruction:
#5 (comment)

Copy link

Hi folks, one day lost with this and all the mentioned steps have one big disadvantage, that when your laptop goes offline while is connected to the remote folder, you will have frozen Dolphin and other KDE components, included IO components as df, etc.

From this reason the only one really working way is doing your self script which will force umount all dead network targets.

Take it from my github and enjoy the totally simplicity.

https://github.com/tomasmark79/lazy_samba

@rpgdev
Copy link

rpgdev commented Jul 16, 2024

Hi folks, one day lost with this and all the mentioned steps have one big disadvantage, that when your laptop goes offline while is connected to the remote folder, you will have frozen Dolphin and other KDE components, included IO components as df, etc.

From this reason the only one really working way is doing your self script which will force umount all dead network targets.

Take it from my github and enjoy the totally simplicity.

https://github.com/tomasmark79/lazy_samba

@tomasmark79 Link says page not found, make sure it's a public repo.

@tomasmark79
Copy link

tomasmark79 commented Jul 16, 2024

I removed the repo.
From this reason I will share the script here:

#!/bin/bash
# Tomas Mark 2024 (tomas@digitalspace.name)

log() {
    if [ "$DEBUG" ]; then
        echo "-> $1"
    fi
}

umount_samba() {
    sudo umount -f -l "$MOUNT_POINT" >/dev/null 2>&1 # potlačení výstupu

    if [ $? -eq 0 ]; then
        log "Samba share was successfully unmounted from $MOUNT_POINT."
    else
        log "Samba share was already unmounted from $MOUNT_POINT."
    fi
}

# function to mount Samba share with parameters
# parameters: CREDENTIAL_FILE, SAMBA_SHARE, TARGET_IP, MOUNT_POINT, DEBUG
mount_samba() {
    CREDENTIAL_FILE=$1
    SAMBA_SHARE=$2
    TARGET_IP=$3
    MOUNT_POINT=$4
    DEBUG=$5
    LOCK_FILE="/tmp/mount_samba.lock"

    # Kontrola existence souboru zámku
    if [ -f "$LOCK_FILE" ]; then
        log "Skript je již spuštěn nebo nebyl korektně ukončen."
        exit 1
    else
        touch "$LOCK_FILE"
    fi

    # check if the destination IP is alive
    if ping -c 1 -W 1 "$TARGET_IP" >/dev/null; then
        log "The destination IP $TARGET_IP is accessible, connecting to Samba share..."

        # check if the share is already connected
        if mountpoint -q "$MOUNT_POINT"; then
            log "Samba share $SAMBA_SHARE already connected to $MOUNT_POINT."
        else
            # connection to Samba share
            sudo mount -t cifs -o noatime,guest,_netdev,vers=3.0,noauto,credentials=$CREDENTIAL_FILE,uid=1000,gid=1000,iocharset=utf8,sec=ntlmssp,nofail,soft,noperm "$SAMBA_SHARE" "$MOUNT_POINT"

            if [ $? -eq 0 ]; then
                log "Samba share $SAMBA_SHARE was successfully connected to $MOUNT_POINT."
            else
                log "Samba share $SAMBA_SHARE was unsuccessfully connected to $MOUNT_POINT. (Failed)"
            fi
        fi
    else
        log "The destination IP $TARGET_IP is not accessible."
        # This umount is neccessary here for unmount inaccessible drive
        sudo umount -f -l "$MOUNT_POINT"
    fi
    
    # Odstranění souboru zámku po dokončení
    rm -f "$LOCK_FILE"
}

# main script body
echo ""
timestamp=$(date +"%Y-%m-%d %H:%M:%S")
echo "Script started at $timestamp"

# call function mount_samba with parameters
# /root/credential2nas is the path to the credential file
mount_samba "/root/credential2nas" "//192.168.79.11/homes" "192.168.79.11" "/mnt/nas/" 1
mount_samba "/root/credential2nas" "//192.168.79.11/music" "192.168.79.11" "/mnt/nas/music" 1
mount_samba "/root/credential2nas" "//192.168.79.11/video" "192.168.79.11" "/mnt/nas/video" 1
mount_samba "/root/credential2nas" "//192.168.79.11/NetBackup" "192.168.79.11" "/mnt/nas/NetBackup" 1
mount_samba "/root/credential2pc" "//192.168.79.111/c" "192.168.79.111" "/mnt/pc/c" 1
#mount_samba "/root/credential2pc" "//192.168.79.111/d" "192.168.79.111" "/mnt/pc/d" 1
mount_samba "/root/credential2pc" "//192.168.79.111/f" "192.168.79.111" "/mnt/pc/f" 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests