forked from tikv/tikv
-
Notifications
You must be signed in to change notification settings - Fork 9
/
setup.rs
341 lines (304 loc) · 11.3 KB
/
setup.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
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::borrow::ToOwned;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use chrono::Local;
use clap::ArgMatches;
use collections::HashMap;
use tikv::config::{check_critical_config, persist_config, MetricConfig, TiKvConfig};
use tikv_util::{self, config, logger};
// A workaround for checking if log is initialized.
pub static LOG_INITIALIZED: AtomicBool = AtomicBool::new(false);
// The info log file names does not end with ".log" since it conflict with rocksdb WAL files.
pub const DEFAULT_ROCKSDB_LOG_FILE: &str = "rocksdb.info";
pub const DEFAULT_RAFTDB_LOG_FILE: &str = "raftdb.info";
#[macro_export]
macro_rules! fatal {
($lvl:expr $(, $arg:expr)*) => ({
if $crate::setup::LOG_INITIALIZED.load(::std::sync::atomic::Ordering::SeqCst) {
crit!($lvl $(, $arg)*);
} else {
eprintln!($lvl $(, $arg)*);
}
slog_global::clear_global();
::std::process::exit(1)
})
}
// TODO: There is a very small chance that duplicate files will be generated if there are
// a lot of logs written in a very short time. Consider rename the rotated file with a version
// number while rotate by size.
//
// The file name format after rotated is as follows: "{original name}.{"%Y-%m-%dT%H-%M-%S%.3f"}"
fn rename_by_timestamp(path: &Path) -> io::Result<PathBuf> {
let mut new_path = path.parent().unwrap().to_path_buf();
let mut new_fname = path.file_stem().unwrap().to_os_string();
let dt = Local::now().format("%Y-%m-%dT%H-%M-%S%.3f");
new_fname.push(format!("-{}", dt));
if let Some(ext) = path.extension() {
new_fname.push(".");
new_fname.push(ext);
};
new_path.push(new_fname);
Ok(new_path)
}
fn make_engine_log_path(path: &str, sub_path: &str, filename: &str) -> String {
let mut path = Path::new(path).to_path_buf();
if !sub_path.is_empty() {
path = path.join(Path::new(sub_path));
}
let path = path.to_str().unwrap_or_else(|| {
fatal!(
"failed to construct engine log dir {:?}, {:?}",
path,
sub_path
);
});
config::ensure_dir_exist(path).unwrap_or_else(|e| {
fatal!("failed to create engine log dir: {}", e);
});
config::canonicalize_log_dir(path, filename).unwrap_or_else(|e| {
fatal!("failed to canonicalize engine log dir {:?}: {}", path, e);
})
}
#[allow(dead_code)]
pub fn initial_logger(config: &TiKvConfig) {
let rocksdb_info_log_path = if !config.rocksdb.info_log_dir.is_empty() {
make_engine_log_path(&config.rocksdb.info_log_dir, "", DEFAULT_ROCKSDB_LOG_FILE)
} else {
// Don't use `DEFAULT_ROCKSDB_SUB_DIR`, because of the logic of `RocksEngine::exists`.
make_engine_log_path(&config.storage.data_dir, "", DEFAULT_ROCKSDB_LOG_FILE)
};
let raftdb_info_log_path = if !config.raftdb.info_log_dir.is_empty() {
make_engine_log_path(&config.raftdb.info_log_dir, "", DEFAULT_RAFTDB_LOG_FILE)
} else {
make_engine_log_path(&config.storage.data_dir, "", DEFAULT_RAFTDB_LOG_FILE)
};
let rocksdb = logger::file_writer(
&rocksdb_info_log_path,
config.log.file.max_size,
config.log.file.max_backups,
config.log.file.max_days,
rename_by_timestamp,
)
.unwrap_or_else(|e| {
fatal!(
"failed to initialize rocksdb log with file {}: {}",
rocksdb_info_log_path,
e
);
});
let raftdb = logger::file_writer(
&raftdb_info_log_path,
config.log.file.max_size,
config.log.file.max_backups,
config.log.file.max_days,
rename_by_timestamp,
)
.unwrap_or_else(|e| {
fatal!(
"failed to initialize raftdb log with file {}: {}",
raftdb_info_log_path,
e
);
});
let slow_log_writer = if config.slow_log_file.is_empty() {
None
} else {
let slow_log_writer = logger::file_writer(
&config.slow_log_file,
config.log.file.max_size,
config.log.file.max_backups,
config.log.file.max_days,
rename_by_timestamp,
)
.unwrap_or_else(|e| {
fatal!(
"failed to initialize slow-log with file {}: {}",
config.slow_log_file,
e
);
});
Some(slow_log_writer)
};
fn build_logger_with_slow_log<N, R, S, T>(
normal: N,
rocksdb: R,
raftdb: T,
slow: Option<S>,
config: &TiKvConfig,
) where
N: slog::Drain<Ok = (), Err = io::Error> + Send + 'static,
R: slog::Drain<Ok = (), Err = io::Error> + Send + 'static,
S: slog::Drain<Ok = (), Err = io::Error> + Send + 'static,
T: slog::Drain<Ok = (), Err = io::Error> + Send + 'static,
{
// Use async drainer and init std log.
let drainer = logger::LogDispatcher::new(normal, rocksdb, raftdb, slow);
let level = config.log.level;
let slow_threshold = config.slow_log_threshold.as_millis();
logger::init_log(drainer, level, true, true, vec![], slow_threshold).unwrap_or_else(|e| {
fatal!("failed to initialize log: {}", e);
});
}
macro_rules! do_build {
($log:expr, $rocksdb:expr, $raftdb:expr, $slow:expr, $enable_timestamp:expr) => {
match config.log.format {
config::LogFormat::Text => build_logger_with_slow_log(
logger::text_format($log, $enable_timestamp),
logger::rocks_text_format($rocksdb, $enable_timestamp),
logger::rocks_text_format($raftdb, $enable_timestamp),
$slow.map(logger::slow_log_text_format),
config,
),
config::LogFormat::Json => build_logger_with_slow_log(
logger::json_format($log, $enable_timestamp),
logger::json_format($rocksdb, $enable_timestamp),
logger::json_format($raftdb, $enable_timestamp),
$slow.map(logger::slow_log_json_format),
config,
),
}
};
}
if config.log.file.filename.is_empty() {
let log = logger::term_writer();
do_build!(
log,
rocksdb,
raftdb,
slow_log_writer,
config.log.enable_timestamp
);
} else {
let log = logger::file_writer(
&config.log.file.filename,
config.log.file.max_size,
config.log.file.max_backups,
config.log.file.max_days,
rename_by_timestamp,
)
.unwrap_or_else(|e| {
fatal!(
"failed to initialize log with file {}: {}",
config.log.file.filename,
e
);
});
do_build!(
log,
rocksdb,
raftdb,
slow_log_writer,
config.log.enable_timestamp
);
}
// Set redact_info_log.
let redact_info_log = config.security.redact_info_log.unwrap_or(false);
log_wrappers::set_redact_info_log(redact_info_log);
LOG_INITIALIZED.store(true, Ordering::SeqCst);
}
#[allow(dead_code)]
pub fn initial_metric(cfg: &MetricConfig) {
tikv_util::metrics::monitor_process()
.unwrap_or_else(|e| fatal!("failed to start process monitor: {}", e));
tikv_util::metrics::monitor_threads("")
.unwrap_or_else(|e| fatal!("failed to start thread monitor: {}", e));
tikv_util::metrics::monitor_allocator_stats("")
.unwrap_or_else(|e| fatal!("failed to monitor allocator stats: {}", e));
if cfg.interval.as_secs() == 0 || cfg.address.is_empty() {
return;
}
warn!("metrics push is not supported any more.");
}
#[allow(dead_code)]
pub fn overwrite_config_with_cmd_args(config: &mut TiKvConfig, matches: &ArgMatches<'_>) {
if let Some(level) = matches.value_of("log-level") {
config.log.level = logger::get_level_by_string(level).unwrap();
config.log_level = slog::Level::Info;
}
if let Some(file) = matches.value_of("log-file") {
config.log.file.filename = file.to_owned();
config.log_file = "".to_owned();
}
if let Some(addr) = matches.value_of("addr") {
config.server.addr = addr.to_owned();
}
if let Some(advertise_addr) = matches.value_of("advertise-addr") {
config.server.advertise_addr = advertise_addr.to_owned();
}
if let Some(status_addr) = matches.value_of("status-addr") {
config.server.status_addr = status_addr.to_owned();
}
if let Some(advertise_status_addr) = matches.value_of("advertise-status-addr") {
config.server.advertise_status_addr = advertise_status_addr.to_owned();
}
if let Some(engine_store_version) = matches.value_of("engine-version") {
config.server.engine_store_version = engine_store_version.to_owned();
}
if let Some(engine_store_git_hash) = matches.value_of("engine-git-hash") {
config.server.engine_store_git_hash = engine_store_git_hash.to_owned();
}
if config.server.engine_addr.is_empty() {
if let Some(engine_addr) = matches.value_of("engine-addr") {
config.server.engine_addr = engine_addr.to_owned();
}
}
if let Some(engine_addr) = matches.value_of("advertise-engine-addr") {
config.server.engine_addr = engine_addr.to_owned();
}
if let Some(data_dir) = matches.value_of("data-dir") {
config.storage.data_dir = data_dir.to_owned();
}
if let Some(endpoints) = matches.values_of("pd-endpoints") {
config.pd.endpoints = endpoints.map(ToOwned::to_owned).collect();
}
if let Some(labels_vec) = matches.values_of("labels") {
let mut labels = HashMap::default();
for label in labels_vec {
let mut parts = label.split('=');
let key = parts.next().unwrap().to_owned();
let value = match parts.next() {
None => fatal!("invalid label: {}", label),
Some(v) => v.to_owned(),
};
if parts.next().is_some() {
fatal!("invalid label: {}", label);
}
labels.insert(key, value);
}
config.server.labels = labels;
}
if let Some(capacity_str) = matches.value_of("capacity") {
let capacity = capacity_str.parse().unwrap_or_else(|e| {
fatal!("invalid capacity: {}", e);
});
config.raft_store.capacity = capacity;
}
if matches.value_of("metrics-addr").is_some() {
warn!("metrics push is not supported any more.");
}
}
#[allow(dead_code)]
pub fn validate_and_persist_config(config: &mut TiKvConfig, persist: bool) {
config.compatible_adjust();
if let Err(e) = config.validate() {
fatal!("invalid configuration: {}", e);
}
if let Err(e) = check_critical_config(config) {
fatal!("critical config check failed: {}", e);
}
if persist {
if let Err(e) = persist_config(config) {
fatal!("persist critical config failed: {}", e);
}
}
}
pub fn ensure_no_unrecognized_config(unrecognized_keys: &[String]) {
if !unrecognized_keys.is_empty() {
fatal!(
"unknown configuration options: {}",
unrecognized_keys.join(", ")
);
}
}