Debian Codegraph @

src/shared/snapshot-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/file.h>
4
5 #include "alloc-util.h"
6 #include "btrfs-util.h"
7 #include "discover-image.h"
8 #include "log.h"
9 #include "mountpoint-util.h"
10 #include "runtime-scope.h"
11 #include "snapshot-util.h"
12 #include "signal-util.h"
13 #include "tmpfile-util.h"
14
15 int create_ephemeral_snapshot(
16 const char *directory,
17 RuntimeScope scope,
18 bool read_only,
19 LockFile *tree_global_lock,
20 LockFile *tree_local_lock,
21 char **ret_new_path) {
22
23 _cleanup_free_ char *np = NULL;
24 int r;
25
26 assert(ret_new_path);
27
28 /* If the specified path is a mount point we generate the new snapshot immediately
29 * inside it under a random name. However if the specified is not a mount point we
30 * create the new snapshot in the parent directory, just next to it. */
31 r = path_is_mount_point(directory);
32 if (r < 0)
33 return log_debug_errno(r, "Failed to determine whether directory %s is mount point: %m", directory);
34 if (r > 0)
35 r = tempfn_random_child(directory, "snapshot.", &np);
36 else
37 r = tempfn_random(directory, "snapshot.", &np);
38 if (r < 0)
39 return log_debug_errno(r, "Failed to generate name for directory snapshot: %m");
40
41 /* We take an exclusive lock on this image, since it's our private, ephemeral copy
42 * only owned by us and no one else. */
43 r = image_path_lock(
44 scope,
45 np,
46 LOCK_EX|LOCK_NB,
47 scope == RUNTIME_SCOPE_SYSTEM ? tree_global_lock : NULL,
48 tree_local_lock);
49 if (r < 0)
50 return log_debug_errno(r, "Failed to lock %s: %m", np);
51
52 {
53 BLOCK_SIGNALS(SIGINT);
54 r = btrfs_subvol_snapshot_at(AT_FDCWD, directory, AT_FDCWD, np,
55 (read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
56 BTRFS_SNAPSHOT_FALLBACK_COPY |
57 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
58 BTRFS_SNAPSHOT_RECURSIVE |
59 BTRFS_SNAPSHOT_QUOTA |
60 BTRFS_SNAPSHOT_SIGINT);
61 }
62 if (r < 0)
63 return log_debug_errno(r, "Failed to create snapshot %s from %s: %m", np, directory);
64
65 *ret_new_path = TAKE_PTR(np);
66
67 return 0;
68 }