-
Notifications
You must be signed in to change notification settings - Fork 994
/
config.rs
255 lines (222 loc) · 8.42 KB
/
config.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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
//! Ballista configuration
use clap::arg_enum;
use core::fmt;
use std::collections::HashMap;
use std::result;
use std::string::ParseError;
use crate::error::{BallistaError, Result};
use datafusion::arrow::datatypes::DataType;
use log::warn;
pub const BALLISTA_DEFAULT_SHUFFLE_PARTITIONS: &str = "ballista.shuffle.partitions";
pub const BALLISTA_WITH_INFORMATION_SCHEMA: &str = "ballista.with_information_schema";
pub type ParseResult<T> = result::Result<T, String>;
/// Configuration option meta-data
#[derive(Debug, Clone)]
pub struct ConfigEntry {
name: String,
_description: String,
_data_type: DataType,
default_value: Option<String>,
}
impl ConfigEntry {
fn new(
name: String,
_description: String,
_data_type: DataType,
default_value: Option<String>,
) -> Self {
Self {
name,
_description,
_data_type,
default_value,
}
}
}
/// Ballista configuration builder
pub struct BallistaConfigBuilder {
settings: HashMap<String, String>,
}
impl Default for BallistaConfigBuilder {
/// Create a new config builder
fn default() -> Self {
Self {
settings: HashMap::new(),
}
}
}
impl BallistaConfigBuilder {
/// Create a new config with an additional setting
pub fn set(&self, k: &str, v: &str) -> Self {
let mut settings = self.settings.clone();
settings.insert(k.to_owned(), v.to_owned());
Self { settings }
}
pub fn build(&self) -> Result<BallistaConfig> {
BallistaConfig::with_settings(self.settings.clone())
}
}
/// Ballista configuration
#[derive(Debug, Clone)]
pub struct BallistaConfig {
/// Settings stored in map for easy serde
settings: HashMap<String, String>,
}
impl BallistaConfig {
/// Create a default configuration
pub fn new() -> Result<Self> {
Self::with_settings(HashMap::new())
}
/// Create a configuration builder
pub fn builder() -> BallistaConfigBuilder {
BallistaConfigBuilder::default()
}
/// Create a new configuration based on key-value pairs
pub fn with_settings(settings: HashMap<String, String>) -> Result<Self> {
let supported_entries = BallistaConfig::valid_entries();
for (name, entry) in &supported_entries {
if let Some(v) = settings.get(name) {
// validate that we can parse the user-supplied value
let _ = Self::parse_value(v.as_str(), entry._data_type.clone()).map_err(|e| BallistaError::General(format!("Failed to parse user-supplied value '{}' for configuration setting '{}': {}", name, v, e)))?;
} else if let Some(v) = entry.default_value.clone() {
let _ = Self::parse_value(v.as_str(), entry._data_type.clone()).map_err(|e| BallistaError::General(format!("Failed to parse default value '{}' for configuration setting '{}': {}", name, v, e)))?;
} else {
return Err(BallistaError::General(format!(
"No value specified for mandatory configuration setting '{}'",
name
)));
}
}
Ok(Self { settings })
}
pub fn parse_value(val: &str, data_type: DataType) -> ParseResult<()> {
match data_type {
DataType::UInt16 => {
val.to_string()
.parse::<usize>()
.map_err(|e| format!("{:?}", e))?;
}
DataType::Boolean => {
val.to_string()
.parse::<bool>()
.map_err(|e| format!("{:?}", e))?;
}
_ => {
return Err(format!("not support data type: {}", data_type));
}
}
Ok(())
}
/// All available configuration options
pub fn valid_entries() -> HashMap<String, ConfigEntry> {
let entries = vec![
ConfigEntry::new(BALLISTA_DEFAULT_SHUFFLE_PARTITIONS.to_string(),
"Sets the default number of partitions to create when repartitioning query stages".to_string(),
DataType::UInt16, Some("2".to_string())),
ConfigEntry::new(BALLISTA_WITH_INFORMATION_SCHEMA.to_string(),
"Sets whether enable information_schema".to_string(),
DataType::Boolean,Some("false".to_string())),
];
entries
.iter()
.map(|e| (e.name.clone(), e.clone()))
.collect::<HashMap<_, _>>()
}
pub fn settings(&self) -> &HashMap<String, String> {
&self.settings
}
pub fn default_shuffle_partitions(&self) -> usize {
self.get_usize_setting(BALLISTA_DEFAULT_SHUFFLE_PARTITIONS)
}
pub fn default_with_information_schema(&self) -> bool {
self.get_bool_setting(BALLISTA_WITH_INFORMATION_SCHEMA)
}
fn get_usize_setting(&self, key: &str) -> usize {
if let Some(v) = self.settings.get(key) {
// infallible because we validate all configs in the constructor
v.parse().unwrap()
} else {
let entries = Self::valid_entries();
// infallible because we validate all configs in the constructor
let v = entries.get(key).unwrap().default_value.as_ref().unwrap();
v.parse().unwrap()
}
}
fn get_bool_setting(&self, key: &str) -> bool {
if let Some(v) = self.settings.get(key) {
// infallible because we validate all configs in the constructor
v.parse::<bool>().unwrap()
} else {
let entries = Self::valid_entries();
// infallible because we validate all configs in the constructor
let v = entries.get(key).unwrap().default_value.as_ref().unwrap();
v.parse::<bool>().unwrap()
}
}
}
// an enum used to configure the scheduler policy
// needs to be visible to code generated by configure_me
arg_enum! {
#[derive(Clone, Copy, Debug, serde::Deserialize)]
pub enum TaskSchedulingPolicy {
PullStaged,
PushStaged,
}
}
impl parse_arg::ParseArgFromStr for TaskSchedulingPolicy {
fn describe_type<W: fmt::Write>(mut writer: W) -> fmt::Result {
write!(writer, "The scheduler policy for the scheduler")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_config() -> Result<()> {
let config = BallistaConfig::new()?;
assert_eq!(2, config.default_shuffle_partitions());
assert!(!config.default_with_information_schema());
Ok(())
}
#[test]
fn custom_config() -> Result<()> {
let config = BallistaConfig::builder()
.set(BALLISTA_DEFAULT_SHUFFLE_PARTITIONS, "123")
.set(BALLISTA_WITH_INFORMATION_SCHEMA, "true")
.build()?;
assert_eq!(123, config.default_shuffle_partitions());
assert!(config.default_with_information_schema());
Ok(())
}
#[test]
fn custom_config_invalid() -> Result<()> {
let config = BallistaConfig::builder()
.set(BALLISTA_DEFAULT_SHUFFLE_PARTITIONS, "true")
.build();
assert!(config.is_err());
assert_eq!("General(\"Failed to parse user-supplied value 'ballista.shuffle.partitions' for configuration setting 'true': ParseIntError { kind: InvalidDigit }\")", format!("{:?}", config.unwrap_err()));
let config = BallistaConfig::builder()
.set(BALLISTA_WITH_INFORMATION_SCHEMA, "123")
.build();
assert!(config.is_err());
assert_eq!("General(\"Failed to parse user-supplied value 'ballista.with_information_schema' for configuration setting '123': ParseBoolError\")", format!("{:?}", config.unwrap_err()));
Ok(())
}
}