Skip to main content

alpm_db/db/
transaction.rs

1//! Transaction representation in [alpm-db].
2//!
3//! A transactio describes a set of additions and/or removals, that are executed in sequence.
4//!
5//! [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
6
7use std::{
8    fmt::Display,
9    fs::{
10        File,
11        OpenOptions,
12        Permissions,
13        copy,
14        create_dir,
15        create_dir_all,
16        remove_dir_all,
17        remove_file,
18        rename,
19        set_permissions,
20    },
21    io::Write,
22    os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt, chown},
23    path::{Path, PathBuf},
24};
25
26use alpm_types::EntryName;
27use fluent_i18n::t;
28use log::debug;
29use nix::unistd::{getegid, geteuid};
30use serde::{Deserialize, Serialize};
31use uuid::Uuid;
32
33use crate::db::{
34    DIR_MODE,
35    DatabaseConfig,
36    EntrySource,
37    Error,
38    entry::{EntryComponent, EntryComponentType},
39};
40
41/// An action item in a transaction plan for an [alpm-db].
42///
43/// This may be an addition or a removal.
44///
45/// # Note
46///
47/// An [`ActionItem`] only tracks what database item changed in an action, not the actual data.
48/// Refer to [`Action`] for transaction items, that are used for changing an [alpm-db].
49///
50/// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
51#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
52#[serde(rename_all = "lowercase")]
53enum ActionItem {
54    /// A package is added.
55    Add(EntryName),
56
57    /// A package is removed.
58    Remove(EntryName),
59}
60
61impl From<&Action> for ActionItem {
62    fn from(value: &Action) -> Self {
63        match value {
64            Action::Add(entry) => Self::Add(entry.entry_name()),
65            Action::Remove(entry) => Self::Remove(entry.clone()),
66        }
67    }
68}
69
70/// The plan of a transaction in an [alpm-db].
71///
72/// A transaction plan consists of one or more action items and serves as a persisted plan of
73/// "what is done in a transaction".
74///
75/// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
76#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
77struct TransactionPlan {
78    uuid: Uuid,
79    actions: Vec<ActionItem>,
80    #[serde(skip)]
81    data_dir: PathBuf,
82}
83
84impl TransactionPlan {
85    /// Returns a reference to the UUID of the transaction plan.
86    pub fn uuid(&self) -> Uuid {
87        self.uuid
88    }
89
90    /// Returns the on-disk file name of the transaction plan.
91    pub fn file_name(&self) -> String {
92        format!("{}.json", self.uuid)
93    }
94
95    /// Writes `Self` as JSON encoded file in the "current" location of the data dir.
96    ///
97    /// # Errors
98    ///
99    /// Returns an error, if
100    ///
101    /// - the transaction plan cannot be turned into a JSON string
102    /// - the output file cannot be opened for writing
103    /// - the transaction plan cannot be written to the output file
104    pub fn write_to_current_dir(&self) -> Result<(), crate::Error> {
105        let path = self
106            .data_dir
107            .join(Transaction::CURRENT_DIR)
108            .join(self.file_name());
109        let data = serde_json::to_string(&self).map_err(|source| crate::Error::Json {
110            context: t!("error-json-transaction-plan", { "uuid" => self.uuid.to_string() }),
111            source,
112        })?;
113
114        let mut file = OpenOptions::new()
115            .create_new(true)
116            .write(true)
117            .mode(0o644)
118            .open(&path)
119            .map_err(|source| crate::Error::IoPath {
120                path: path.clone(),
121                context: t!("error-io-path-open-writable"),
122                source,
123            })?;
124
125        file.write_all(&data.into_bytes()).map_err(|source|
126            crate::Error::IoPath {
127                path: path.clone(),
128                context: t!("error-io-path-write-transaction-plan", { "uuid" => self.uuid.to_string() }),
129                source
130            })?;
131
132        Ok(())
133    }
134
135    /// Moves the "current" transaction plan to the "past" location of the data dir.
136    ///
137    /// # Errors
138    ///
139    /// Returns an error, if the current transaction plan cannot be moved (e.g. because it has not
140    /// yet been persisted - see [`Self::write_to_current_dir`]).
141    pub fn move_to_past_transaction_dir(&self) -> Result<(), crate::Error> {
142        // Move transaction plan from current to previous location.
143        rename(
144            self.data_dir
145                .join(Transaction::CURRENT_DIR)
146                .join(self.file_name()),
147            self.data_dir
148                .join(Transaction::PAST_DIR)
149                .join(self.file_name()),
150        )
151        .map_err(|source| crate::Error::IoPath {
152            path: self
153                .data_dir
154                .join(Transaction::CURRENT_DIR)
155                .join(self.file_name()),
156            context: t!("error-io-path-move-transaction-plan", { "uuid" => self.uuid().to_string() }),
157            source,
158        })
159    }
160}
161
162impl From<&Transaction> for TransactionPlan {
163    fn from(value: &Transaction) -> Self {
164        Self {
165            uuid: value.uuid,
166            actions: value.actions.iter().map(Into::into).collect(),
167            data_dir: value.data_dir.clone(),
168        }
169    }
170}
171
172/// A file-based lock to prevent concurrent write access to a database.
173#[derive(Debug)]
174pub(crate) struct WriteLock {
175    /// The path to the lock file.
176    path: PathBuf,
177
178    /// The file handle for `path`.
179    file: File,
180}
181
182impl WriteLock {
183    /// The default file mode of the lock file.
184    const DEFAULT_FILE_MODE: u32 = 0o100000;
185
186    /// Creates a new [`WriteLock`] at a specific `path`.
187    ///
188    /// # Errors
189    ///
190    /// Returns an error, if
191    ///
192    /// - the lock file cannot be created at `path` (e.g. because it already exists)
193    /// - exclusive access to the file cannot be established
194    pub fn new(path: impl AsRef<Path>) -> Result<Self, crate::Error> {
195        let path = path.as_ref();
196        debug!("Create an alpm-db lock file at {path:?}");
197
198        let file = OpenOptions::new()
199            .write(true)
200            .create_new(true)
201            .mode(Self::DEFAULT_FILE_MODE)
202            .open(path)
203            .map_err(|source| crate::Error::IoPath {
204                path: path.to_path_buf(),
205                context: t!("error-io-path-db-lock-create"),
206                source,
207            })?;
208        file.try_lock()
209            .map_err(|source| Error::DatabaseFailedExclusiveLockFile {
210                path: path.to_path_buf(),
211                source,
212            })?;
213
214        Ok(Self {
215            path: path.to_path_buf(),
216            file,
217        })
218    }
219
220    /// Releases and removes the lock file and consumes [`Self`].
221    ///
222    /// # Errors
223    ///
224    /// Returns an error, if
225    ///
226    /// - the lock file cannot be released
227    /// - the lock file cannot be deleted
228    pub fn remove(self) -> Result<(), crate::Error> {
229        self.file.unlock().map_err(|source| crate::Error::IoPath {
230            path: self.path.clone(),
231            context: t!("error-io-path-db-lock-release"),
232            source,
233        })?;
234
235        remove_file(&self.path).map_err(|source| crate::Error::IoPath {
236            path: self.path.clone(),
237            context: t!("error-io-path-db-lock-delete"),
238            source,
239        })?;
240
241        Ok(())
242    }
243}
244
245impl AsRef<Path> for WriteLock {
246    fn as_ref(&self) -> &Path {
247        &self.path
248    }
249}
250
251/// Creates a new file handle at `path` for writing an entry component.
252///
253/// The file mode is compatible with alpm-db entry components.
254///
255/// # Errors
256///
257/// Returns an error, if a new file cannot be created for writing at `path`.
258fn create_entry_component(path: impl AsRef<Path>) -> Result<File, crate::Error> {
259    let path = path.as_ref();
260    debug!("Creating alpm-db entry component {path:?}");
261
262    OpenOptions::new()
263        .create_new(true)
264        .write(true)
265        .mode(EntryComponent::FILE_MODE)
266        .open(path)
267        .map_err(|source| crate::Error::IoPath {
268            path: path.to_path_buf(),
269            context: t!("error-io-path-db-create-component"),
270            source,
271        })
272}
273
274/// Writes an `entry` to a directory `path`.
275///
276/// This function is used to create a new entry for the root directory of an [alpm-db].
277///
278/// # Errors
279///
280/// Returns an error, if
281///
282/// - the [alpm-db-desc] data of the [`EntrySource`] implementation cannot be retrieved
283/// - the [alpm-db-files] data of the [`EntrySource`] implementation cannot be retrieved
284/// - the [ALPM-MTREE] data of the [`EntrySource`] implementation cannot be retrieved
285/// - an error occurs while attempting to retrieve the optional [alpm-install-scriptlet] data
286///
287/// [ALPM-MTREE]: https://alpm.archlinux.page/specifications/ALPM-MTREE.5.html
288/// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
289/// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
290/// [alpm-db-files]: https://alpm.archlinux.page/specifications/alpm-db-files.5.html
291/// [alpm-install-scriptlet]: https://alpm.archlinux.page/specifications/alpm-install-scriptlet.5.html
292fn write_entry_to_dir(
293    entry: Box<dyn EntrySource>,
294    path: impl AsRef<Path>,
295) -> Result<(), crate::Error> {
296    let alpm_db_desc = entry.alpm_db_desc()?;
297    let alpm_db_files = entry.alpm_db_files()?;
298    let alpm_install_scriptlet = entry.alpm_install_scriptlet()?;
299    let alpm_mtree = entry.alpm_mtree()?;
300
301    let entry_dir = path.as_ref().join(entry.entry_name().to_string());
302    if entry_dir.exists() {
303        return Err(Error::EntryExists {
304            name: entry.entry_name().clone(),
305        }
306        .into());
307    }
308    create_dir(&entry_dir).map_err(|source| crate::Error::IoPath {
309        path: entry_dir.clone(),
310        context: t!("error-io-path-entry-dir-create"),
311        source,
312    })?;
313    set_permissions(&entry_dir, Permissions::from_mode(DIR_MODE)).map_err(|source| {
314        crate::Error::IoPath {
315            path: entry_dir.clone(),
316            context: t!("error-io-path-db-set-permissions-on-dir"),
317            source,
318        }
319    })?;
320
321    let components = {
322        let mut components = vec![
323            (
324                EntryComponentType::DbDesc,
325                create_entry_component(entry_dir.join(EntryComponentType::DbDesc.as_ref()))?,
326                alpm_db_desc.to_string().into_bytes(),
327            ),
328            (
329                EntryComponentType::DbFiles,
330                create_entry_component(entry_dir.join(EntryComponentType::DbFiles.as_ref()))?,
331                alpm_db_files.to_string().into_bytes(),
332            ),
333            (
334                EntryComponentType::Mtree,
335                create_entry_component(entry_dir.join(EntryComponentType::Mtree.as_ref()))?,
336                alpm_mtree.data_ensure_gzip()?,
337            ),
338        ];
339
340        if let Some(alpm_install_scriptlet) = alpm_install_scriptlet {
341            components.push((
342                EntryComponentType::InstallScriptlet,
343                create_entry_component(
344                    entry_dir.join(EntryComponentType::InstallScriptlet.as_ref()),
345                )?,
346                alpm_install_scriptlet.into_bytes(),
347            ))
348        }
349
350        components
351    };
352
353    for (component_type, mut file, data) in components {
354        file.write_all(&data)
355            .map_err(|source| crate::Error::IoPath {
356                path: entry_dir.clone(),
357                context: t!(
358                    "error-io-path-db-write-component",
359                    { "file_type" => component_type.file_type_name().to_string()}
360                ),
361                source,
362            })?
363    }
364
365    Ok(())
366}
367
368/// An action in a transaction for an [alpm-db].
369///
370/// This may be an addition or a removal.
371///
372/// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
373#[derive(Debug)]
374pub enum Action {
375    /// A package is added.
376    ///
377    /// Tracks data that is lazy-loaded from an implementation of [`EntrySource`].
378    Add(Box<dyn EntrySource>),
379
380    /// A package is removed.
381    Remove(EntryName),
382}
383
384impl Display for Action {
385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386        let (action, entry) = match self {
387            Self::Add(entry) => ("Add", &entry.entry_name()),
388            Self::Remove(entry) => ("Remove", entry),
389        };
390
391        write!(f, "{action} {entry}")
392    }
393}
394
395/// Creates all directories required for a transaction to function at `path`.
396///
397/// Returns the canonicalized transaction data directory.
398///
399/// # Note
400///
401/// This creates `path` and all required subdirectories.
402///
403/// # Errors
404///
405/// Returns an error, if
406///
407/// - `path` exists and
408///   - it cannot be canonicalized
409///   - it is not a directory
410///   - metadata for it cannot be retrieved
411///   - its ownership cannot be changed to the UID/GID of the calling user
412///   - its permissions cannot be changed to the default permissions
413/// - `path` does not exist and
414///   - it cannot be created
415///   - its permissions cannot be set to the defaults
416/// - any of the required subdirectories
417///   - cannot be created
418///   - cannot be adjusted to be owned by the calling UID/GID and have default permissions
419fn create_transaction_dirs(path: impl AsRef<Path>) -> Result<PathBuf, crate::Error> {
420    let path = path.as_ref();
421
422    let path = if path.exists() {
423        // If the path exists already, canonicalize it and ensure, that it is valid.
424        // The path must be an empty directory with default permissions, owned by the
425        // UID/GID of the calling process.
426
427        let path = path.canonicalize().map_err(|source| crate::Error::IoPath {
428            path: path.to_path_buf(),
429            context: t!("error-io-path-db-transaction-data-dir-canonicalize"),
430            source,
431        })?;
432
433        // Fail, if the targeted path is not a directory.
434        if !&path.is_dir() {
435            return Err(Error::TransactionDataDirIsNotADirectory { path }.into());
436        }
437
438        let euid = geteuid().as_raw();
439        let egid = getegid().as_raw();
440        let metadata = path
441            .symlink_metadata()
442            .map_err(|source| crate::Error::IoPath {
443                path: path.clone(),
444                context: t!("error-io-path-metadata"),
445                source,
446            })?;
447
448        // Change ownership if it doesn't match the calling UID/GID.
449        if !(metadata.uid() == euid && metadata.gid() == egid) {
450            chown(&path, Some(euid), Some(egid)).map_err(|source| crate::Error::IoPath {
451                path: path.clone(),
452                context: t!("error-io-path-chown"),
453                source,
454            })?;
455        }
456
457        // Change permissions if they don't match the defaults.
458        if metadata.permissions().mode() != DIR_MODE {
459            set_permissions(&path, PermissionsExt::from_mode(DIR_MODE)).map_err(|source| {
460                crate::Error::IoPath {
461                    path: path.clone(),
462                    context: t!("error-io-path-db-transaction-data-dir-set-permissions"),
463                    source,
464                }
465            })?;
466        }
467
468        path
469    } else {
470        // If the path does not yet exist, create it, canonicalize it and set default
471        // permissions.
472
473        create_dir_all(path).map_err(|source| crate::Error::IoPath {
474            path: path.to_path_buf(),
475            context: t!("error-io-path-db-transaction-data-dir-create"),
476            source,
477        })?;
478        let path = path.canonicalize().map_err(|source| crate::Error::IoPath {
479            path: path.to_path_buf(),
480            context: t!("error-io-path-db-transaction-data-dir-canonicalize"),
481            source,
482        })?;
483
484        set_permissions(&path, PermissionsExt::from_mode(DIR_MODE)).map_err(|source| {
485            crate::Error::IoPath {
486                path: path.clone(),
487                context: t!("error-io-path-db-transaction-data-dir-set-permissions"),
488                source,
489            }
490        })?;
491
492        path
493    };
494
495    // Create all required subdirectories (for current and previous transaction plans, as well as
496    // temporary transaction data).
497    for subdir in [
498        Transaction::CURRENT_DIR,
499        Transaction::PAST_DIR,
500        Transaction::TEMP_DIR,
501    ] {
502        let subdir = path.join(subdir);
503
504        if subdir.is_dir() {
505            let euid = geteuid().as_raw();
506            let egid = getegid().as_raw();
507            let metadata = subdir
508                .symlink_metadata()
509                .map_err(|source| crate::Error::IoPath {
510                    path: subdir.clone(),
511                    context: t!("error-io-path-metadata"),
512                    source,
513                })?;
514
515            // Change ownership if it doesn't match the calling UID/GID.
516            if !(metadata.uid() == euid && metadata.gid() == egid) {
517                chown(&subdir, Some(euid), Some(egid)).map_err(|source| crate::Error::IoPath {
518                    path: subdir.clone(),
519                    context: t!("error-io-path-chown"),
520                    source,
521                })?;
522            }
523
524            // Change permissions if they don't match the defaults.
525            if metadata.permissions().mode() != DIR_MODE {
526                set_permissions(&subdir, PermissionsExt::from_mode(DIR_MODE)).map_err(
527                    |source| crate::Error::IoPath {
528                        path: subdir.clone(),
529                        context: t!("error-io-path-db-transaction-data-dir-set-permissions"),
530                        source,
531                    },
532                )?;
533            }
534
535            continue;
536        }
537
538        create_dir(&subdir).map_err(|source| crate::Error::IoPath {
539            path: subdir.to_path_buf(),
540            context: t!("error-io-path-db-base-create"),
541            source,
542        })?;
543        set_permissions(&subdir, PermissionsExt::from_mode(DIR_MODE)).map_err(|source| {
544            crate::Error::IoPath {
545                path: subdir.clone(),
546                context: t!("error-io-path-db-transaction-data-dir-set-permissions"),
547                source,
548            }
549        })?;
550    }
551
552    Ok(path)
553}
554
555/// Removes the temporary directory for this transaction.
556///
557/// # Errors
558///
559/// Returns an error, if the temporary directory of the transaction, or any of its children
560/// cannot be removed.
561fn remove_temp_transaction_dir(path: impl AsRef<Path>) -> Result<(), crate::Error> {
562    let path = path.as_ref();
563
564    remove_dir_all(path).map_err(|source| crate::Error::IoPath {
565        path: path.to_path_buf(),
566        context: t!("error-io-path-db-transaction-temp-dir-remove"),
567        source,
568    })
569}
570
571/// Checks whether `path1` and `path2` are on the same device.
572///
573/// # Errors
574///
575/// Returns an error, if the metadata for `path1` or `path2` cannot be retrieved.
576fn paths_on_same_device(
577    path1: impl AsRef<Path>,
578    path2: impl AsRef<Path>,
579) -> Result<bool, crate::Error> {
580    let path1 = path1.as_ref();
581    let path2 = path2.as_ref();
582
583    Ok(path1
584        .symlink_metadata()
585        .map_err(|source| crate::Error::IoPath {
586            path: path1.to_path_buf(),
587            context: t!("error-io-path-metadata"),
588            source,
589        })?
590        .dev()
591        == path2
592            .symlink_metadata()
593            .map_err(|source| crate::Error::IoPath {
594                path: path2.to_path_buf(),
595                context: t!("error-io-path-metadata"),
596                source,
597            })?
598            .dev())
599}
600
601/// A transaction for an [alpm-db].
602///
603/// A transaction consists of zero or more more [`Action`]s.
604/// Each [`Action::Add`] is paired with an implementation of [`EntrySource`], which provides
605/// access to the data about to be written to disk.
606///
607/// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
608#[derive(Debug)]
609pub(crate) struct Transaction {
610    uuid: Uuid,
611    actions: Vec<Action>,
612    database_dir: PathBuf,
613    data_dir: PathBuf,
614    write_lock: WriteLock,
615}
616
617impl Transaction {
618    /// The name of the directory below the data directory in which current transaction plans are
619    /// stored.
620    const CURRENT_DIR: &str = "current";
621
622    /// The name of the directory below the data directory in which past transaction plans are
623    /// stored.
624    const PAST_DIR: &str = "past";
625
626    /// The name of the directory below the data directory in which temporary transaction data is
627    /// stored.
628    const TEMP_DIR: &str = "temp";
629
630    /// Creates a new [`Transaction`].
631    ///
632    /// # Errors
633    ///
634    /// Returns an error, if a lock file cannot be created for the transaction.
635    pub fn new(config: &DatabaseConfig) -> Result<Self, crate::Error> {
636        let database_dir = config.database_dir().to_path_buf();
637        let data_dir = config.transaction_data_dir();
638        let lock_file = config.lock_file();
639        let uuid = Uuid::now_v7();
640        debug!(
641            "Create transaction {uuid} for alpm-db {database_dir:?}, using data dir {data_dir:?} and lock file {lock_file:?}"
642        );
643
644        let write_lock = WriteLock::new(lock_file)?;
645        let data_dir = create_transaction_dirs(data_dir)?;
646
647        Ok(Self {
648            uuid,
649            actions: Vec::new(),
650            database_dir,
651            data_dir,
652            write_lock,
653        })
654    }
655
656    /// Adds a new action to this transaction.
657    pub fn add_action(&mut self, action: Action) {
658        self.actions.push(action);
659    }
660
661    /// Returns a reference to the UUID of this transaction.
662    pub fn uuid(&self) -> &Uuid {
663        &self.uuid
664    }
665
666    /// Returns a reference to the database dir of this transaction.
667    pub fn database_dir(&self) -> &Path {
668        &self.database_dir
669    }
670
671    /// Returns a reference to the data dir of this transaction.
672    pub fn data_dir(&self) -> &Path {
673        &self.data_dir
674    }
675
676    /// Returns a reference to the path of the write lock file of this transaction.
677    pub fn lock_file(&self) -> &Path {
678        self.write_lock.as_ref()
679    }
680
681    /// Creates the temporary directory for this transaction and returns its path.
682    ///
683    /// # Errors
684    ///
685    /// Returns an error, if the temporary directory cannot be created.
686    fn create_temp_dir(&self) -> Result<PathBuf, crate::Error> {
687        let temp_dir = self
688            .data_dir
689            .join(Transaction::TEMP_DIR)
690            .join(self.uuid().to_string());
691
692        // Create the temporary directory for this transaction.
693        create_dir(&temp_dir).map_err(|source| crate::Error::IoPath {
694            path: temp_dir.clone(),
695            context: t!("error-io-path-db-transaction-temp-dir-create"),
696            source,
697        })?;
698
699        Ok(temp_dir)
700    }
701
702    /// Commits all changes of this transaction to the [alpm-db] and consumes [`Self`].
703    ///
704    /// Committing a transaction involves several steps:
705    ///
706    /// - creating a plan for the transaction and persisting it in the directory for current
707    ///   transactions
708    /// - creation of a temporary directory for the transaction
709    /// - collection of the data of all additions in the temporary directory
710    /// - removal of all entries marked for removal from the [alpm-db]
711    /// - move/copy of all additions from the temporary directory to the [alpm-db]
712    /// - removal of the temporary directory
713    /// - moving the transaction plan from the directory for current transactions to that for past
714    ///   ones
715    /// - removing the write lock for the database
716    ///
717    /// # Note
718    ///
719    /// This method returns early (and removes the lock file), if the transaction describes no
720    /// operations.
721    ///
722    /// # Errors
723    ///
724    /// Returns an error, if
725    ///
726    /// - writing the transaction plan to the directory for current transactions fails
727    /// - creating the temporary directory for the transaction fails
728    /// - checking whether temporary directory and [alpm-db] are on the same device fails
729    /// - writing a new entry to the temporary directory fails
730    /// - removal of an entry would fail because it does not exist in the [alpm-db]
731    /// - removing an entry from the [alpm-db] fails
732    /// - moving/copying a new entry from the temporary directory to the [alpm-db] fails
733    /// - removing the temporary directory fails
734    /// - moving the transaction plan fails to the directory for past transactions fails
735    /// - removing the write lock fails
736    ///
737    /// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
738    pub fn commit(self) -> Result<(), crate::Error> {
739        debug!(
740            "Committing transaction {} for alpm-db {:?} using data dir {:?}",
741            self.uuid(),
742            self.database_dir(),
743            self.data_dir(),
744        );
745
746        // Return early, if there are no actions to perform
747        if self.actions.is_empty() {
748            debug!(
749                "The transaction {} for alpm-db {:?} has no actions to perform.",
750                self.uuid, self.database_dir
751            );
752
753            self.write_lock.remove()?;
754
755            return Ok(());
756        }
757
758        // Write the transaction plan to the directory for current transactions.
759        // (If there are no actions, this is a noop).
760        let transaction_plan = TransactionPlan::from(&self);
761        transaction_plan.write_to_current_dir()?;
762
763        let temp_dir = self.create_temp_dir()?;
764        let path = self.database_dir().to_path_buf();
765        let uuid = *self.uuid();
766        // Check whether the temporary location and the database are on the same device.
767        let same_device = paths_on_same_device(&path, &temp_dir)?;
768
769        // Write all additions to the temporary directory and collect the removals.
770        // Any errors that may occur are collected as well.
771        let (removals, errors) = {
772            let mut removals = Vec::new();
773            let mut errors = Vec::new();
774            for action in self.actions {
775                match action {
776                    Action::Add(entry) => {
777                        if let Err(error) = write_entry_to_dir(entry, &temp_dir) {
778                            errors.push(error);
779                        }
780                    }
781                    Action::Remove(entry_name) => {
782                        if !path.join(entry_name.to_string()).exists() {
783                            errors.push(
784                                Error::EntryDoesNotExist {
785                                    name: entry_name.clone(),
786                                }
787                                .into(),
788                            );
789                        }
790                        removals.push(entry_name)
791                    }
792                }
793            }
794            (removals, errors)
795        };
796
797        // Remove the temporary directory, if errors occurred during preparation and return an
798        // error.
799        if !errors.is_empty() {
800            remove_temp_transaction_dir(&temp_dir)?;
801
802            return Err(Error::TransactionTemporaryDataErrors {
803                path: path.to_path_buf(),
804                uuid,
805                errors: errors.iter().map(ToString::to_string).collect(),
806            }
807            .into());
808        }
809
810        // Remove all entries marked for removal from the database.
811        for removal in removals {
812            remove_dir_all(path.join(removal.to_string())).map_err(|source| {
813                crate::Error::IoPath {
814                    path: path.join(removal.to_string()),
815                    context: t!("error-io-path-db-entry-remove"),
816                    source,
817                }
818            })?
819        }
820
821        // Move or copy all entries marked for addition from temporary dir to database.
822        if same_device {
823            debug!(
824                "Temporary transaction data and database are on the same device: Moving entries..."
825            );
826        } else {
827            debug!(
828                "Temporary transaction data and database are on separate devices: Copying entries..."
829            );
830        }
831
832        for entry in temp_dir.read_dir().map_err(|source| crate::Error::IoPath {
833            path: temp_dir.clone(),
834            context: t!("error-io-path-db-transaction-temp-dir-read"),
835            source,
836        })? {
837            let entry = entry.map_err(|source| crate::Error::IoPath {
838                path: temp_dir.clone(),
839                context: t!("error-io-path-db-transaction-temp-dir-entry-read"),
840                source,
841            })?;
842            let entry_from = entry.path();
843            let entry_to = path.join(entry.file_name());
844            if same_device {
845                rename(&entry_from, &entry_to).map_err(|source| crate::Error::IoPath {
846                    path: entry_from.clone(),
847                    context: t!("error-io-path-db-transaction-temp-dir-entry-move"),
848                    source,
849                })?;
850            } else {
851                copy(&entry_from, &entry_to).map_err(|source| crate::Error::IoPath {
852                    path: entry_from.clone(),
853                    context: t!("error-io-path-db-transaction-temp-dir-entry-copy"),
854                    source,
855                })?;
856            }
857        }
858
859        // Remove the temporary data.
860        remove_temp_transaction_dir(&temp_dir)?;
861
862        // Move the transaction plan from current to previous location in the data directory.
863        transaction_plan.move_to_past_transaction_dir()?;
864
865        self.write_lock.remove()?;
866
867        Ok(())
868    }
869}
870
871#[cfg(test)]
872mod tests {
873    use insta::{assert_snapshot, with_settings};
874    use log::LevelFilter;
875    use simplelog::{ColorChoice, Config, TermLogger, TerminalMode};
876    use tempfile::{NamedTempFile, TempDir};
877    use testresult::TestResult;
878
879    use super::*;
880
881    /// Initialize a logger that shows trace messages on stderr.
882    fn init_logger() {
883        if TermLogger::init(
884            LevelFilter::Trace,
885            Config::default(),
886            TerminalMode::Stderr,
887            ColorChoice::Auto,
888        )
889        .is_err()
890        {
891            debug!("Not initializing another logger, as one is initialized already.");
892        }
893    }
894
895    /// Ensures, that [`WriteLock::new`] succeeds on creating a lock file.
896    ///
897    /// Also checks, that the default file mode is applied and that the file is cleaned up on drop.
898    #[test]
899    fn write_lock_new_succeeds() -> TestResult {
900        init_logger();
901        let temp_dir = TempDir::new()?;
902        let lock_file_path = temp_dir.path().join(PathBuf::from("db.lck"));
903
904        let lock = WriteLock::new(&lock_file_path)?;
905        let metadata = lock_file_path.metadata()?;
906        assert_eq!(metadata.permissions().mode(), WriteLock::DEFAULT_FILE_MODE);
907
908        lock.remove()?;
909
910        assert!(!lock_file_path.exists());
911
912        Ok(())
913    }
914
915    /// Ensures, that [`WriteLock::new`] fails on creating a lock file, if the target file exists
916    /// already.
917    #[test]
918    fn write_lock_new_fails_on_existing_file() -> TestResult {
919        init_logger();
920        let temp_file = NamedTempFile::new()?;
921
922        let Err(error) = WriteLock::new(temp_file.path()) else {
923            panic!("Expected to fail with crate::Error::IoPath");
924        };
925
926        debug!("{error}");
927        assert!(matches!(error, crate::Error::IoPath { .. }));
928
929        Ok(())
930    }
931
932    /// Ensures, that the JSON representation of a [`TransactionPlan`] remains stable.
933    #[test]
934    fn transaction_plan_stable_serialization() -> TestResult {
935        init_logger();
936
937        let temp_dir = TempDir::new()?;
938        let path = temp_dir.path();
939
940        let plan = TransactionPlan {
941            uuid: "01a17815-fe9d-77f6-9bb1-387d74e07195".parse()?,
942            actions: vec![
943                ActionItem::Add("example-1.0.0-1".parse()?),
944                ActionItem::Remove("other-example-2.0.0-1".parse()?),
945            ],
946            data_dir: path.to_path_buf(),
947        };
948
949        let json_plan = serde_json::to_string(&plan)?;
950
951        debug!("{json_plan}");
952        with_settings!({ description => "Simple, serialized transaction plan example", snapshot_path => "snapshots" }, {
953            assert_snapshot!("transaction_plan_stable_serialize_example", json_plan);
954        });
955
956        Ok(())
957    }
958}