service_install/install/files/
process_parent.rs

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
use std::path::{Path, PathBuf};
use std::process::Command;

use itertools::Itertools;
use sysinfo::Pid;

use crate::install::init::PathCheckError;
use crate::install::{init, InstallStep};

#[derive(Debug)]
pub(crate) enum IdRes {
    /// Process locking up the file has no parent, must be orphaned
    NoParent,
    ParentIsInit {
        init: init::System,
        pid: Pid,
    },
    ParentNotInit {
        parents: Vec<PathBuf>,
        pid: Pid,
    },
}

impl IdRes {
    fn from_tree_and_pid(
        tree: Vec<&Path>,
        pid: Pid,
        init_systems: &[init::System],
    ) -> Result<IdRes, PathCheckError> {
        let Some(direct_parent) = tree.first() else {
            return Ok(IdRes::NoParent);
        };

        for init in init_systems {
            if init.is_init_path(direct_parent)? {
                return Ok(IdRes::ParentIsInit {
                    init: init.clone(),
                    pid,
                });
            }
        }

        Ok(IdRes::ParentNotInit {
            pid,
            parents: tree.into_iter().map(PathBuf::from).collect(),
        })
    }
}

pub(crate) fn list(
    target: &Path,
    init_systems: &[init::System],
) -> Result<Vec<IdRes>, PathCheckError> {
    use sysinfo::{ProcessRefreshKind, System, UpdateKind};

    let mut s = System::new();
    s.refresh_processes_specifics(
        ProcessRefreshKind::new()
            .with_exe(UpdateKind::Always)
            .with_cmd(UpdateKind::Always),
    );

    let using_target: Vec<_> = s
        .processes()
        .iter()
        .map(|(_, process)| process)
        .filter(|p| p.exe() == Some(target))
        .collect();

    let without_children = using_target.iter().filter(|p| {
        if let Some(parent) = p.parent() {
            !using_target.iter().any(|p| p.pid() == parent)
        } else {
            true
        }
    });

    without_children
        .cloned()
        .map(|p| {
            let mut process = p;
            let mut tree = Vec::new();

            while let Some(parent) = process.parent() {
                if let Some(parent) = s.process(parent) {
                    process = parent;
                    if let Some(exe) = process.exe() {
                        tree.push(exe);
                    } else {
                        let cmd = process.cmd();
                        let path = Path::new(&cmd[0]);
                        tree.push(path);
                    }
                }
            }
            (tree, p.pid())
        })
        .map(|(tree, pid)| IdRes::from_tree_and_pid(tree, pid, init_systems))
        .collect()
}

#[derive(Debug, thiserror::Error)]
pub enum KillOldError {
    #[error("Could not run the kill command")]
    KillUnavailable(#[source] std::io::Error),
    #[error("The kill command faild with: {0}")]
    KillFailed(String),
}

pub struct KillOld {
    pid: Pid,
    parents: Vec<PathBuf>,
}

impl InstallStep for KillOld {
    fn describe(&self, tense: crate::Tense) -> String {
        match tense {
            crate::Tense::Past => {
                "there was a program running with the same name taking up the \
                    install location it has been terminated"
            }
            crate::Tense::Questioning => {
                "there is a program running with the same name taking up the \
                    install location terminate it?"
            }
            crate::Tense::Active => {
                "there is a program running with the same name taking up the \
                    install location, terminating it"
            }
            crate::Tense::Future => {
                "there is a program running with the same name taking up the \
                    install location, it will be terminated"
            }
        }
        .to_string()
    }

    fn perform(
        &mut self,
    ) -> Result<Option<Box<dyn crate::install::RollbackStep>>, crate::install::InstallError> {
        let output = Command::new("kill")
            .arg("--signal")
            .arg("TERM")
            .arg(format!("{}", self.pid))
            .output()
            .map_err(KillOldError::KillUnavailable)
            .map_err(crate::install::InstallError::KillOld)?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
            Err(crate::install::InstallError::KillOld(
                KillOldError::KillFailed(stderr),
            ))
        } else {
            Ok(None)
        }
    }

    fn describe_detailed(&self, tense: crate::Tense) -> String {
        let list = if self.parents.len() == 1 {
            self.parents
                .first()
                .expect("len just checked")
                .display()
                .to_string()
        } else {
            self.parents
                .iter()
                .map(|p| p.display().to_string())
                .join("\n\twhich was started by: ")
        };

        match tense {
            crate::Tense::Past => format!(
                "there was a program running with the same name taking up the \
            install location. It was was started by: {list}\nIt had to be terminated \
            before we could continue."
            ),
            crate::Tense::Questioning => format!(
                "there is a program running with the same name taking up the \
            install location. It was was started by: {list}\nIt must be terminated \
            before we can continue. Terminating might not work or the parent \
            can restart the program. Do you wish to try to stop the program and \
            continue installation?"
            ),
            crate::Tense::Active => format!(
                "there is a program running with the same name taking up the \
            install location. It was was started by: {list}\nIt must be terminated \
            before we can continue. Terminating might not work or the parent \
            can restart the program. Stopping the program and continuing installation"
            ),
            crate::Tense::Future => format!(
                "there is a program running with the same name taking up the \
            install location. It was was started by: {list}\nIt must be terminated \
            before we can continue. Terminating might not work or the parent \
            can restart the program. Will try to stop the program and continuing \
            installation"
            ),
        }
    }
}

pub(crate) fn kill_old_steps(pid: Pid, parents: Vec<PathBuf>) -> Box<dyn InstallStep> {
    Box::new(KillOld { pid, parents })
}