File: 4000-zsys-support.patch

package info (click to toggle)
zfs-linux 2.0.3-9%2Bdeb11u1
  • links: PTS, VCS
  • area: contrib
  • in suites: bullseye
  • size: 54,364 kB
  • sloc: ansic: 365,663; sh: 57,417; asm: 8,996; python: 8,652; makefile: 5,521; perl: 770; sed: 41; awk: 5
file content (400 lines) | stat: -rw-r--r-- 14,503 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
Description: Support zsys systems
 Zsys is an enhanced and structured dataset layout for ZFS.
 .
 It enables advanced use cases by differentiating system,
 user data and persistent partitions to allow only partial
 permanent or temporary rollback without destroying intermediate
 snapshots.
Author: Jean-Baptiste Lallement <jean.baptiste@ubuntu.com>
        Didier Roche <didrocks@ubuntu.com>
Last-Update: 2019-06-06
Index: zfs-linux-2.0.1/etc/systemd/system-generators/zfs-mount-generator.in
===================================================================
--- zfs-linux-2.0.1.orig/etc/systemd/system-generators/zfs-mount-generator.in
+++ zfs-linux-2.0.1/etc/systemd/system-generators/zfs-mount-generator.in
@@ -29,6 +29,8 @@ FSLIST="@sysconfdir@/zfs/zfs-list.cache"
 
 [ -d "${FSLIST}" ] || exit 0
 
+OLD_IFS=$IFS
+
 do_fail() {
   printf 'zfs-mount-generator: %s\n' "$*" > /dev/kmsg
   exit 1
@@ -137,6 +139,9 @@ process_line() {
     fi
   done
 
+  # Escape the mountpoint per systemd policy.
+  mountfile="$(systemd-escape --path --suffix=mount "${p_mountpoint}")"
+
   if [ -n "${p_systemd_after}" ] && \
       [ "${p_systemd_after}" != "-" ] ; then
     after="${p_systemd_after} ${after}"
@@ -162,6 +167,62 @@ process_line() {
       [ "${p_encroot}" != "-" ] ; then
     keyloadunit="zfs-load-key-$(systemd-escape "${p_encroot}").service"
     if [ "${p_encroot}" = "${dataset}" ] ; then
+
+      # Automount and unmount ZSys USERDATA datasets with keystore
+      zsys_automount=0
+      automount_loadkey_extra_args=""
+      automount_pool=""
+      automount_user=""
+      if echo "${dataset}" | grep -q '/USERDATA/'; then
+        automount_pool=${dataset%%/*}
+        automount_user=${dataset##*/}
+        # Only operate on user dataset mountpoint itself and not its children
+        if ! echo "${automount_user}" | grep -q '/'; then
+          automount_user=${automount_user%%_*}
+          # Ensure we have a keystore
+          if [ -f "/run/keystore/${automount_pool}/${automount_user}.enc" -a -x /usr/sbin/user_keystore ]; then
+            zsys_automount=1
+          fi
+        fi
+      fi
+
+      # Create automount unit and keystore tracker
+      if [ ${zsys_automount} -eq 1 ]; then
+        automountunit="$(systemd-escape --path --suffix=automount "${p_mountpoint}")"
+      echo \
+"# Automatically generated by zfs-mount-generator
+
+[Unit]
+Description=Automount ZFS user home for ${dataset} on demand
+
+[Automount]
+Where=${p_mountpoint}
+TimeoutIdleSec=10
+
+[Install]
+WantedBy=local-fs.target
+"   > "${dest_norm}/${automountunit}"
+        create_dependencies "${automountunit}" "wants" "local-fs.target"
+
+        keystoreunit="zfs-keystore-$(systemd-escape "${p_encroot}").service"
+        automount_loadkey_extra_args="BindsTo=${mountfile}
+BindsTo=${keystoreunit}
+After=${keystoreunit}"
+        echo \
+"# Automatically generated by zfs-mount-generator
+
+[Unit]
+Description=Make available ZFS encryption key for ${dataset} from keystore
+ConditionPathExists=/run/keystore/${automount_pool}/${automount_user}.enc
+BindsTo=${keyloadunit}
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStop=/usr/sbin/user_keystore lock ${automount_pool} ${automount_user}
+"   > "${dest_norm}/${keystoreunit}"
+      fi
+
       keymountdep=""
       if [ "${p_keyloc%%://*}" = "file" ] ; then
         if [ -n "${requiredmounts}" ] ; then
@@ -217,6 +278,7 @@ Wants=${wants}
 After=${after}
 ${requires}
 ${keymountdep}
+${automount_loadkey_extra_args}
 
 [Service]
 Type=oneshot
@@ -269,9 +331,6 @@ ExecStop=${keyunloadcmd}"   > "${dest_no
     do_fail "invalid mountpoint for ${dataset}"
   fi
 
-  # Escape the mountpoint per systemd policy.
-  mountfile="$(systemd-escape --path --suffix=mount "${p_mountpoint}")"
-
   # Parse options
   # see lib/libzfs/libzfs_mount.c:zfs_add_options
   opts=""
@@ -458,6 +517,87 @@ Options=defaults${opts},zfsutil" > "${de
 
 }
 
+ZPOOL_CACHE="@sysconfdir@/zfs/zpool.cache"
+PROPS="name,mountpoint,canmount,atime,relatime,devices,exec\
+,readonly,setuid,nbmand,encroot,keylocation\
+,org.openzfs.systemd:requires,org.openzfs.systemd:requires-mounts-for\
+,org.openzfs.systemd:before,org.openzfs.systemd:after\
+,org.openzfs.systemd:wanted-by,org.openzfs.systemd:required-by\
+,org.openzfs.systemd:nofail,org.openzfs.systemd:ignore"
+zsys_revert_failed=0
+errfile="/tmp/zsys-revert-out.log"
+
+drop_emergency_on_failure() {
+  if [ ${zsys_revert_failed} -eq 0 ]; then
+    return
+  fi
+
+  # Drop to emergency target in case of failure after cleanup fstab mountpoints.
+  # This avoids booting and having a mix of old and new datasets, and creating directory in the wrong
+  # datasets, like /boot/grub in / which will prevent zfs to mount /boot dataset later on.
+  rm -f "${dest_norm}"/*.mount
+  ln -s /lib/systemd/system/emergency.target "${dest_norm}"/default.target
+
+  printf 'ERROR: zfs-mount-generator failed and you requested a revert:\n' > /dev/kmsg
+  cat "${errfile}" > /dev/kmsg
+  printf 'You can reboot on current master dataset to fix the issue\n' > /dev/kmsg
+}
+
+# Handle revert so that zsys prepares all datasets as expected.
+initzsys() {
+  if [ ! -x @sbindir@/zsysd ]; then
+    return
+  fi
+
+  # Non ZFS system
+  if ! grep -q "root=ZFS=" /proc/cmdline; then
+    return
+  fi
+
+  # If we boot on the same dataset than last time, assume we don’t need to do anything as the cache file will only
+  # import desired pools.
+  bootds="$(sed -e 's/.*root=ZFS=\([^ ]\+\).*/\1/' /proc/cmdline)"
+  if grep -Eq "${bootds}\s+/\s+on" "${FSLIST}/"*; then
+      return
+  fi
+
+  # If we get here: we are reverting. Let zsys handle it
+  trap drop_emergency_on_failure EXIT INT QUIT ABRT PIPE TERM
+
+  exec 3>&1 1>"${errfile}"
+  exec 4>&2 2>&1
+
+  zsys_revert_failed=1
+  # Import and list previously imported pools for zsys
+  if [ -f "${ZPOOL_CACHE}" ]; then
+    @sbindir@/zpool import -c "${ZPOOL_CACHE}" -aN
+  # As a best effort, import all available pools, hoping there is no conflict.
+  else
+    echo "We had to search for all available pools because ${ZPOOL_CACHE} doesn't exist. To avoid this, create a zpool cache file."
+    @sbindir@/zpool import -aN
+  fi
+
+  @sbindir@/zsysd boot-prepare >"${errfile}"
+
+  # If FSLIST is empty, populate with all imported pools
+  if [ -z "$(ls -A ${FSLIST})" ]; then
+    @sbindir@/zpool list -H -o name | xargs -I{} touch ${FSLIST}/{}
+  fi
+
+  # Refresh zfs list cache
+  for cachefile in "${FSLIST}/"* ; do
+    pool=`basename ${cachefile}`
+    @sbindir@/zfs list -H -t filesystem -o "${PROPS}" -r "${pool}" >"${cachefile}"
+  done
+
+  exec 1>&3 3>&-
+  exec 2>&4 4>&-
+  zsys_revert_failed=0
+  rm "${errfile}"
+}
+
+initzsys
+
 for cachefile in "${FSLIST}/"* ; do
   # Disable glob expansion to protect against special characters when parsing.
   set -f
Index: zfs-linux-2.0.1/contrib/initramfs/scripts/zfs
===================================================================
--- zfs-linux-2.0.1.orig/contrib/initramfs/scripts/zfs
+++ zfs-linux-2.0.1/contrib/initramfs/scripts/zfs
@@ -64,6 +64,20 @@ get_fs_value()
 	"${ZFS}" get -H -ovalue "$value" "$fs" 2> /dev/null
 }
 
+# Get a ZFS filesystem property value with the source stripped from the value
+get_fs_value_without_source()
+{
+	value="$(get_fs_value $@)"
+	echo "${value%%:*}"
+}
+
+# Get a ZFS filesystem property source for a given key
+get_fs_source()
+{
+	value="$(get_fs_value $@)"
+	echo "${value#*:}"
+}
+
 # Find the 'bootfs' property on pool $1.
 # If the property does not contain '/', then ignore this
 # pool by exporting it again.
@@ -486,16 +500,17 @@ clone_snap()
 	snap="$1"
 	destfs="$2"
 	mountpoint="$3"
+	local additional_parameters="$4"
 
 	[ "$quiet" != "y" ] && zfs_log_begin_msg "Cloning '$snap' to '$destfs'"
 
+	if [ -n "${mountpoint}" ]; then
+		additional_parameters="${additional_parameters} -o mountpoint=${mountpoint}"
+	fi
+
 	# Clone the snapshot into a dataset we can boot from
-	# + We don't want this filesystem to be automatically mounted, we
-	#   want control over this here and nowhere else.
-	# + We don't need any mountpoint set for the same reason.
-	# We use the 'org.zol:mountpoint' property to remember the mountpoint.
-	ZFS_CMD="${ZFS} clone -o canmount=noauto -o mountpoint=none"
-	ZFS_CMD="${ZFS_CMD} -o org.zol:mountpoint=${mountpoint}"
+	ZFS_CMD="${ZFS} clone"
+	ZFS_CMD="${ZFS_CMD} -o canmount=noauto ${additional_parameters}"
 	ZFS_CMD="${ZFS_CMD} $snap $destfs"
 	ZFS_STDERR="$(${ZFS_CMD} 2>&1)"
 	ZFS_ERROR="$?"
@@ -606,6 +621,15 @@ setup_snapshot_booting()
 	snapname="${snap##*@}"
 	ZFS_BOOTFS="${rootfs}_${snapname}"
 
+	# Detect if we are on a zsys system, which will generates an unique UUID
+	# and override ZFS_BOOTFS
+	use_zsys=$(get_fs_value_without_source "${rootfs}" com.ubuntu.zsys:bootfs)
+	if [ "$use_zsys" = "yes" ]; then
+		zsys_uid=`uid`
+		ZFS_BOOTFS="${rootfs%_*}_${zsys_uid}" # we strip old uid and add new one
+	fi
+
+	# Rollback won't have effect on zsys system
 	if ! grep -qiE '(^|[^\\](\\\\)* )(rollback)=(on|yes|1)( |$)' /proc/cmdline
 	then
 		# If the destination dataset for the clone
@@ -635,10 +659,18 @@ setup_snapshot_booting()
 			#       rpool/ROOT/debian/boot@snap2	=> rpool/ROOT/debian_snap2/boot
 			#       rpool/ROOT/debian/usr@snap2	=> rpool/ROOT/debian_snap2/usr
 			#       rpool/ROOT/debian/var@snap2	=> rpool/ROOT/debian_snap2/var
+			#
+			# For zsys, we have stable root dataset names with uid, so:
+			#       rpool/ROOT/debian_uid1@snap2		=> rpool/ROOT/debian_uid2
+			#       rpool/ROOT/debian_uid1/boot@snap2	=> rpool/ROOT/debian_uid2/boot
+
 			subfs="${s##$rootfs}"
 			subfs="${subfs%%@$snapname}"
 
 			destfs="${rootfs}_${snapname}" # base fs.
+			if [ "${use_zsys}" = "yes" ]; then
+				destfs="${rootfs%_*}_${zsys_uid}" # we strip old uid and add new one
+			fi
 			[ -n "$subfs" ] && destfs="${destfs}$subfs" # + sub fs.
 
 			# Get the mountpoint of the filesystem, to be used
@@ -655,9 +687,38 @@ setup_snapshot_booting()
 				fi
 			fi
 
+			# On non zsys:
+			# + We don't want this filesystem to be automatically mounted, we
+			#   want control over this here and nowhere else.
+			# + We don't need any mountpoint set for the same reason.
+			# + We use the 'org.zol:mountpoint' property to remember the mountpoint.
+			# On zsys:
+			# + We don't want this filesystem to be automatically mounted, when cloned
+			#   so, we set canmount=noauto. Zsys early boot will set the current datasets
+			#   to on, alongside other system datasets switch. This enables
+			#   zpool import -a -R /altroot to mount the whole system.
+			#   The initrd script is doing zpool import -N, so we are not impacted by setting
+			#   canmount=on on secondary boot.
+			# + We thus need the real mountpoint set for this reason (as we can't set it
+			#   once the system booted, even if the mountpoint didn't change)
+			# + We set additional parameters to zsys to mark datasets we want mount manually
+			#   at boot.
+			if [ "${use_zsys}" != "yes" ]; then
+				clone_additional_parameters="-o org.zol:mountpoint=${mountpoint}"
+				mountpoint=none
+			else
+				[ "$(get_fs_value_without_source "$s" com.ubuntu.zsys:bootfs)" != "yes" ] && continue
+				clone_additional_parameters="-o com.ubuntu.zsys:bootfs=yes"
+				# Only set mountpoint explicitely if it was locally set
+				# Keep the possibility to have mountpoint inherited for manual zfs snapshots without zsys involved, which
+				# will have an empty user propertie
+				local mountpoint_source="$(get_fs_source "$s" com.ubuntu.zsys:mountpoint)"
+				[ -n "${mountpoint_source}" -a "${mountpoint_source}" != "local" ] && mountpoint=""
+			fi
+
 			# Clone the snapshot into its own
 			# filesystem
-			clone_snap "$s" "${destfs}" "${mountpoint}" || \
+			clone_snap "$s" "${destfs}" "${mountpoint}" "${clone_additional_parameters}" || \
 			    retval=$((retval + 1))
 		fi
 	done
@@ -875,6 +936,38 @@ mountroot()
 		shell
 	fi
 
+	# ------------
+	# Open and mount luks keystore for any pools using one
+	CRYPTROOT=/scripts/local-top/cryptroot
+	# We already processed original crypttab by calling local-top. Only add zvol related ones now.
+	if [ -x "${CRYPTROOT}" ]; then
+	        TABFILE=/cryptroot/crypttab
+	        :>"${TABFILE}"
+		# Wait for all keystore devices in /dev/zvol to appear with a 5s timeout
+		timeout=50
+		NUMKS=$(zfs list -H -o name | grep '/keystore$' | wc -l)
+		while [ ${NUMKS} -ne $(find /dev/zvol/ -name 'keystore' | wc -l) ]; do
+			if [ $timeout -le 0 ]; then
+				break
+			fi
+			sleep .1
+			timeout=$((timeout - 1))
+		done
+		# Locate, then mount the keystore volumes
+		for ks in $(find /dev/zvol/ -name 'keystore'); do
+			[ ! -e "${ks}" ] && continue
+			pool="$(basename $(dirname ${ks}))"
+			echo "keystore-${pool} ${ks} none luks,discard" >> "${TABFILE}"
+		done
+		${CRYPTROOT}
+		for dev in $(find /dev/mapper -name 'keystore-*'); do
+			# Translate filename to path
+			storepath="/run/$(echo $(basename ${dev})|sed -e 's,-,/,')"
+			mkdir -p "${storepath}"
+			mount "${dev}" "${storepath}"
+		done
+	fi
+
 	# In case the pool was specified as guid, resolve guid to name
 	pool="$("${ZPOOL}" get name,guid -o name,value -H | \
 	    awk -v pool="${ZFS_RPOOL}" '$2 == pool { print $1 }')"
@@ -918,6 +1011,8 @@ mountroot()
 		# Booting from a snapshot?
 		# Will overwrite the ZFS_BOOTFS variable like so:
 		#   rpool/ROOT/debian@snap2 => rpool/ROOT/debian_snap2
+		#   or
+		#   rpool/ROOT/debian@snap2 => rpool/ROOT/debian_<uid> if selected system is a zsys one
 		echo "${ZFS_BOOTFS}" | grep -q '@' && \
 		    setup_snapshot_booting "${ZFS_BOOTFS}"
 	fi
@@ -955,8 +1050,16 @@ mountroot()
 	# Go through the complete list (recursively) of all filesystems below
 	# the real root dataset
 	filesystems=$("${ZFS}" list -oname -tfilesystem -H -r "${ZFS_BOOTFS}")
+
+	# If the root filesystem is a zsys one, we select the datasets to mount
+	# at boot.
+	# Some datasets under ROOT/ can be mounted on top of persistent datasets
+	# that are hosted elsewhere in the pool. Those are thus only mounted at
+	# early boot.
+	use_zsys=$(get_fs_value_without_source "${ZFS_BOOTFS}" com.ubuntu.zsys:bootfs)
 	for fs in $filesystems $ZFS_INITRD_ADDITIONAL_DATASETS
 	do
+		[ "$use_zsys" = "yes" -a "$(get_fs_value_without_source "$fs" com.ubuntu.zsys:bootfs)" != "yes" ] && continue
 		mount_fs "$fs"
 	done
 
@@ -1002,3 +1105,8 @@ mountroot()
 		fi
 	fi
 }
+
+uid()
+{
+	dd if=/dev/urandom of=/dev/stdout bs=1 count=100 2>/dev/null | tr -dc 'a-z0-9' | cut -c-6
+}