Все в порядке, но.
Этот текст мало кто будет читать и мы можем написать здесь все, что угодно, например.
Вы живете в неведении. Роботы уже вторглись в нашу жизнь и быстро захватывают мир, но мы встали на светлый путь и боремся за выживание человечества. А если серьезно, то.
В целях обеспечения безопасности сайта от кибератак нам необходимо убедиться, что вы человек. Если данная страница выводится вам часто, есть вероятность, что ваш компьютер заражен или вы используете для доступа IP адрес зараженных компьютеров.
Если это ваш частный компьютер и вы пытаетесь зайти на сайт, например, из дома — мы рекомендуем вам проверить ваш компьютер на наличие вирусов.
Если вы пытаетесь зайти на сайт, например, с работы или открытых сетей — вам необходимо обратиться с системному администратору и сообщить, что о возможном заражении компьютеров в вашей сети.
- © 2005-2023, «4PDA». 4PDA® — зарегистрированный товарный знак.
Overlay filesystem (Русский)
Состояние перевода: На этой странице представлен перевод статьи Overlay filesystem. Дата последней синхронизации: 27 мая 2020. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.
Overlayfs позволяет накладывать одно дерево каталогов (обычно доступное в режиме «чтение-запись») на другое, но с доступом только для чтения. Все изменения переходят на верхний слой с возможностью записи. Данная схема чаще всего используется с Live CD, но существует и множество других применений. Данная реализация отличается от других каскадно-объединённых файловых систем тем, что после открытия файла все операции направляются непосредственно в базовую, «нижнюю» или «верхнюю» файловую систему, что упрощает реализацию и не ухудшает производительность в данных случаях.
Overlayfs доступен в ядре Linux с версии 3.18.
Установка
Overlayfs включён в ядре по умолчанию, а модуль overlay автоматически подгружается после ввода команды монтирования.
Использование
Используйте следующие аргументы mount для монтирования overlay:
# mount -t overlay overlay -o lowerdir=/lower,upperdir=/upper,workdir=/work /merged
Примечание: Рабочий каталог ( workdir ) должен быть пустым и находиться в той же точке монтирования файловой системы, что и верхний каталог.
Нижняя директория может быть списком каталогов, разделённых : , все изменения в каталоге merged по-прежнему будут отражаться в upper .
# mount -t overlay overlay -o lowerdir=/lower1:/lower2:/lower3,upperdir=/upper,workdir=/work /merged
Примечание: Порядок монтирования папок lowerdir : слева-направо/сверху-вниз. То есть крайняя левая папка из списка будет смонтирована как самый верхний слой из lowerdir , а крайняя правая папка, соответственно, как самый нижний слой.
Таким образом порядок слоёв из вышеупомянутого примера будет следующим:
/upper /lower1 /lower2 /lower3
Используйте следующий формат, чтобы добавить запись overlayfs в /etc/fstab :
/etc/fstab
overlay /merged overlay noauto,x-systemd.automount,lowerdir=/lower,upperdir=/upper,workdir=/work 0 0
Параметры монтирования noauto и x-systemd.automount необходимы для предотвращения зависания systemd при загрузке, например, из-за ошибки монтирования overlay. Также overlay теперь будет монтироваться при первом обращении, а запросы будут буферизироваться до готовности самого overlay. Для получения дополнительной информации смотрите раздел Fstab (Русский)#Автоматическое монтирование с systemd.
Overlay только для чтения
Иногда необходимо создать представление из комбинации двух или более каталогов, доступное только для чтения. В этом случае его можно создать более простым способом, так как каталоги upper и work не обязательны:
# mount -t overlay overlay -o lowerdir=/lower1:/lower2 /merged
Когда upperdir не указан, overlay автоматически монтируется только для чтения.
Смотрите также
- Документация файловой системы Overlay
- Обзор OverlayFS — что она делает и как работает [устаревшая ссылка 2023-05-06 ⓘ]
- Wikipedia:OverlayFS
Overlay file system raspberry что это
i just notices that there is ‘overlay file system’ option in ‘raspi-config’. It must be some sort of new feature as did not notice that before.
My question is. If overlay in enabled, what folders are write protected?
Is it entire SD card or just part of it?
What about USB drive connected?
This feature would make my life much easier for testing purposes but i would like to be sure that if for example i will install tons of software while overlay is enabled, then after reboot my Raspbian will exaclty in the same state like it was before i turned overlay on.
Thanks for any clues in that matter.
dgordon42 Posts: 806 Joined: Tue Aug 13, 2013 6:55 pm Location: Dublin, Ireland
Re: Raspi-config, Overlay file system question.
Some more information on the Overlay File System here.
Hope this helps,
Dave.
Raspberry Pi Overlay Root Filesystem
This document describes a method to protect the root filesystem from writes while still allowing all applications to function as normal while writing to a temporary Overlay filesystem. Figuring this out would have been impossible for me without this excellent post by ejolson on the RPI.org forums.
For my installation I used a RPI 3 and the latest Raspbian Stretch Lite image (2017-11-29). I do not know if these instructions will work without modification on earlier RPI hardware.
Note: When the overlay filesystem is in place your RPI will function as usual, but any data generated after startup is only saved in RAM and will be lost upon reboot.
Let’s Begin
First we need to create a initramfs image that contains the overlay module and a boot script to mount our root partition with the overlay. (All this could of course be compiled into the kernel image, but initramfs-tools(8) is an easier way to learn about the early init-process.)
echo overlay >>/etc/initramfs-tools/modules
Place the following boot script in /etc/initramfs-tools/scripts/overlay (download):
# Local filesystem mounting -*- shell-script -*- # # This script overrides local_mount_root() in /scripts/local # and mounts root as a read-only filesystem with a temporary (rw) # overlay filesystem. # . /scripts/local local_mount_root() < local_top local_device_setup "$" "root file system" ROOT="$" # Get the root filesystem type if not set if [ -z "$" ]; then FSTYPE=$(get_fstype "$") else FSTYPE=$ fi local_premount # CHANGES TO THE ORIGINAL FUNCTION BEGIN HERE # N.B. this code still lacks error checking modprobe $ checkfs $ root "$" # Create directories for root and the overlay mkdir /lower /upper # Mount read-only root to /lower if [ "$" != "unknown" ]; then mount -r -t $ $ $ /lower else mount -r $ $ /lower fi modprobe overlay # Mount a tmpfs for the overlay in /upper mount -t tmpfs tmpfs /upper mkdir /upper/data /upper/work # Mount the final overlay-root in $rootmnt mount -t overlay \ -olowerdir=/lower,upperdir=/upper/data,workdir=/upper/work \ overlay $ >
Create the initramfs image:
update-initramfs -c -k $(uname -r)
It will be placed in /boot/initrd.img — you can rename it to match your kernel file if you want.
Add the following to /boot/config.txt — where initrd7.img is the initramfs image you created in the previous step:
kernel=kernel7.img initramfs initrd7.img
And finally, add boot=overlay to the beginning of /boot/cmdline.txt .
This should do it. Reboot and keep your fingers crossed.
Kernel Panic
If the OS doesn’t come back up, there is probably a typo somewhere, or you missed something.
You can remove boot=overlay from cmdline.txt to boot as normal.
A serial connection can be really handy when trying to troubleshoot the startup process. USB TTL console cables are dirt cheap, just make sure you get one that outputs 3.3V on the TX line so that you don’t fry your RPI. Use screen(1)’s buffer to scroll back and try to figure out where it went wrong.
The documentation is also quite good. Read the man page for initramfs-tools(8) and the default boot scripts themselves:
less /usr/share/initramfs-tools/init less /usr/share/initramfs-tools/scripts/local
Finishing Touches
Read-Only /boot
The /boot filesystem is still mounted rw . You can protect it as well by adding ro to the boot partitions mount options in /etc/fstab :
PARTUUID=72a9e9a9-01 /boot vfat defaults,ro 0 2
overctl
Since I would be updating the filesystem on my RPI regularly, I wanted a secure way to enable and disable the overlay. overctl has the following features:
Usage: overctl [-h|-r|-s|-t|-w] -h, --help This message -r, --ro Set read-only root with overlay fs -s, --status Show current state -t, --toggle Toggle between -r and -w -w, --rw Set read-write root
Place the script in /usr/local/sbin and mark the file as executable. You will also need to create the following files containing the cmdline.txt options that you wish to toggle between:
cp /boot/cmdline.txt /boot/cmdline.txt.orig cp /boot/cmdline.txt /boot/cmdline.txt.overlay
cmdline.txt.orig should contain your vanilla settings (so, no boot=overlay ), while /boot/cmdline.txt.overlay should include the boot=overlay directive. The overctl script merely copies the contents of either of these files into /boot/cmdline.txt as requested.
motd(5)
I figured I could use a reminder of which state the RPI is in. So I cobbled together this motd(5) script:
#!/bin/sh str=$(mount | grep ' on / ') if echo $str | grep -q 'overlay'; then printf "\n------ INFO: / MOUNTED WITH OVERLAY ------\n\n" elif echo $str | grep -q 'rw'; then printf "\n++++++ INFO: / MOUNTED READ-WRITE ++++++\n\n" else printf "\n. WARNING: / UNKNOWN STATE . \n\n" fi
Place the code above in /etc/update-motd.d/80-overlay and make sure the file is executable.