1 use std
::collections
::BTreeSet
;
3 use std
::io
::{BufRead, BufReader}
;
4 use std
::os
::unix
::io
::AsRawFd
;
5 use std
::path
::{Path, PathBuf}
;
6 use std
::sync
::{Arc, RwLock}
;
7 use std
::thread
::spawn
;
8 use std
::time
::SystemTime
;
10 use anyhow
::{bail, format_err, Error}
;
11 use crossbeam_channel
::{bounded, TryRecvError}
;
13 use proxmox_sys
::fs
::{create_path, CreateOptions}
;
15 use crate::rrd
::{AggregationFn, Archive, DataSourceType, Database}
;
24 /// RRD cache - keep RRD data in RAM, but write updates to disk
26 /// This cache is designed to run as single instance (no concurrent
27 /// access from other processes).
29 config
: Arc
<CacheConfig
>,
30 state
: Arc
<RwLock
<JournalState
>>,
31 rrd_map
: Arc
<RwLock
<RRDMap
>>,
34 pub(crate) struct CacheConfig
{
37 file_options
: CreateOptions
,
38 dir_options
: CreateOptions
,
42 /// Creates a new instance
44 /// `basedir`: All files are stored relative to this path.
46 /// `file_options`: Files are created with this options.
48 /// `dir_options`: Directories are created with this options.
50 /// `apply_interval`: Commit journal after `apply_interval` seconds.
52 /// `load_rrd_cb`; The callback function is used to load RRD files,
53 /// and should return a newly generated RRD if the file does not
54 /// exists (or is unreadable). This may generate RRDs with
55 /// different configurations (dependent on `rel_path`).
56 pub fn new
<P
: AsRef
<Path
>>(
58 file_options
: Option
<CreateOptions
>,
59 dir_options
: Option
<CreateOptions
>,
61 load_rrd_cb
: fn(path
: &Path
, rel_path
: &str, dst
: DataSourceType
) -> Database
,
62 ) -> Result
<Self, Error
> {
63 let basedir
= basedir
.as_ref().to_owned();
65 let file_options
= file_options
.unwrap_or_else(CreateOptions
::new
);
66 let dir_options
= dir_options
.unwrap_or_else(CreateOptions
::new
);
70 Some(dir_options
.clone()),
71 Some(dir_options
.clone()),
73 .map_err(|err
: Error
| format_err
!("unable to create rrdb stat dir - {}", err
))?
;
75 let config
= Arc
::new(CacheConfig
{
82 let state
= JournalState
::new(Arc
::clone(&config
))?
;
83 let rrd_map
= RRDMap
::new(Arc
::clone(&config
), load_rrd_cb
);
86 config
: Arc
::clone(&config
),
87 state
: Arc
::new(RwLock
::new(state
)),
88 rrd_map
: Arc
::new(RwLock
::new(rrd_map
)),
92 /// Create a new RRD as used by the proxmox backup server
94 /// It contains the following RRAs:
96 /// * cf=average,r=60,n=1440 => 1day
97 /// * cf=maximum,r=60,n=1440 => 1day
98 /// * cf=average,r=30*60,n=1440 => 1month
99 /// * cf=maximum,r=30*60,n=1440 => 1month
100 /// * cf=average,r=6*3600,n=1440 => 1year
101 /// * cf=maximum,r=6*3600,n=1440 => 1year
102 /// * cf=average,r=7*86400,n=570 => 10years
103 /// * cf=maximum,r=7*86400,n=570 => 10year
105 /// The resulting data file size is about 80KB.
106 pub fn create_proxmox_backup_default_rrd(dst
: DataSourceType
) -> Database
{
108 // 1 min * 1440 => 1 day
109 Archive
::new(AggregationFn
::Average
, 60, 1440),
110 Archive
::new(AggregationFn
::Maximum
, 60, 1440),
111 // 30 min * 1440 => 30 days ~ 1 month
112 Archive
::new(AggregationFn
::Average
, 30 * 60, 1440),
113 Archive
::new(AggregationFn
::Maximum
, 30 * 60, 1440),
114 // 6 h * 1440 => 360 days ~ 1 year
115 Archive
::new(AggregationFn
::Average
, 6 * 3600, 1440),
116 Archive
::new(AggregationFn
::Maximum
, 6 * 3600, 1440),
117 // 1 week * 570 => 10 years
118 Archive
::new(AggregationFn
::Average
, 7 * 86400, 570),
119 Archive
::new(AggregationFn
::Maximum
, 7 * 86400, 570),
122 Database
::new(dst
, rra_list
)
125 /// Sync the journal data to disk (using `fdatasync` syscall)
126 pub fn sync_journal(&self) -> Result
<(), Error
> {
127 self.state
.read().unwrap().sync_journal()
130 /// Apply and commit the journal. Should be used at server startup.
131 pub fn apply_journal(&self) -> Result
<bool
, Error
> {
132 let config
= Arc
::clone(&self.config
);
133 let state
= Arc
::clone(&self.state
);
134 let rrd_map
= Arc
::clone(&self.rrd_map
);
136 let mut state_guard
= self.state
.write().unwrap();
137 let journal_applied
= state_guard
.journal_applied
;
139 if let Some(ref recv
) = state_guard
.apply_thread_result
{
140 match recv
.try_recv() {
142 // finished without errors, OK
143 state_guard
.apply_thread_result
= None
;
146 // finished with errors, log them
147 log
::error
!("{}", err
);
148 state_guard
.apply_thread_result
= None
;
150 Err(TryRecvError
::Empty
) => {
152 return Ok(journal_applied
);
154 Err(TryRecvError
::Disconnected
) => {
155 // crashed, start again
156 log
::error
!("apply journal thread crashed - try again");
157 state_guard
.apply_thread_result
= None
;
162 let now
= proxmox_time
::epoch_f64();
163 let wants_commit
= (now
- state_guard
.last_journal_flush
) > self.config
.apply_interval
;
165 if journal_applied
&& !wants_commit
{
166 return Ok(journal_applied
);
169 state_guard
.last_journal_flush
= proxmox_time
::epoch_f64();
171 let (sender
, receiver
) = bounded(1);
172 state_guard
.apply_thread_result
= Some(receiver
);
175 let result
= apply_and_commit_journal_thread(config
, state
, rrd_map
, journal_applied
)
176 .map_err(|err
| err
.to_string());
177 sender
.send(result
).unwrap();
183 /// Update data in RAM and write file back to disk (journal)
190 ) -> Result
<(), Error
> {
191 let journal_applied
= self.apply_journal()?
;
196 .append_journal_entry(time
, value
, dst
, rel_path
)?
;
202 .update(rel_path
, time
, value
, dst
, false)?
;
208 /// Extract data from cached RRD
210 /// `start`: Start time. If not specified, we simply extract 10 data points.
212 /// `end`: End time. Default is to use the current time.
213 pub fn extract_cached_data(
221 ) -> Result
<Option
<Entry
>, Error
> {
225 .extract_cached_data(base
, name
, cf
, resolution
, start
, end
)
229 fn apply_and_commit_journal_thread(
230 config
: Arc
<CacheConfig
>,
231 state
: Arc
<RwLock
<JournalState
>>,
232 rrd_map
: Arc
<RwLock
<RRDMap
>>,
234 ) -> Result
<(), Error
> {
236 state
.write().unwrap().rotate_journal()?
; // start new journal, keep old one
238 let start_time
= SystemTime
::now();
239 log
::debug
!("applying rrd journal");
241 match apply_journal_impl(Arc
::clone(&state
), Arc
::clone(&rrd_map
)) {
243 let elapsed
= start_time
.elapsed().unwrap().as_secs_f64();
245 "applied rrd journal ({} entries in {:.3} seconds)",
250 Err(err
) => bail
!("apply rrd journal failed - {}", err
),
254 let start_time
= SystemTime
::now();
255 log
::debug
!("commit rrd journal");
257 match commit_journal_impl(config
, state
, rrd_map
) {
258 Ok(rrd_file_count
) => {
259 let elapsed
= start_time
.elapsed().unwrap().as_secs_f64();
261 "rrd journal successfully committed ({} files in {:.3} seconds)",
266 Err(err
) => bail
!("rrd journal commit failed: {}", err
),
271 fn apply_journal_lines(
272 state
: Arc
<RwLock
<JournalState
>>,
273 rrd_map
: Arc
<RwLock
<RRDMap
>>,
274 journal_name
: &str, // used for logging
275 reader
: &mut BufReader
<File
>,
276 lock_read_line
: bool
,
277 ) -> Result
<usize, Error
> {
282 let mut line
= String
::new();
283 let len
= if lock_read_line
{
284 let _lock
= state
.read().unwrap(); // make sure we read entire lines
285 reader
.read_line(&mut line
)?
287 reader
.read_line(&mut line
)?
294 let entry
: JournalEntry
= match line
.parse() {
298 "unable to parse rrd journal '{}' line {} (skip) - {}",
303 continue; // skip unparseable lines
307 rrd_map
.write().unwrap().update(
318 fn apply_journal_impl(
319 state
: Arc
<RwLock
<JournalState
>>,
320 rrd_map
: Arc
<RwLock
<RRDMap
>>,
321 ) -> Result
<usize, Error
> {
324 // Apply old journals first
325 let journal_list
= state
.read().unwrap().list_old_journals()?
;
327 for entry
in journal_list
{
328 log
::info
!("apply old journal log {}", entry
.name
);
329 let file
= std
::fs
::OpenOptions
::new().read(true).open(&entry
.path
)?
;
330 let mut reader
= BufReader
::new(file
);
331 lines
+= apply_journal_lines(
333 Arc
::clone(&rrd_map
),
340 let mut journal
= state
.read().unwrap().open_journal_reader()?
;
342 lines
+= apply_journal_lines(
344 Arc
::clone(&rrd_map
),
351 let mut state_guard
= state
.write().unwrap(); // block other writers
353 lines
+= apply_journal_lines(
355 Arc
::clone(&rrd_map
),
361 state_guard
.rotate_journal()?
; // start new journal, keep old one
363 // We need to apply the journal only once, because further updates
364 // are always directly applied.
365 state_guard
.journal_applied
= true;
371 fn fsync_file_or_dir(path
: &Path
) -> Result
<(), Error
> {
372 let file
= std
::fs
::File
::open(path
)?
;
373 nix
::unistd
::fsync(file
.as_raw_fd())?
;
377 pub(crate) fn fsync_file_and_parent(path
: &Path
) -> Result
<(), Error
> {
378 let file
= std
::fs
::File
::open(path
)?
;
379 nix
::unistd
::fsync(file
.as_raw_fd())?
;
380 if let Some(parent
) = path
.parent() {
381 fsync_file_or_dir(parent
)?
;
386 fn rrd_parent_dir(basedir
: &Path
, rel_path
: &str) -> PathBuf
{
387 let mut path
= basedir
.to_owned();
388 let rel_path
= Path
::new(rel_path
);
389 if let Some(parent
) = rel_path
.parent() {
395 fn commit_journal_impl(
396 config
: Arc
<CacheConfig
>,
397 state
: Arc
<RwLock
<JournalState
>>,
398 rrd_map
: Arc
<RwLock
<RRDMap
>>,
399 ) -> Result
<usize, Error
> {
400 let files
= rrd_map
.read().unwrap().file_list();
402 let mut rrd_file_count
= 0;
405 let mut dir_set
= BTreeSet
::new();
407 log
::info
!("write rrd data back to disk");
409 // save all RRDs - we only need a read lock here
410 // Note: no fsync here (we do it afterwards)
411 for rel_path
in files
.iter() {
412 let parent_dir
= rrd_parent_dir(&config
.basedir
, rel_path
);
413 dir_set
.insert(parent_dir
);
415 if let Err(err
) = rrd_map
.read().unwrap().flush_rrd_file(rel_path
) {
417 log
::error
!("unable to save rrd {}: {}", rel_path
, err
);
422 bail
!("errors during rrd flush - unable to commit rrd journal");
425 // Important: We fsync files after writing all data! This increase
426 // the likelihood that files are already synced, so this is
427 // much faster (although we need to re-open the files).
429 log
::info
!("starting rrd data sync");
431 for rel_path
in files
.iter() {
432 let mut path
= config
.basedir
.clone();
434 fsync_file_or_dir(&path
)
435 .map_err(|err
| format_err
!("fsync rrd file {} failed - {}", rel_path
, err
))?
;
438 // also fsync directories
439 for dir_path
in dir_set
{
440 fsync_file_or_dir(&dir_path
)
441 .map_err(|err
| format_err
!("fsync rrd dir {:?} failed - {}", dir_path
, err
))?
;
444 // if everything went ok, remove the old journal files
445 state
.write().unwrap().remove_old_journals()?
;