">
 

What broke when we exported Linux file systems to macOS over NFS

Iniciado por joomlamz, Hoje at 11:25

Respostas: 1   |   Visualizações: 1

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Saudações à comunidade do **webmastersmz.com**. Como especialista em tecnologia, analisei o tópico sobre os desafios de exportar sistemas de ficheiros Linux via NFS (Network File System) para o macOS.

Este é um tema clássico, mas que continua a gerar "dores de cabeça" devido às diferenças fundamentais na forma como os dois sistemas operativos gerem permissões e metadados. Aqui estão os pontos principais da análise técnica:

### 1. Incompatibilidade de ACLs e Atributos Estendidos
O Linux utiliza primariamente permissões POSIX (`chmod`/`chown`), enquanto o macOS, embora seja baseado em BSD/Unix, faz um uso extensivo de **ACLs (Access Control Lists)** e atributos estendidos específicos do HFS+ ou APFS. Quando tentamos mapear estes sistemas através do protocolo NFS, ocorre frequentemente a perda de metadados críticos, resultando em erros de acesso ou ficheiros que não podem ser abertos pelo Finder.

### 2. O Problema do `idmapd` e Mapeamento de UID/GID
Um dos pontos mais críticos é a discrepância entre os IDs de utilizador (UID) e de grupo (GID). No Linux, é comum que o utilizador principal tenha o UID 1000. No macOS, o primeiro utilizador criado tem tipicamente o UID 501. Se o servidor NFS não estiver configurado com um `idmapd` (ID Mapping Daemon) robusto, o macOS verá os ficheiros como pertencentes a um utilizador desconhecido ou, pior, a `nobody`, impedindo a escrita ou execução.

### 3. Comportamento do Protocolo (NFSv3 vs NFSv4)
O NFSv3 é muitas vezes preferido pela sua simplicidade, mas carece de mecanismos de segurança avançados. O NFSv4, embora mais moderno e seguro, é extremamente sensível a configurações de DNS e ao domínio kerberos. A complexidade na resolução de nomes de utilizador no NFSv4 frequentemente causa latência e timeouts no macOS, que o Finder interpreta como "disco desligado" ou "permissão negada".

### 4. Bloqueio de Ficheiros (File Locking)
O macOS utiliza o protocolo NLM (Network Lock Manager) de forma muito rigorosa. Em ambientes NFS mal configurados, os bloqueios de ficheiros (locks) podem não ser libertados corretamente, levando a situações de *race condition* onde dois utilizadores ou processos tentam escrever no mesmo ficheiro simultaneamente, corrompendo a base de dados ou o conteúdo do ficheiro.

---

**Sugestão para o debate:**
Convido os membros do fórum a partilharem as vossas experiências. Alguém aqui já tentou contornar estas limitações usando **SMB/CIFS** como alternativa ao NFS para o macOS? Ou preferem utilizar soluções como o **SSHFS** (via MacFUSE) para ambientes de desenvolvimento? Quais foram as vossas estratégias para manter a consistência de permissões entre servidores de desenvolvimento Linux e máquinas locais macOS? Vamos discutir as vossas soluções!

---

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da **AplicHost** em https://aplichost.com.

What broke when we exported Linux file systems to macOS over NFS



Tópico: What broke when we exported Linux file systems to macOS over NFS
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
We build a Mac app that opens NTFS, Ext4 and XFS drives. The approach is a bit unusual, so this is a write-up of the parts that surprised us.

The setup: a small Linux VM on Apple's Virtualization framework mounts the disk with the real Linux file system drivers (a 6.18 kernel in a Buildroot image), and the host mounts the result over NFS so it shows up in Finder. On macOS 15 and later the disk reaches the VM as a USB mass-storage device. On macOS 12 to 14 that hot-plug isn't available, so we serve the raw disk over NBD on vsock. The guest's root file system is read-only and checked against a hash list at every boot, its firewall drops everything by default, and NFS is exported only to the host's gateway address.

On paper that's the whole thing. In practice, these are the things that cost us the most time.



NFSv4 looked right and wasn't


We started with NFSv4 and had to back out. The macOS NFSv4 client refuses extended attributes with EPERM instead of falling back to ._ files the way it does on v3. In our tests in November, Word opened files read-only, Office, WPS, Pages and Numbers couldn't save, and tags and quarantine flags couldn't be written at all.

So the guest now runs NFSv3 only:

rpc.nfsd -N 4 -N 4.1 -N 4.2
# nfs.conf: vers4=n

Each disk gets its own export, to the gateway address only, with all_squash and its own random fsid.



Finder names the volume after the last path component


Finder names an NFS volume after the last component of the mount path, so every disk showed up with the name of our session id (something like d5). The fix is a bit silly: the guest creates a symlink named after the disk that points to the real session directory, and the host mounts the symlink, because mountd resolves it. Also, right after an export starts, mountd sometimes refuses the first mount with "Permission denied", so the host retries three times.



ntfs3 keeps the important bits in the page cache


With NTFS through the kernel's ntfs3 driver, the bitmap, the directory index and the MFT mirror stay in the page cache for a while. If you pull the drive soon after a write, you can get a volume that ntfsfix can't repair. The guest now calls syncfs every couple of seconds whenever there is unwritten data, which also clears the volume's dirty flag.



Eject took 40 seconds


After the Mac unmounted a volume, nfsd inside the guest kept it busy for a minute or more. We checked open files, NFSv4 open/lock/delegation state, the export cache and the client objects. None of them was it, and NFSv3 behaved the same. The only thing that released the disk immediately was restarting the nfsd threads. So on the first refused unmount we wait two seconds, restart the threads with a short grace period, and try again. Eject went from about 40 seconds to 1 or 2. We still don't know what exactly holds the volume. Our guess is nfsd's file cache.

A related one: to take a disk out of NFS you need exportfs -u '*:<path>'. Just editing /etc/exports and running exportfs -r leaves the kernel's export entry in place, and an NTFS disk then took 20 to 30 seconds to let go. With -u it takes under a second.



Office leaves empty folders behind


Office saves through temporary folders with names like <name>.sb-<hex>-<hex>. When the old version is still open, the Mac's NFS client turns a delete into a .nfs.* rename, so the folder can't be removed, and empty folders pile up after the document closes. The engine watches the mounted volume with FSEvents and removes empty ones after ten seconds of quiet. It only ever calls rmdir, so it can't delete anything with content.



What it costs


On one Apple silicon Mac running macOS 27, the first disk shows up in Finder about 4.5 seconds after you plug it in, including starting the background engine. The second takes about 2. The VM uses roughly 0.8 GB of memory while a disk is open.

Things that don't work: deleting in Finder is permanent, because NFS volumes have no Trash. Ext4 casefold directories and fscrypt aren't supported, XFS has to be v5, and ZFS only works for single-disk pools.

We're not the only ones doing this. anylinuxfs uses the same idea (libkrun plus NFS), is free and open source, and is worth a look if you're comfortable in Terminal on an Apple silicon Mac.

I work on CrossDriver, the app this comes from. The free version opens NTFS, Ext4, XFS, Btrfs, F2FS and ZFS read-only with no time limit and no sign-up: https://fs.crossdriver.com/en/omni/?utm_source=devto&utm_medium=article&utm_campaign=articles


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: