]>
Commit | Line | Data |
---|---|---|
4ce7da51 | 1 | use std::sync::{Mutex, Arc}; |
2ab5acac | 2 | use std::path::{Path, PathBuf}; |
97168f92 | 3 | use std::os::unix::io::AsRawFd; |
a2479cfa | 4 | |
f7d4e4b5 | 5 | use anyhow::{bail, format_err, Error}; |
a2479cfa | 6 | use futures::*; |
7fa9a37c DM |
7 | use http::request::Parts; |
8 | use http::Response; | |
9 | use hyper::{Body, StatusCode}; | |
10 | use hyper::header; | |
11 | use url::form_urlencoded; | |
ea368a06 | 12 | |
a2479cfa | 13 | use openssl::ssl::{SslMethod, SslAcceptor, SslFiletype}; |
7c667013 | 14 | use tokio_stream::wrappers::ReceiverStream; |
7fa9a37c | 15 | use serde_json::{json, Value}; |
a2479cfa | 16 | |
9ea4bce4 | 17 | use proxmox::try_block; |
a2479cfa | 18 | use proxmox::api::RpcEnvironmentType; |
32413921 | 19 | use proxmox::sys::linux::socket::set_tcp_keepalive; |
fd6d2438 DM |
20 | use proxmox::tools::fs::CreateOptions; |
21 | ||
6fbf0acc | 22 | use proxmox_rest_server::{ApiConfig, RestServer}; |
a2479cfa | 23 | |
1298618a DM |
24 | use proxmox_backup::{ |
25 | backup::DataStore, | |
26 | server::{ | |
26858dba | 27 | auth::default_api_auth, |
1298618a | 28 | WorkerTask, |
1298618a DM |
29 | jobstate::{ |
30 | self, | |
31 | Job, | |
32 | }, | |
33 | rotate_task_log_archive, | |
34 | }, | |
1298618a DM |
35 | }; |
36 | ||
af06decd | 37 | use pbs_buildcfg::configdir; |
84af82e8 | 38 | use proxmox_systemd::time::{compute_next_event, parse_calendar_event}; |
6c76aa43 | 39 | use pbs_tools::logrotate::LogRotate; |
1298618a | 40 | |
89725197 DM |
41 | use pbs_api_types::{ |
42 | Authid, TapeBackupJobConfig, VerificationJobConfig, SyncJobConfig, DataStoreConfig, | |
43 | PruneOptions, | |
44 | }; | |
e7d4be9d | 45 | |
8bca935f DM |
46 | use proxmox_rest_server::daemon; |
47 | ||
e3f41f21 | 48 | use proxmox_backup::server; |
d01e2420 | 49 | use proxmox_backup::auth_helpers::*; |
97168f92 | 50 | use proxmox_backup::tools::{ |
32413921 | 51 | PROXMOX_BACKUP_TCP_KEEPALIVE_TIME, |
97168f92 DM |
52 | disks::{ |
53 | DiskManage, | |
54 | zfs_pool_stats, | |
368f4c54 | 55 | get_pool_from_dataset, |
97168f92 | 56 | }, |
97168f92 | 57 | }; |
02c7a755 | 58 | |
e7d4be9d | 59 | |
a13573c2 | 60 | use proxmox_backup::api2::pull::do_sync_job; |
8513626b | 61 | use proxmox_backup::api2::tape::backup::do_tape_backup_job; |
1298618a | 62 | use proxmox_backup::server::do_verification_job; |
b8d90798 | 63 | use proxmox_backup::server::do_prune_job; |
a13573c2 | 64 | |
946c3e8a | 65 | fn main() -> Result<(), Error> { |
ac7513e3 DM |
66 | proxmox_backup::tools::setup_safe_path_env(); |
67 | ||
21211748 DM |
68 | let backup_uid = pbs_config::backup_user()?.uid; |
69 | let backup_gid = pbs_config::backup_group()?.gid; | |
843880f0 TL |
70 | let running_uid = nix::unistd::Uid::effective(); |
71 | let running_gid = nix::unistd::Gid::effective(); | |
72 | ||
73 | if running_uid != backup_uid || running_gid != backup_gid { | |
74 | bail!("proxy not running as backup user or group (got uid {} gid {})", running_uid, running_gid); | |
75 | } | |
76 | ||
d420962f | 77 | pbs_runtime::main(run()) |
4223d9f8 DM |
78 | } |
79 | ||
7fa9a37c DM |
80 | fn get_index( |
81 | auth_id: Option<String>, | |
82 | language: Option<String>, | |
83 | api: &ApiConfig, | |
84 | parts: Parts, | |
85 | ) -> Response<Body> { | |
86 | ||
87 | let (userid, csrf_token) = match auth_id { | |
88 | Some(auth_id) => { | |
89 | let auth_id = auth_id.parse::<Authid>(); | |
90 | match auth_id { | |
91 | Ok(auth_id) if !auth_id.is_token() => { | |
92 | let userid = auth_id.user().clone(); | |
93 | let new_csrf_token = assemble_csrf_prevention_token(csrf_secret(), &userid); | |
94 | (Some(userid), Some(new_csrf_token)) | |
95 | } | |
96 | _ => (None, None) | |
97 | } | |
98 | } | |
99 | None => (None, None), | |
100 | }; | |
101 | ||
102 | let nodename = proxmox::tools::nodename(); | |
103 | let user = userid.as_ref().map(|u| u.as_str()).unwrap_or(""); | |
104 | ||
105 | let csrf_token = csrf_token.unwrap_or_else(|| String::from("")); | |
106 | ||
107 | let mut debug = false; | |
108 | let mut template_file = "index"; | |
109 | ||
110 | if let Some(query_str) = parts.uri.query() { | |
111 | for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() { | |
112 | if k == "debug" && v != "0" && v != "false" { | |
113 | debug = true; | |
114 | } else if k == "console" { | |
115 | template_file = "console"; | |
116 | } | |
117 | } | |
118 | } | |
119 | ||
120 | let mut lang = String::from(""); | |
121 | if let Some(language) = language { | |
122 | if Path::new(&format!("/usr/share/pbs-i18n/pbs-lang-{}.js", language)).exists() { | |
123 | lang = language; | |
124 | } | |
125 | } | |
126 | ||
127 | let data = json!({ | |
128 | "NodeName": nodename, | |
129 | "UserName": user, | |
130 | "CSRFPreventionToken": csrf_token, | |
131 | "language": lang, | |
132 | "debug": debug, | |
133 | }); | |
134 | ||
135 | let (ct, index) = match api.render_template(template_file, &data) { | |
136 | Ok(index) => ("text/html", index), | |
137 | Err(err) => ("text/plain", format!("Error rendering template: {}", err)), | |
138 | }; | |
139 | ||
140 | let mut resp = Response::builder() | |
141 | .status(StatusCode::OK) | |
142 | .header(header::CONTENT_TYPE, ct) | |
143 | .body(index.into()) | |
144 | .unwrap(); | |
145 | ||
146 | if let Some(userid) = userid { | |
147 | resp.extensions_mut().insert(Authid::from((userid, None))); | |
148 | } | |
149 | ||
150 | resp | |
151 | } | |
152 | ||
fda5797b | 153 | async fn run() -> Result<(), Error> { |
02c7a755 DM |
154 | if let Err(err) = syslog::init( |
155 | syslog::Facility::LOG_DAEMON, | |
156 | log::LevelFilter::Info, | |
157 | Some("proxmox-backup-proxy")) { | |
4223d9f8 | 158 | bail!("unable to inititialize syslog - {}", err); |
02c7a755 DM |
159 | } |
160 | ||
e1d367df DM |
161 | // Note: To debug early connection error use |
162 | // PROXMOX_DEBUG=1 ./target/release/proxmox-backup-proxy | |
163 | let debug = std::env::var("PROXMOX_DEBUG").is_ok(); | |
164 | ||
d01e2420 DM |
165 | let _ = public_auth_key(); // load with lazy_static |
166 | let _ = csrf_secret(); // load with lazy_static | |
167 | ||
02c7a755 | 168 | let mut config = ApiConfig::new( |
af06decd | 169 | pbs_buildcfg::JS_DIR, |
26858dba SR |
170 | &proxmox_backup::api2::ROUTER, |
171 | RpcEnvironmentType::PUBLIC, | |
172 | default_api_auth(), | |
7fa9a37c | 173 | get_index, |
26858dba | 174 | )?; |
02c7a755 | 175 | |
02c7a755 DM |
176 | config.add_alias("novnc", "/usr/share/novnc-pve"); |
177 | config.add_alias("extjs", "/usr/share/javascript/extjs"); | |
7f066a9b | 178 | config.add_alias("qrcodejs", "/usr/share/javascript/qrcodejs"); |
02c7a755 DM |
179 | config.add_alias("fontawesome", "/usr/share/fonts-font-awesome"); |
180 | config.add_alias("xtermjs", "/usr/share/pve-xtermjs"); | |
abd4c4cb | 181 | config.add_alias("locale", "/usr/share/pbs-i18n"); |
02c7a755 | 182 | config.add_alias("widgettoolkit", "/usr/share/javascript/proxmox-widget-toolkit"); |
9c01e73c | 183 | config.add_alias("docs", "/usr/share/doc/proxmox-backup/html"); |
02c7a755 | 184 | |
af06decd | 185 | let mut indexpath = PathBuf::from(pbs_buildcfg::JS_DIR); |
2ab5acac DC |
186 | indexpath.push("index.hbs"); |
187 | config.register_template("index", &indexpath)?; | |
01ca99da | 188 | config.register_template("console", "/usr/share/pve-xtermjs/index.html.hbs")?; |
2ab5acac | 189 | |
fd6d2438 DM |
190 | let backup_user = pbs_config::backup_user()?; |
191 | let mut commando_sock = proxmox_rest_server::CommandoSocket::new(crate::server::our_ctrl_sock(), backup_user.gid); | |
192 | ||
193 | let dir_opts = CreateOptions::new().owner(backup_user.uid).group(backup_user.gid); | |
194 | let file_opts = CreateOptions::new().owner(backup_user.uid).group(backup_user.gid); | |
a68768cf | 195 | |
fd6d2438 DM |
196 | config.enable_file_log( |
197 | pbs_buildcfg::API_ACCESS_LOG_FN, | |
36b7085e DM |
198 | Some(dir_opts.clone()), |
199 | Some(file_opts.clone()), | |
200 | &mut commando_sock, | |
201 | )?; | |
202 | ||
203 | config.enable_auth_log( | |
204 | pbs_buildcfg::API_AUTH_LOG_FN, | |
0a33fba4 DM |
205 | Some(dir_opts.clone()), |
206 | Some(file_opts.clone()), | |
fd6d2438 DM |
207 | &mut commando_sock, |
208 | )?; | |
8e7e2223 | 209 | |
02c7a755 | 210 | let rest_server = RestServer::new(config); |
0a33fba4 | 211 | proxmox_backup::server::init_worker_tasks(pbs_buildcfg::PROXMOX_BACKUP_LOG_DIR_M!().into(), file_opts.clone())?; |
02c7a755 | 212 | |
6d1f61b2 | 213 | //openssl req -x509 -newkey rsa:4096 -keyout /etc/proxmox-backup/proxy.key -out /etc/proxmox-backup/proxy.pem -nodes |
6d1f61b2 | 214 | |
4ce7da51 | 215 | // we build the initial acceptor here as we cannot start if this fails |
c381a162 | 216 | let acceptor = make_tls_acceptor()?; |
4ce7da51 | 217 | let acceptor = Arc::new(Mutex::new(acceptor)); |
6d1f61b2 | 218 | |
4ce7da51 | 219 | // to renew the acceptor we just add a command-socket handler |
a723c087 WB |
220 | commando_sock.register_command( |
221 | "reload-certificate".to_string(), | |
222 | { | |
4ce7da51 | 223 | let acceptor = Arc::clone(&acceptor); |
a723c087 | 224 | move |_value| -> Result<_, Error> { |
4ce7da51 DM |
225 | log::info!("reloading certificate"); |
226 | match make_tls_acceptor() { | |
227 | Err(err) => log::error!("error reloading certificate: {}", err), | |
228 | Ok(new_acceptor) => { | |
229 | let mut guard = acceptor.lock().unwrap(); | |
230 | *guard = new_acceptor; | |
231 | } | |
232 | } | |
a723c087 WB |
233 | Ok(Value::Null) |
234 | } | |
235 | }, | |
236 | )?; | |
0d176f36 | 237 | |
062cf75c DC |
238 | // to remove references for not configured datastores |
239 | commando_sock.register_command( | |
240 | "datastore-removed".to_string(), | |
241 | |_value| { | |
242 | if let Err(err) = proxmox_backup::backup::DataStore::remove_unused_datastores() { | |
243 | log::error!("could not refresh datastores: {}", err); | |
244 | } | |
245 | Ok(Value::Null) | |
246 | } | |
247 | )?; | |
248 | ||
a690ecac WB |
249 | let server = daemon::create_daemon( |
250 | ([0,0,0,0,0,0,0,0], 8007).into(), | |
a723c087 | 251 | move |listener, ready| { |
97168f92 | 252 | |
4ce7da51 | 253 | let connections = accept_connections(listener, acceptor, debug); |
7c667013 | 254 | let connections = hyper::server::accept::from_stream(ReceiverStream::new(connections)); |
083ff3fd WB |
255 | |
256 | Ok(ready | |
48aa2b93 | 257 | .and_then(|_| hyper::Server::builder(connections) |
083ff3fd | 258 | .serve(rest_server) |
fd6d2438 | 259 | .with_graceful_shutdown(proxmox_rest_server::shutdown_future()) |
083ff3fd WB |
260 | .map_err(Error::from) |
261 | ) | |
262 | .map_err(|err| eprintln!("server error: {}", err)) | |
263 | .map(|_| ()) | |
a690ecac | 264 | ) |
a2ca7137 | 265 | }, |
d7c6ad60 | 266 | "proxmox-backup-proxy.service", |
083ff3fd | 267 | ); |
a2ca7137 | 268 | |
af06decd | 269 | server::write_pid(pbs_buildcfg::PROXMOX_BACKUP_PROXY_PID_FN)?; |
d98c9a7a WB |
270 | daemon::systemd_notify(daemon::SystemdNotify::Ready)?; |
271 | ||
fda5797b | 272 | let init_result: Result<(), Error> = try_block!({ |
a68768cf TL |
273 | server::register_task_control_commands(&mut commando_sock)?; |
274 | commando_sock.spawn()?; | |
fd6d2438 | 275 | proxmox_rest_server::server_state_init()?; |
fda5797b WB |
276 | Ok(()) |
277 | }); | |
d607b886 | 278 | |
fda5797b WB |
279 | if let Err(err) = init_result { |
280 | bail!("unable to start daemon - {}", err); | |
281 | } | |
e3f41f21 | 282 | |
8545480a | 283 | start_task_scheduler(); |
eaeda365 | 284 | start_stat_generator(); |
8545480a | 285 | |
083ff3fd | 286 | server.await?; |
a546a8a0 | 287 | log::info!("server shutting down, waiting for active workers to complete"); |
fd6d2438 | 288 | proxmox_rest_server::last_worker_future().await?; |
fda5797b | 289 | log::info!("done - exit server"); |
e3f41f21 | 290 | |
4223d9f8 | 291 | Ok(()) |
02c7a755 | 292 | } |
8545480a | 293 | |
4ce7da51 | 294 | fn make_tls_acceptor() -> Result<SslAcceptor, Error> { |
c381a162 WB |
295 | let key_path = configdir!("/proxy.key"); |
296 | let cert_path = configdir!("/proxy.pem"); | |
297 | ||
298 | let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap(); | |
299 | acceptor.set_private_key_file(key_path, SslFiletype::PEM) | |
300 | .map_err(|err| format_err!("unable to read proxy key {} - {}", key_path, err))?; | |
301 | acceptor.set_certificate_chain_file(cert_path) | |
302 | .map_err(|err| format_err!("unable to read proxy cert {} - {}", cert_path, err))?; | |
303 | acceptor.check_private_key().unwrap(); | |
304 | ||
4ce7da51 | 305 | Ok(acceptor.build()) |
c381a162 WB |
306 | } |
307 | ||
a5e3be49 WB |
308 | type ClientStreamResult = |
309 | Result<std::pin::Pin<Box<tokio_openssl::SslStream<tokio::net::TcpStream>>>, Error>; | |
310 | const MAX_PENDING_ACCEPTS: usize = 1024; | |
311 | ||
48aa2b93 | 312 | fn accept_connections( |
0bfcea6a | 313 | listener: tokio::net::TcpListener, |
4ce7da51 | 314 | acceptor: Arc<Mutex<openssl::ssl::SslAcceptor>>, |
e1d367df | 315 | debug: bool, |
a5e3be49 | 316 | ) -> tokio::sync::mpsc::Receiver<ClientStreamResult> { |
48aa2b93 | 317 | |
ea93bea7 | 318 | let (sender, receiver) = tokio::sync::mpsc::channel(MAX_PENDING_ACCEPTS); |
48aa2b93 | 319 | |
4ce7da51 | 320 | tokio::spawn(accept_connection(listener, acceptor, debug, sender)); |
a5e3be49 WB |
321 | |
322 | receiver | |
323 | } | |
324 | ||
325 | async fn accept_connection( | |
326 | listener: tokio::net::TcpListener, | |
4ce7da51 | 327 | acceptor: Arc<Mutex<openssl::ssl::SslAcceptor>>, |
a5e3be49 WB |
328 | debug: bool, |
329 | sender: tokio::sync::mpsc::Sender<ClientStreamResult>, | |
330 | ) { | |
ea93bea7 | 331 | let accept_counter = Arc::new(()); |
48aa2b93 | 332 | |
a5e3be49 | 333 | loop { |
4ce7da51 DM |
334 | let (sock, _addr) = match listener.accept().await { |
335 | Ok(conn) => conn, | |
336 | Err(err) => { | |
337 | eprintln!("error accepting tcp connection: {}", err); | |
cc269b9f | 338 | continue; |
a5e3be49 | 339 | } |
cc269b9f | 340 | }; |
48aa2b93 | 341 | |
cc269b9f WB |
342 | sock.set_nodelay(true).unwrap(); |
343 | let _ = set_tcp_keepalive(sock.as_raw_fd(), PROXMOX_BACKUP_TCP_KEEPALIVE_TIME); | |
48aa2b93 | 344 | |
4ce7da51 DM |
345 | let ssl = { // limit acceptor_guard scope |
346 | // Acceptor can be reloaded using the command socket "reload-certificate" command | |
347 | let acceptor_guard = acceptor.lock().unwrap(); | |
348 | ||
349 | match openssl::ssl::Ssl::new(acceptor_guard.context()) { | |
350 | Ok(ssl) => ssl, | |
351 | Err(err) => { | |
352 | eprintln!("failed to create Ssl object from Acceptor context - {}", err); | |
353 | continue; | |
354 | }, | |
355 | } | |
cc269b9f | 356 | }; |
4ce7da51 | 357 | |
cc269b9f WB |
358 | let stream = match tokio_openssl::SslStream::new(ssl, sock) { |
359 | Ok(stream) => stream, | |
360 | Err(err) => { | |
361 | eprintln!("failed to create SslStream using ssl and connection socket - {}", err); | |
362 | continue; | |
363 | }, | |
364 | }; | |
365 | ||
366 | let mut stream = Box::pin(stream); | |
367 | let sender = sender.clone(); | |
368 | ||
369 | if Arc::strong_count(&accept_counter) > MAX_PENDING_ACCEPTS { | |
370 | eprintln!("connection rejected - to many open connections"); | |
371 | continue; | |
48aa2b93 | 372 | } |
cc269b9f | 373 | |
b4931192 | 374 | let accept_counter = Arc::clone(&accept_counter); |
cc269b9f WB |
375 | tokio::spawn(async move { |
376 | let accept_future = tokio::time::timeout( | |
377 | Duration::new(10, 0), stream.as_mut().accept()); | |
378 | ||
379 | let result = accept_future.await; | |
380 | ||
381 | match result { | |
382 | Ok(Ok(())) => { | |
383 | if sender.send(Ok(stream)).await.is_err() && debug { | |
384 | eprintln!("detect closed connection channel"); | |
385 | } | |
386 | } | |
387 | Ok(Err(err)) => { | |
388 | if debug { | |
389 | eprintln!("https handshake failed - {}", err); | |
390 | } | |
391 | } | |
392 | Err(_) => { | |
393 | if debug { | |
394 | eprintln!("https handshake timeout"); | |
395 | } | |
396 | } | |
397 | } | |
398 | ||
399 | drop(accept_counter); // decrease reference count | |
400 | }); | |
a5e3be49 | 401 | } |
48aa2b93 DM |
402 | } |
403 | ||
eaeda365 | 404 | fn start_stat_generator() { |
fd6d2438 | 405 | let abort_future = proxmox_rest_server::shutdown_future(); |
eaeda365 DM |
406 | let future = Box::pin(run_stat_generator()); |
407 | let task = futures::future::select(future, abort_future); | |
408 | tokio::spawn(task.map(|_| ())); | |
409 | } | |
410 | ||
8545480a | 411 | fn start_task_scheduler() { |
fd6d2438 | 412 | let abort_future = proxmox_rest_server::shutdown_future(); |
8545480a DM |
413 | let future = Box::pin(run_task_scheduler()); |
414 | let task = futures::future::select(future, abort_future); | |
415 | tokio::spawn(task.map(|_| ())); | |
416 | } | |
417 | ||
6a7be83e | 418 | use std::time::{SystemTime, Instant, Duration, UNIX_EPOCH}; |
8545480a DM |
419 | |
420 | fn next_minute() -> Result<Instant, Error> { | |
6a7be83e DM |
421 | let now = SystemTime::now(); |
422 | let epoch_now = now.duration_since(UNIX_EPOCH)?; | |
423 | let epoch_next = Duration::from_secs((epoch_now.as_secs()/60 + 1)*60); | |
8545480a DM |
424 | Ok(Instant::now() + epoch_next - epoch_now) |
425 | } | |
426 | ||
427 | async fn run_task_scheduler() { | |
428 | ||
429 | let mut count: usize = 0; | |
430 | ||
431 | loop { | |
432 | count += 1; | |
433 | ||
434 | let delay_target = match next_minute() { // try to run very minute | |
435 | Ok(d) => d, | |
436 | Err(err) => { | |
437 | eprintln!("task scheduler: compute next minute failed - {}", err); | |
0a8d773a | 438 | tokio::time::sleep_until(tokio::time::Instant::from_std(Instant::now() + Duration::from_secs(60))).await; |
8545480a DM |
439 | continue; |
440 | } | |
441 | }; | |
442 | ||
443 | if count > 2 { // wait 1..2 minutes before starting | |
444 | match schedule_tasks().catch_unwind().await { | |
445 | Err(panic) => { | |
446 | match panic.downcast::<&str>() { | |
447 | Ok(msg) => { | |
448 | eprintln!("task scheduler panic: {}", msg); | |
449 | } | |
450 | Err(_) => { | |
451 | eprintln!("task scheduler panic - unknown type"); | |
452 | } | |
453 | } | |
454 | } | |
455 | Ok(Err(err)) => { | |
456 | eprintln!("task scheduler failed - {:?}", err); | |
457 | } | |
458 | Ok(Ok(_)) => {} | |
459 | } | |
460 | } | |
461 | ||
0a8d773a | 462 | tokio::time::sleep_until(tokio::time::Instant::from_std(delay_target)).await; |
8545480a DM |
463 | } |
464 | } | |
465 | ||
466 | async fn schedule_tasks() -> Result<(), Error> { | |
467 | ||
468 | schedule_datastore_garbage_collection().await; | |
25829a87 | 469 | schedule_datastore_prune().await; |
a6160cdf | 470 | schedule_datastore_sync_jobs().await; |
73df9c51 | 471 | schedule_datastore_verify_jobs().await; |
8513626b | 472 | schedule_tape_backup_jobs().await; |
9a760917 | 473 | schedule_task_log_rotate().await; |
8545480a DM |
474 | |
475 | Ok(()) | |
476 | } | |
477 | ||
8545480a DM |
478 | async fn schedule_datastore_garbage_collection() { |
479 | ||
e7d4be9d | 480 | let config = match pbs_config::datastore::config() { |
8545480a DM |
481 | Err(err) => { |
482 | eprintln!("unable to read datastore config - {}", err); | |
483 | return; | |
484 | } | |
485 | Ok((config, _digest)) => config, | |
486 | }; | |
487 | ||
488 | for (store, (_, store_config)) in config.sections { | |
489 | let datastore = match DataStore::lookup_datastore(&store) { | |
490 | Ok(datastore) => datastore, | |
491 | Err(err) => { | |
492 | eprintln!("lookup_datastore failed - {}", err); | |
493 | continue; | |
494 | } | |
495 | }; | |
496 | ||
25829a87 | 497 | let store_config: DataStoreConfig = match serde_json::from_value(store_config) { |
8545480a DM |
498 | Ok(c) => c, |
499 | Err(err) => { | |
500 | eprintln!("datastore config from_value failed - {}", err); | |
501 | continue; | |
502 | } | |
503 | }; | |
504 | ||
505 | let event_str = match store_config.gc_schedule { | |
506 | Some(event_str) => event_str, | |
507 | None => continue, | |
508 | }; | |
509 | ||
510 | let event = match parse_calendar_event(&event_str) { | |
511 | Ok(event) => event, | |
512 | Err(err) => { | |
513 | eprintln!("unable to parse schedule '{}' - {}", event_str, err); | |
514 | continue; | |
515 | } | |
516 | }; | |
517 | ||
518 | if datastore.garbage_collection_running() { continue; } | |
519 | ||
520 | let worker_type = "garbage_collection"; | |
521 | ||
b6ba5acd DC |
522 | let last = match jobstate::last_run_time(worker_type, &store) { |
523 | Ok(time) => time, | |
524 | Err(err) => { | |
525 | eprintln!("could not get last run time of {} {}: {}", worker_type, store, err); | |
526 | continue; | |
8545480a DM |
527 | } |
528 | }; | |
529 | ||
530 | let next = match compute_next_event(&event, last, false) { | |
15ec790a DC |
531 | Ok(Some(next)) => next, |
532 | Ok(None) => continue, | |
8545480a DM |
533 | Err(err) => { |
534 | eprintln!("compute_next_event for '{}' failed - {}", event_str, err); | |
535 | continue; | |
536 | } | |
537 | }; | |
e693818a | 538 | |
6a7be83e DM |
539 | let now = proxmox::tools::time::epoch_i64(); |
540 | ||
8545480a DM |
541 | if next > now { continue; } |
542 | ||
1cd951c9 | 543 | let job = match Job::new(worker_type, &store) { |
d7a122a0 DC |
544 | Ok(job) => job, |
545 | Err(_) => continue, // could not get lock | |
546 | }; | |
547 | ||
ad54df31 | 548 | let auth_id = Authid::root_auth_id(); |
d7a122a0 | 549 | |
c724f658 | 550 | if let Err(err) = crate::server::do_garbage_collection_job(job, datastore, auth_id, Some(event_str), false) { |
3b707fbb | 551 | eprintln!("unable to start garbage collection job on datastore {} - {}", store, err); |
8545480a DM |
552 | } |
553 | } | |
554 | } | |
25829a87 DM |
555 | |
556 | async fn schedule_datastore_prune() { | |
557 | ||
e7d4be9d | 558 | let config = match pbs_config::datastore::config() { |
25829a87 DM |
559 | Err(err) => { |
560 | eprintln!("unable to read datastore config - {}", err); | |
561 | return; | |
562 | } | |
563 | Ok((config, _digest)) => config, | |
564 | }; | |
565 | ||
566 | for (store, (_, store_config)) in config.sections { | |
25829a87 DM |
567 | |
568 | let store_config: DataStoreConfig = match serde_json::from_value(store_config) { | |
569 | Ok(c) => c, | |
570 | Err(err) => { | |
a6160cdf | 571 | eprintln!("datastore '{}' config from_value failed - {}", store, err); |
25829a87 DM |
572 | continue; |
573 | } | |
574 | }; | |
575 | ||
576 | let event_str = match store_config.prune_schedule { | |
577 | Some(event_str) => event_str, | |
578 | None => continue, | |
579 | }; | |
580 | ||
581 | let prune_options = PruneOptions { | |
582 | keep_last: store_config.keep_last, | |
583 | keep_hourly: store_config.keep_hourly, | |
584 | keep_daily: store_config.keep_daily, | |
585 | keep_weekly: store_config.keep_weekly, | |
586 | keep_monthly: store_config.keep_monthly, | |
587 | keep_yearly: store_config.keep_yearly, | |
588 | }; | |
589 | ||
89725197 | 590 | if !pbs_datastore::prune::keeps_something(&prune_options) { // no prune settings - keep all |
25829a87 DM |
591 | continue; |
592 | } | |
593 | ||
25829a87 | 594 | let worker_type = "prune"; |
b15751bf | 595 | if check_schedule(worker_type, &event_str, &store) { |
82c05b41 HL |
596 | let job = match Job::new(worker_type, &store) { |
597 | Ok(job) => job, | |
598 | Err(_) => continue, // could not get lock | |
599 | }; | |
25829a87 | 600 | |
ad54df31 | 601 | let auth_id = Authid::root_auth_id().clone(); |
82c05b41 HL |
602 | if let Err(err) = do_prune_job(job, prune_options, store.clone(), &auth_id, Some(event_str)) { |
603 | eprintln!("unable to start datastore prune job {} - {}", &store, err); | |
25829a87 DM |
604 | } |
605 | }; | |
25829a87 DM |
606 | } |
607 | } | |
a6160cdf DM |
608 | |
609 | async fn schedule_datastore_sync_jobs() { | |
610 | ||
a6160cdf | 611 | |
a4e5a0fc | 612 | let config = match pbs_config::sync::config() { |
a6160cdf DM |
613 | Err(err) => { |
614 | eprintln!("unable to read sync job config - {}", err); | |
615 | return; | |
616 | } | |
617 | Ok((config, _digest)) => config, | |
618 | }; | |
619 | ||
a6160cdf DM |
620 | for (job_id, (_, job_config)) in config.sections { |
621 | let job_config: SyncJobConfig = match serde_json::from_value(job_config) { | |
622 | Ok(c) => c, | |
623 | Err(err) => { | |
624 | eprintln!("sync job config from_value failed - {}", err); | |
625 | continue; | |
626 | } | |
627 | }; | |
628 | ||
629 | let event_str = match job_config.schedule { | |
630 | Some(ref event_str) => event_str.clone(), | |
631 | None => continue, | |
632 | }; | |
633 | ||
c67b1fa7 | 634 | let worker_type = "syncjob"; |
b15751bf | 635 | if check_schedule(worker_type, &event_str, &job_id) { |
82c05b41 HL |
636 | let job = match Job::new(worker_type, &job_id) { |
637 | Ok(job) => job, | |
638 | Err(_) => continue, // could not get lock | |
639 | }; | |
a6160cdf | 640 | |
ad54df31 | 641 | let auth_id = Authid::root_auth_id().clone(); |
bfa942c0 | 642 | if let Err(err) = do_sync_job(job, job_config, &auth_id, Some(event_str), false) { |
82c05b41 | 643 | eprintln!("unable to start datastore sync job {} - {}", &job_id, err); |
a6160cdf DM |
644 | } |
645 | }; | |
a6160cdf DM |
646 | } |
647 | } | |
eaeda365 | 648 | |
73df9c51 | 649 | async fn schedule_datastore_verify_jobs() { |
1298618a | 650 | |
802189f7 | 651 | let config = match pbs_config::verify::config() { |
73df9c51 HL |
652 | Err(err) => { |
653 | eprintln!("unable to read verification job config - {}", err); | |
654 | return; | |
655 | } | |
656 | Ok((config, _digest)) => config, | |
657 | }; | |
658 | for (job_id, (_, job_config)) in config.sections { | |
659 | let job_config: VerificationJobConfig = match serde_json::from_value(job_config) { | |
660 | Ok(c) => c, | |
661 | Err(err) => { | |
662 | eprintln!("verification job config from_value failed - {}", err); | |
663 | continue; | |
664 | } | |
665 | }; | |
666 | let event_str = match job_config.schedule { | |
667 | Some(ref event_str) => event_str.clone(), | |
668 | None => continue, | |
669 | }; | |
82c05b41 | 670 | |
73df9c51 | 671 | let worker_type = "verificationjob"; |
ad54df31 | 672 | let auth_id = Authid::root_auth_id().clone(); |
b15751bf | 673 | if check_schedule(worker_type, &event_str, &job_id) { |
82c05b41 HL |
674 | let job = match Job::new(&worker_type, &job_id) { |
675 | Ok(job) => job, | |
676 | Err(_) => continue, // could not get lock | |
677 | }; | |
bfa942c0 | 678 | if let Err(err) = do_verification_job(job, job_config, &auth_id, Some(event_str), false) { |
82c05b41 | 679 | eprintln!("unable to start datastore verification job {} - {}", &job_id, err); |
73df9c51 HL |
680 | } |
681 | }; | |
73df9c51 HL |
682 | } |
683 | } | |
684 | ||
8513626b DM |
685 | async fn schedule_tape_backup_jobs() { |
686 | ||
e3619d41 | 687 | let config = match pbs_config::tape_job::config() { |
8513626b DM |
688 | Err(err) => { |
689 | eprintln!("unable to read tape job config - {}", err); | |
690 | return; | |
691 | } | |
692 | Ok((config, _digest)) => config, | |
693 | }; | |
694 | for (job_id, (_, job_config)) in config.sections { | |
695 | let job_config: TapeBackupJobConfig = match serde_json::from_value(job_config) { | |
696 | Ok(c) => c, | |
697 | Err(err) => { | |
698 | eprintln!("tape backup job config from_value failed - {}", err); | |
699 | continue; | |
700 | } | |
701 | }; | |
702 | let event_str = match job_config.schedule { | |
703 | Some(ref event_str) => event_str.clone(), | |
704 | None => continue, | |
705 | }; | |
706 | ||
707 | let worker_type = "tape-backup-job"; | |
708 | let auth_id = Authid::root_auth_id().clone(); | |
709 | if check_schedule(worker_type, &event_str, &job_id) { | |
710 | let job = match Job::new(&worker_type, &job_id) { | |
711 | Ok(job) => job, | |
712 | Err(_) => continue, // could not get lock | |
713 | }; | |
bfa942c0 | 714 | if let Err(err) = do_tape_backup_job(job, job_config.setup, &auth_id, Some(event_str), false) { |
7a61f89e | 715 | eprintln!("unable to start tape backup job {} - {}", &job_id, err); |
8513626b DM |
716 | } |
717 | }; | |
718 | } | |
719 | } | |
720 | ||
721 | ||
9a760917 | 722 | async fn schedule_task_log_rotate() { |
9a760917 DC |
723 | |
724 | let worker_type = "logrotate"; | |
72aa1834 | 725 | let job_id = "access-log_and_task-archive"; |
9a760917 | 726 | |
9a760917 DC |
727 | // schedule daily at 00:00 like normal logrotate |
728 | let schedule = "00:00"; | |
729 | ||
b15751bf | 730 | if !check_schedule(worker_type, schedule, job_id) { |
9a760917 DC |
731 | // if we never ran the rotation, schedule instantly |
732 | match jobstate::JobState::load(worker_type, job_id) { | |
733 | Ok(state) => match state { | |
734 | jobstate::JobState::Created { .. } => {}, | |
735 | _ => return, | |
736 | }, | |
737 | _ => return, | |
738 | } | |
739 | } | |
740 | ||
741 | let mut job = match Job::new(worker_type, job_id) { | |
742 | Ok(job) => job, | |
743 | Err(_) => return, // could not get lock | |
744 | }; | |
745 | ||
746 | if let Err(err) = WorkerTask::new_thread( | |
747 | worker_type, | |
72aa1834 | 748 | None, |
049a22a3 | 749 | Authid::root_auth_id().to_string(), |
9a760917 DC |
750 | false, |
751 | move |worker| { | |
752 | job.start(&worker.upid().to_string())?; | |
3b82f3ee | 753 | worker.log("starting task log rotation".to_string()); |
e4f5f59e | 754 | |
9a760917 | 755 | let result = try_block!({ |
b7f2be51 TL |
756 | let max_size = 512 * 1024 - 1; // an entry has ~ 100b, so > 5000 entries/file |
757 | let max_files = 20; // times twenty files gives > 100000 task entries | |
9a760917 DC |
758 | let has_rotated = rotate_task_log_archive(max_size, true, Some(max_files))?; |
759 | if has_rotated { | |
3b82f3ee | 760 | worker.log("task log archive was rotated".to_string()); |
9a760917 | 761 | } else { |
3b82f3ee | 762 | worker.log("task log archive was not rotated".to_string()); |
9a760917 DC |
763 | } |
764 | ||
fe4cc5b1 TL |
765 | let max_size = 32 * 1024 * 1024 - 1; |
766 | let max_files = 14; | |
af06decd | 767 | let mut logrotate = LogRotate::new(pbs_buildcfg::API_ACCESS_LOG_FN, true) |
fe4cc5b1 TL |
768 | .ok_or_else(|| format_err!("could not get API access log file names"))?; |
769 | ||
fe7bdc9d | 770 | if logrotate.rotate(max_size, None, Some(max_files))? { |
fe4cc5b1 | 771 | println!("rotated access log, telling daemons to re-open log file"); |
36b7085e | 772 | pbs_runtime::block_on(command_reopen_access_logfiles())?; |
3b82f3ee | 773 | worker.log("API access log was rotated".to_string()); |
fe7bdc9d | 774 | } else { |
3b82f3ee | 775 | worker.log("API access log was not rotated".to_string()); |
fe7bdc9d TL |
776 | } |
777 | ||
af06decd | 778 | let mut logrotate = LogRotate::new(pbs_buildcfg::API_AUTH_LOG_FN, true) |
fe7bdc9d | 779 | .ok_or_else(|| format_err!("could not get API auth log file names"))?; |
fe4cc5b1 | 780 | |
fe7bdc9d | 781 | if logrotate.rotate(max_size, None, Some(max_files))? { |
36b7085e DM |
782 | println!("rotated auth log, telling daemons to re-open log file"); |
783 | pbs_runtime::block_on(command_reopen_auth_logfiles())?; | |
3b82f3ee | 784 | worker.log("API authentication log was rotated".to_string()); |
fe4cc5b1 | 785 | } else { |
3b82f3ee | 786 | worker.log("API authentication log was not rotated".to_string()); |
fe4cc5b1 TL |
787 | } |
788 | ||
9a760917 DC |
789 | Ok(()) |
790 | }); | |
791 | ||
792 | let status = worker.create_state(&result); | |
793 | ||
794 | if let Err(err) = job.finish(status) { | |
795 | eprintln!("could not finish job state for {}: {}", worker_type, err); | |
796 | } | |
797 | ||
798 | result | |
799 | }, | |
800 | ) { | |
801 | eprintln!("unable to start task log rotation: {}", err); | |
802 | } | |
803 | ||
804 | } | |
805 | ||
36b7085e | 806 | async fn command_reopen_access_logfiles() -> Result<(), Error> { |
fe4cc5b1 TL |
807 | // only care about the most recent daemon instance for each, proxy & api, as other older ones |
808 | // should not respond to new requests anyway, but only finish their current one and then exit. | |
fd6d2438 DM |
809 | let sock = crate::server::our_ctrl_sock(); |
810 | let f1 = proxmox_rest_server::send_command(sock, "{\"command\":\"api-access-log-reopen\"}\n"); | |
fe4cc5b1 | 811 | |
fd6d2438 DM |
812 | let pid = crate::server::read_pid(pbs_buildcfg::PROXMOX_BACKUP_API_PID_FN)?; |
813 | let sock = crate::server::ctrl_sock_from_pid(pid); | |
814 | let f2 = proxmox_rest_server::send_command(sock, "{\"command\":\"api-access-log-reopen\"}\n"); | |
546b6a23 TL |
815 | |
816 | match futures::join!(f1, f2) { | |
817 | (Err(e1), Err(e2)) => Err(format_err!("reopen commands failed, proxy: {}; api: {}", e1, e2)), | |
818 | (Err(e1), Ok(_)) => Err(format_err!("reopen commands failed, proxy: {}", e1)), | |
36b7085e DM |
819 | (Ok(_), Err(e2)) => Err(format_err!("reopen commands failed, api: {}", e2)), |
820 | _ => Ok(()), | |
821 | } | |
822 | } | |
823 | ||
824 | async fn command_reopen_auth_logfiles() -> Result<(), Error> { | |
825 | // only care about the most recent daemon instance for each, proxy & api, as other older ones | |
826 | // should not respond to new requests anyway, but only finish their current one and then exit. | |
827 | let sock = crate::server::our_ctrl_sock(); | |
828 | let f1 = proxmox_rest_server::send_command(sock, "{\"command\":\"api-auth-log-reopen\"}\n"); | |
829 | ||
830 | let pid = crate::server::read_pid(pbs_buildcfg::PROXMOX_BACKUP_API_PID_FN)?; | |
831 | let sock = crate::server::ctrl_sock_from_pid(pid); | |
832 | let f2 = proxmox_rest_server::send_command(sock, "{\"command\":\"api-auth-log-reopen\"}\n"); | |
833 | ||
834 | match futures::join!(f1, f2) { | |
835 | (Err(e1), Err(e2)) => Err(format_err!("reopen commands failed, proxy: {}; api: {}", e1, e2)), | |
836 | (Err(e1), Ok(_)) => Err(format_err!("reopen commands failed, proxy: {}", e1)), | |
546b6a23 TL |
837 | (Ok(_), Err(e2)) => Err(format_err!("reopen commands failed, api: {}", e2)), |
838 | _ => Ok(()), | |
839 | } | |
fe4cc5b1 TL |
840 | } |
841 | ||
eaeda365 DM |
842 | async fn run_stat_generator() { |
843 | ||
013fa7bb | 844 | let mut count = 0; |
eaeda365 | 845 | loop { |
013fa7bb | 846 | count += 1; |
a720894f | 847 | let save = if count >= 6 { count = 0; true } else { false }; |
013fa7bb | 848 | |
eaeda365 DM |
849 | let delay_target = Instant::now() + Duration::from_secs(10); |
850 | ||
013fa7bb | 851 | generate_host_stats(save).await; |
eaeda365 | 852 | |
0a8d773a | 853 | tokio::time::sleep_until(tokio::time::Instant::from_std(delay_target)).await; |
013fa7bb DM |
854 | |
855 | } | |
eaeda365 DM |
856 | |
857 | } | |
858 | ||
013fa7bb | 859 | fn rrd_update_gauge(name: &str, value: f64, save: bool) { |
309ef20d | 860 | use proxmox_backup::rrd; |
013fa7bb | 861 | if let Err(err) = rrd::update_value(name, value, rrd::DST::Gauge, save) { |
309ef20d DM |
862 | eprintln!("rrd::update_value '{}' failed - {}", name, err); |
863 | } | |
864 | } | |
865 | ||
013fa7bb | 866 | fn rrd_update_derive(name: &str, value: f64, save: bool) { |
309ef20d | 867 | use proxmox_backup::rrd; |
013fa7bb | 868 | if let Err(err) = rrd::update_value(name, value, rrd::DST::Derive, save) { |
309ef20d DM |
869 | eprintln!("rrd::update_value '{}' failed - {}", name, err); |
870 | } | |
871 | } | |
872 | ||
013fa7bb | 873 | async fn generate_host_stats(save: bool) { |
8f0cec26 | 874 | use proxmox::sys::linux::procfs::{ |
485841da | 875 | read_meminfo, read_proc_stat, read_proc_net_dev, read_loadavg}; |
eaeda365 | 876 | |
d420962f | 877 | pbs_runtime::block_in_place(move || { |
4f951399 DM |
878 | |
879 | match read_proc_stat() { | |
880 | Ok(stat) => { | |
013fa7bb DM |
881 | rrd_update_gauge("host/cpu", stat.cpu, save); |
882 | rrd_update_gauge("host/iowait", stat.iowait_percent, save); | |
4f951399 DM |
883 | } |
884 | Err(err) => { | |
885 | eprintln!("read_proc_stat failed - {}", err); | |
eaeda365 DM |
886 | } |
887 | } | |
2c66a590 | 888 | |
4f951399 DM |
889 | match read_meminfo() { |
890 | Ok(meminfo) => { | |
013fa7bb DM |
891 | rrd_update_gauge("host/memtotal", meminfo.memtotal as f64, save); |
892 | rrd_update_gauge("host/memused", meminfo.memused as f64, save); | |
893 | rrd_update_gauge("host/swaptotal", meminfo.swaptotal as f64, save); | |
894 | rrd_update_gauge("host/swapused", meminfo.swapused as f64, save); | |
a4a3f7ca | 895 | } |
4f951399 DM |
896 | Err(err) => { |
897 | eprintln!("read_meminfo failed - {}", err); | |
a4a3f7ca DM |
898 | } |
899 | } | |
8f0cec26 | 900 | |
4f951399 DM |
901 | match read_proc_net_dev() { |
902 | Ok(netdev) => { | |
6f422880 | 903 | use pbs_config::network::is_physical_nic; |
4f951399 DM |
904 | let mut netin = 0; |
905 | let mut netout = 0; | |
906 | for item in netdev { | |
907 | if !is_physical_nic(&item.device) { continue; } | |
908 | netin += item.receive; | |
909 | netout += item.send; | |
910 | } | |
013fa7bb DM |
911 | rrd_update_derive("host/netin", netin as f64, save); |
912 | rrd_update_derive("host/netout", netout as f64, save); | |
8f0cec26 | 913 | } |
4f951399 DM |
914 | Err(err) => { |
915 | eprintln!("read_prox_net_dev failed - {}", err); | |
8f0cec26 DM |
916 | } |
917 | } | |
dd15c0aa | 918 | |
485841da DM |
919 | match read_loadavg() { |
920 | Ok(loadavg) => { | |
013fa7bb | 921 | rrd_update_gauge("host/loadavg", loadavg.0 as f64, save); |
485841da DM |
922 | } |
923 | Err(err) => { | |
924 | eprintln!("read_loadavg failed - {}", err); | |
925 | } | |
926 | } | |
927 | ||
8c03041a DM |
928 | let disk_manager = DiskManage::new(); |
929 | ||
013fa7bb | 930 | gather_disk_stats(disk_manager.clone(), Path::new("/"), "host", save); |
91e5bb49 | 931 | |
e7d4be9d | 932 | match pbs_config::datastore::config() { |
d0833a70 | 933 | Ok((config, _)) => { |
e7d4be9d | 934 | let datastore_list: Vec<DataStoreConfig> = |
17c7b46a | 935 | config.convert_to_typed_array("datastore").unwrap_or_default(); |
d0833a70 DM |
936 | |
937 | for config in datastore_list { | |
8c03041a | 938 | |
91e5bb49 | 939 | let rrd_prefix = format!("datastore/{}", config.name); |
8c03041a | 940 | let path = std::path::Path::new(&config.path); |
013fa7bb | 941 | gather_disk_stats(disk_manager.clone(), path, &rrd_prefix, save); |
d0833a70 DM |
942 | } |
943 | } | |
944 | Err(err) => { | |
945 | eprintln!("read datastore config failed - {}", err); | |
946 | } | |
947 | } | |
948 | ||
4f951399 | 949 | }); |
eaeda365 | 950 | } |
dd15c0aa | 951 | |
b15751bf DM |
952 | fn check_schedule(worker_type: &str, event_str: &str, id: &str) -> bool { |
953 | let event = match parse_calendar_event(event_str) { | |
82c05b41 HL |
954 | Ok(event) => event, |
955 | Err(err) => { | |
956 | eprintln!("unable to parse schedule '{}' - {}", event_str, err); | |
957 | return false; | |
958 | } | |
959 | }; | |
960 | ||
b15751bf | 961 | let last = match jobstate::last_run_time(worker_type, &id) { |
82c05b41 HL |
962 | Ok(time) => time, |
963 | Err(err) => { | |
964 | eprintln!("could not get last run time of {} {}: {}", worker_type, id, err); | |
965 | return false; | |
966 | } | |
967 | }; | |
968 | ||
969 | let next = match compute_next_event(&event, last, false) { | |
970 | Ok(Some(next)) => next, | |
971 | Ok(None) => return false, | |
972 | Err(err) => { | |
973 | eprintln!("compute_next_event for '{}' failed - {}", event_str, err); | |
974 | return false; | |
975 | } | |
976 | }; | |
977 | ||
978 | let now = proxmox::tools::time::epoch_i64(); | |
979 | next <= now | |
980 | } | |
981 | ||
013fa7bb | 982 | fn gather_disk_stats(disk_manager: Arc<DiskManage>, path: &Path, rrd_prefix: &str, save: bool) { |
91e5bb49 | 983 | |
934f5bb8 | 984 | match proxmox_backup::tools::disks::disk_usage(path) { |
33070956 | 985 | Ok(status) => { |
91e5bb49 | 986 | let rrd_key = format!("{}/total", rrd_prefix); |
33070956 | 987 | rrd_update_gauge(&rrd_key, status.total as f64, save); |
91e5bb49 | 988 | let rrd_key = format!("{}/used", rrd_prefix); |
33070956 | 989 | rrd_update_gauge(&rrd_key, status.used as f64, save); |
91e5bb49 DM |
990 | } |
991 | Err(err) => { | |
992 | eprintln!("read disk_usage on {:?} failed - {}", path, err); | |
993 | } | |
994 | } | |
995 | ||
934f5bb8 DM |
996 | match disk_manager.find_mounted_device(path) { |
997 | Ok(None) => {}, | |
998 | Ok(Some((fs_type, device, source))) => { | |
999 | let mut device_stat = None; | |
1000 | match fs_type.as_str() { | |
1001 | "zfs" => { | |
368f4c54 DC |
1002 | if let Some(source) = source { |
1003 | let pool = get_pool_from_dataset(&source).unwrap_or(&source); | |
1004 | match zfs_pool_stats(pool) { | |
934f5bb8 DM |
1005 | Ok(stat) => device_stat = stat, |
1006 | Err(err) => eprintln!("zfs_pool_stats({:?}) failed - {}", pool, err), | |
91e5bb49 DM |
1007 | } |
1008 | } | |
934f5bb8 DM |
1009 | } |
1010 | _ => { | |
1011 | if let Ok(disk) = disk_manager.clone().disk_by_dev_num(device.into_dev_t()) { | |
1012 | match disk.read_stat() { | |
1013 | Ok(stat) => device_stat = stat, | |
1014 | Err(err) => eprintln!("disk.read_stat {:?} failed - {}", path, err), | |
91e5bb49 DM |
1015 | } |
1016 | } | |
1017 | } | |
91e5bb49 | 1018 | } |
934f5bb8 DM |
1019 | if let Some(stat) = device_stat { |
1020 | let rrd_key = format!("{}/read_ios", rrd_prefix); | |
1021 | rrd_update_derive(&rrd_key, stat.read_ios as f64, save); | |
1022 | let rrd_key = format!("{}/read_bytes", rrd_prefix); | |
1023 | rrd_update_derive(&rrd_key, (stat.read_sectors*512) as f64, save); | |
dd15c0aa | 1024 | |
934f5bb8 DM |
1025 | let rrd_key = format!("{}/write_ios", rrd_prefix); |
1026 | rrd_update_derive(&rrd_key, stat.write_ios as f64, save); | |
1027 | let rrd_key = format!("{}/write_bytes", rrd_prefix); | |
1028 | rrd_update_derive(&rrd_key, (stat.write_sectors*512) as f64, save); | |
dd15c0aa | 1029 | |
934f5bb8 DM |
1030 | let rrd_key = format!("{}/io_ticks", rrd_prefix); |
1031 | rrd_update_derive(&rrd_key, (stat.io_ticks as f64)/1000.0, save); | |
8c03041a DM |
1032 | } |
1033 | } | |
934f5bb8 DM |
1034 | Err(err) => { |
1035 | eprintln!("find_mounted_device failed - {}", err); | |
1036 | } | |
8c03041a | 1037 | } |
8c03041a | 1038 | } |