aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 58e21915202220e7497136800c3ac4dee822099c (plain) (blame)
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
use std::fs::{self, DirEntry, File};
use std::io::{BufRead, BufReader, Result, Seek, Write};
use std::path::Path;
use std::process::{self, ChildStderr, ChildStdout, Command, Stdio};
use std::thread;
use std::time::{Duration, SystemTime};

use nix::sys::reboot::RebootMode;
use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal as Sig};
use sys_mount::{Mount, Unmount, UnmountDrop, UnmountFlags};
use sysinfo::{ProcessExt, Signal, System, SystemExt};

const SERVICE_RESTART_INTERVAL: Duration = Duration::from_secs(30);

macro_rules! log {
    ($col:expr, $($tts:tt)*) => {
        {
            println!($($tts)*);
        }
    };
}

macro_rules! log_raw {
    ($col:expr, $($tts:tt)*) => {
        {
            print!($($tts)*);
        }
    };
}

macro_rules! halt {
    () => {
        loop {
            thread::park();
        }
    };
}

fn start() -> Result<()> {
    log!(Color::Yellow, "Starting rustkrazy");

    for service in fs::read_dir("/bin")? {
        let service = service?;
        let service_name = match service.file_name().into_string() {
            Ok(v) => v,
            Err(_) => {
                log!(Color::Red, "[ ERROR ] invalid unicode in file name");
                continue;
            }
        };

        if service_name == "init" {
            continue;
        }

        thread::spawn(move || match supervise(service, service_name.clone()) {
            Ok(_) => {}
            Err(e) => log!(Color::Red, "can't supervise {}: {}", service_name, e),
        });
    }

    Ok(())
}

fn supervise(service: DirEntry, service_name: String) -> Result<()> {
    loop {
        let mut cmd = Command::new(service.path());
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        match cmd.spawn() {
            Ok(mut child) => {
                log!(Color::Green, "[  OK   ] starting {}", service_name);

                let child_stdout = child.stdout.take();
                let service_name2 = service_name.clone();
                thread::spawn(move || {
                    log_out(child_stdout.expect("no child stdout"), service_name2)
                        .expect("logging stdout failed");
                });

                let child_stderr = child.stderr.take();
                let service_name2 = service_name.clone();
                thread::spawn(move || {
                    log_err(child_stderr.expect("no child stderr"), service_name2)
                        .expect("logging stderr failed");
                });

                match child.wait() {
                    Ok(status) => {
                        log!(
                            Color::Yellow,
                            "[ INFO  ] {} exited with {}",
                            service_name,
                            status
                        );
                    }
                    Err(e) => {
                        log!(
                            Color::Red,
                            "[ ERROR ] can't wait for {} to exit: {}",
                            service_name,
                            e
                        );
                    }
                }
            }
            Err(e) => {
                log!(Color::Red, "[ ERROR ] starting {}: {}", service_name, e);
            }
        }

        thread::sleep(SERVICE_RESTART_INTERVAL);
    }
}

fn log_out(pipe: ChildStdout, service_name: String) -> Result<()> {
    let mut file = File::create(Path::new("/tmp").join(service_name.clone() + ".log"))?;
    let mut r = BufReader::new(pipe);

    loop {
        let mut buf = String::new();
        if r.read_line(&mut buf)? == 0 {
            log!(Color::Yellow, "[ INFO  ] {} closed stdout", service_name);
            return Ok(());
        }

        if file.metadata()?.len() > 30000000 {
            file.set_len(0)?;
            file.rewind()?;
        }

        if !buf.is_empty() {
            let timestamp = humantime::format_rfc3339_seconds(SystemTime::now());
            let buf = format!("[{} {}] {}", timestamp, service_name, buf);

            log_raw!(Color::White, "{}", buf);

            file.write_all(buf.as_bytes())?;
        }
    }
}

fn log_err(pipe: ChildStderr, service_name: String) -> Result<()> {
    let mut file = File::create(Path::new("/data").join(service_name.clone() + ".err"))?;
    let mut r = BufReader::new(pipe);

    loop {
        let mut buf = String::new();
        if r.read_line(&mut buf)? == 0 {
            log!(Color::Yellow, "[ INFO  ] {} closed stderr", service_name);
            return Ok(());
        }

        if file.metadata()?.len() > 30000000 {
            file.set_len(0)?;
            file.rewind()?;
        }

        if !buf.is_empty() {
            let timestamp = humantime::format_rfc3339_seconds(SystemTime::now());
            let buf = format!("[{} {}] {}", timestamp, service_name, buf);

            log_raw!(Color::White, "{}", buf);

            file.write_all(buf.as_bytes())?;
        }
    }
}

fn mount_or_halt(part_id: u8, mount_point: &str, fs: &str) -> UnmountDrop<Mount> {
    let mut mount = None;
    let mut mount_err = None;

    let devs = [
        format!("/dev/mmcblk0p{}", part_id),
        format!("/dev/sda{}", part_id),
        format!("/dev/vda{}", part_id),
    ];

    for dev in &devs {
        match Mount::builder().fstype(fs).mount(dev, mount_point) {
            Ok(v) => {
                mount = Some(v.into_unmount_drop(UnmountFlags::DETACH));
                break;
            }
            Err(e) => {
                mount_err = Some(e);
            }
        };
    }

    match mount {
        None => {
            if let Some(e) = mount_err {
                log!(Color::Red, "[ ERROR ] can't mount {}: {}", mount_point, e)
            } else {
                log!(
                    Color::Red,
                    "[ ERROR ] can't mount {}: unknown error (this shouldn't happen)",
                    mount_point
                );
            }

            halt!();
        }
        Some(handle) => handle,
    }
}

fn end() {
    log!(Color::Yellow, "[ INFO  ] send SIGTERM to all processes");
    for process in System::new_all().processes().values() {
        process.kill_with(Signal::Term);
    }

    thread::sleep(Duration::from_secs(3));
}

extern "C" fn reboot(_: i32) {
    end();
    sysreset(RebootMode::RB_AUTOBOOT);
}

extern "C" fn poweroff(_: i32) {
    end();
    sysreset(RebootMode::RB_POWER_OFF);
}

fn main() {
    if process::id() != 1 {
        log!(Color::Red, "[ ERROR ] must be run as PID 1");
        halt!();
    }

    let _boot_handle = mount_or_halt(1, "/boot", "vfat");
    let _data_handle = mount_or_halt(4, "/data", "ext4");
    let _proc_handle = Mount::builder()
        .fstype("proc")
        .mount("proc", "/proc")
        .expect("can't mount /proc procfs");
    let _tmp_handle = Mount::builder()
        .fstype("tmpfs")
        .mount("tmpfs", "/tmp")
        .expect("can't mount /tmp tmpfs");
    let _run_handle = Mount::builder()
        .fstype("tmpfs")
        .mount("tmpfs", "/run")
        .expect("can't mount /run tmpfs");

    match start() {
        Ok(_) => {}
        Err(e) => log!(Color::Red, "[ ERROR ] {}", e),
    }

    let reboot_action = SigAction::new(
        SigHandler::Handler(reboot),
        SaFlags::empty(),
        SigSet::from(Sig::SIGUSR1),
    );

    let shutdown_action = SigAction::new(
        SigHandler::Handler(poweroff),
        SaFlags::empty(),
        SigSet::from(Sig::SIGUSR2),
    );

    unsafe {
        match nix::sys::signal::sigaction(Sig::SIGUSR1, &reboot_action) {
            Ok(_) => {}
            Err(e) => log!(
                Color::Red,
                "[ ERROR ] can't subscribe to SIGUSR1: {}",
                e.desc()
            ),
        }
    }

    unsafe {
        match nix::sys::signal::sigaction(Sig::SIGUSR2, &shutdown_action) {
            Ok(_) => {}
            Err(e) => log!(
                Color::Red,
                "[ ERROR ] can't subscribe to SIGUSR2: {}",
                e.desc()
            ),
        }
    }

    halt!();
}

fn sysreset(reboot_mode: RebootMode) {
    nix::unistd::sync();

    log!(Color::Yellow, "[ INFO  ] send final SIGTERM");
    for process in System::new_all().processes().values() {
        process.kill_with(Signal::Term);
    }

    thread::sleep(Duration::from_secs(3));

    log!(Color::Yellow, "[ INFO  ] send final SIGKILL");
    for process in System::new_all().processes().values() {
        process.kill_with(Signal::Kill);
    }

    let Err(e) = nix::sys::reboot::reboot(reboot_mode);
    log!(
        Color::Red,
        "[ ERROR ] can't reboot (mode: {:?}): {}",
        reboot_mode,
        e
    );
    halt!();
}