-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresource.rs
More file actions
520 lines (480 loc) · 18.7 KB
/
Copy pathresource.rs
File metadata and controls
520 lines (480 loc) · 18.7 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use std::{collections::BTreeMap, sync::LazyLock};
use snafu::{OptionExt, ResultExt, Snafu};
use stackable_operator::{
builder,
builder::pod::{PodBuilder, container::ContainerBuilder, volume::VolumeBuilder},
commons::resources::{
CpuLimitsFragment, MemoryLimits, MemoryLimitsFragment, NoRuntimeLimits,
NoRuntimeLimitsFragment, Resources, ResourcesFragment,
},
k8s_openapi::{
api::core::v1::{EmptyDirVolumeSource, ResourceRequirements},
apimachinery::pkg::api::resource::Quantity,
},
memory::MemoryQuantity,
};
use strum::{EnumDiscriminants, IntoStaticStr};
use crate::crd::{
DruidRole, PATH_SEGMENT_CACHE, PROP_SEGMENT_CACHE_LOCATIONS,
memory::{HistoricalDerivedSettings, RESERVED_OS_MEMORY},
storage::{self, default_free_percentage_empty_dir_fragment},
};
// volume names
const SEGMENT_CACHE_VOLUME_NAME: &str = "segment-cache";
/// This Error cannot derive PartialEq because fragment::ValidationError doesn't derive it
#[derive(Snafu, Debug, EnumDiscriminants)]
#[strum_discriminants(derive(IntoStaticStr))]
#[allow(clippy::enum_variant_names)]
pub enum Error {
#[snafu(display("failed to derive Druid settings from resources"))]
DeriveMemorySettings { source: crate::crd::memory::Error },
#[snafu(display("failed to get memory limits"))]
GetMemoryLimit,
#[snafu(display("failed to parse memory quantity"))]
ParseMemoryQuantity {
source: stackable_operator::memory::Error,
},
#[snafu(display("the operator produced an internally inconsistent state"))]
InconsistentConfiguration,
#[snafu(display("failed to add needed volume"))]
AddVolume { source: builder::pod::Error },
#[snafu(display("failed to add needed volumeMount"))]
AddVolumeMount {
source: builder::pod::container::Error,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum RoleResource {
Druid(Resources<storage::DruidStorage, NoRuntimeLimits>),
Historical(Resources<storage::HistoricalStorage, NoRuntimeLimits>),
}
impl RoleResource {
pub fn as_resource_requirements(&self) -> ResourceRequirements {
match self {
Self::Druid(r) => r.clone().into(),
Self::Historical(r) => r.clone().into(),
}
}
pub fn as_memory_limits(&self) -> MemoryLimits<NoRuntimeLimits> {
match self {
Self::Druid(r) => r.memory.clone(),
Self::Historical(r) => r.memory.clone(),
}
}
/// Update the given configuration file with resource properties.
/// Currently it only adds historical-specific configs for direct memory buffers, thread counts and segment cache.
pub fn update_druid_config_file(
&self,
config: &mut BTreeMap<String, Option<String>>,
) -> Result<(), Error> {
match self {
Self::Historical(r) => {
let free_percentage = r.storage.segment_cache.free_percentage.unwrap_or(5u16);
let capacity = &r.storage.segment_cache.empty_dir.capacity;
config
.entry(PROP_SEGMENT_CACHE_LOCATIONS.to_string())
.or_insert_with(|| {
Some(format!(
r#"[{{"path":"{}","maxSize":"{}","freeSpacePercent":"{}"}}]"#,
PATH_SEGMENT_CACHE, capacity.0, free_percentage
))
});
let settings =
HistoricalDerivedSettings::try_from(r).context(DeriveMemorySettingsSnafu)?;
settings.add_settings(config);
}
Self::Druid(_) => (),
}
Ok(())
}
pub fn update_volumes_and_volume_mounts(
&self,
cb: &mut ContainerBuilder,
pb: &mut PodBuilder,
) -> Result<(), Error> {
if let Self::Historical(r) = self {
cb.add_volume_mount(SEGMENT_CACHE_VOLUME_NAME, PATH_SEGMENT_CACHE)
.context(AddVolumeMountSnafu)?;
pb.add_volume(
VolumeBuilder::new(SEGMENT_CACHE_VOLUME_NAME)
.empty_dir(EmptyDirVolumeSource {
medium: r.storage.segment_cache.empty_dir.medium.clone(),
size_limit: Some(r.storage.segment_cache.empty_dir.capacity.clone()),
})
.build(),
)
.context(AddVolumeSnafu)?;
}
Ok(())
}
/// Computes the heap and direct access memory sizes per role. The settings can be used to configure
/// the JVM accordingly. The direct memory size is an [`Option`] because not all roles require
/// direct access memory.
pub fn get_memory_sizes(
&self,
role: &DruidRole,
) -> Result<(MemoryQuantity, Option<MemoryQuantity>), Error> {
match self {
Self::Historical(r) => {
let settings =
HistoricalDerivedSettings::try_from(r).context(DeriveMemorySettingsSnafu)?;
Ok((
settings.heap_memory(),
Some(settings.direct_access_memory()),
))
}
Self::Druid(r) => {
let total_memory =
MemoryQuantity::try_from(r.memory.limit.as_ref().context(GetMemoryLimitSnafu)?)
.context(ParseMemoryQuantitySnafu)?;
match role {
DruidRole::Historical => Err(Error::InconsistentConfiguration),
DruidRole::Coordinator => {
// The coordinator needs no direct memory
let heap_memory = total_memory - *RESERVED_OS_MEMORY;
Ok((heap_memory, None))
}
DruidRole::Broker => {
let direct_memory = MemoryQuantity::from_mebi(400.);
let heap_memory = total_memory - *RESERVED_OS_MEMORY - direct_memory;
Ok((heap_memory, Some(direct_memory)))
}
DruidRole::MiddleManager => {
// The middle manager needs no direct memory
let heap_memory = total_memory - *RESERVED_OS_MEMORY;
Ok((heap_memory, None))
}
DruidRole::Router => {
let direct_memory = MemoryQuantity::from_mebi(128.);
let heap_memory = total_memory - *RESERVED_OS_MEMORY - direct_memory;
Ok((heap_memory, Some(direct_memory)))
}
}
}
}
}
}
pub static MIDDLE_MANAGER_RESOURCES: LazyLock<
ResourcesFragment<storage::DruidStorage, NoRuntimeLimits>,
> = LazyLock::new(|| ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("300m".to_owned())),
max: Some(Quantity("1200m".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1500Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::DruidStorageFragment {},
});
pub static BROKER_RESOURCES: LazyLock<ResourcesFragment<storage::DruidStorage, NoRuntimeLimits>> =
LazyLock::new(|| ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("300m".to_owned())),
max: Some(Quantity("1200m".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1500Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::DruidStorageFragment {},
});
pub static HISTORICAL_RESOURCES: LazyLock<
ResourcesFragment<storage::HistoricalStorage, NoRuntimeLimits>,
> = LazyLock::new(|| ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("300m".to_owned())),
max: Some(Quantity("1200m".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1500Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::HistoricalStorageFragment {
segment_cache: default_free_percentage_empty_dir_fragment(),
},
});
pub static COORDINATOR_RESOURCES: LazyLock<
ResourcesFragment<storage::DruidStorage, NoRuntimeLimits>,
> = LazyLock::new(|| ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("100m".to_owned())),
max: Some(Quantity("400m".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("768Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::DruidStorageFragment {},
});
pub static ROUTER_RESOURCES: LazyLock<ResourcesFragment<storage::DruidStorage, NoRuntimeLimits>> =
LazyLock::new(|| ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("300m".to_owned())),
max: Some(Quantity("1200m".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("512Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::DruidStorageFragment {},
});
#[cfg(test)]
mod test {
use rstest::*;
use stackable_operator::{
commons::resources::{
CpuLimits, CpuLimitsFragment, MemoryLimits, MemoryLimitsFragment,
NoRuntimeLimitsFragment,
},
k8s_openapi::apimachinery::pkg::api::resource::Quantity,
role_utils::{CommonConfiguration, RoleGroup},
};
use super::*;
use crate::crd::{
MiddleManagerConfig,
storage::{HistoricalStorage, default_free_percentage_empty_dir},
tests::deserialize_yaml_file,
v1alpha1,
};
#[rstest]
#[case(
Some(ResourcesFragment{
cpu: CpuLimitsFragment{
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimitsFragment{
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment{},
},
storage: storage::HistoricalStorageFragment{
segment_cache: default_free_percentage_empty_dir_fragment(),
},
}),
None,
None,
Resources{
cpu: CpuLimits{
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimits{
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimits{},
},
storage: storage::HistoricalStorage{
segment_cache: default_free_percentage_empty_dir(),
},
},
)]
#[case(
Some(ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::HistoricalStorageFragment {
segment_cache: default_free_percentage_empty_dir_fragment(),
},
}),
Some(ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::HistoricalStorageFragment {
segment_cache: default_free_percentage_empty_dir_fragment(),
},
}),
None,
Resources {
cpu: CpuLimits {
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimits {
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimits {},
},
storage: storage::HistoricalStorage {
segment_cache: default_free_percentage_empty_dir(),
},
},
)]
#[case(
Some(ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::HistoricalStorageFragment {
segment_cache: default_free_percentage_empty_dir_fragment(),
},
}),
Some(ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::HistoricalStorageFragment {
segment_cache: default_free_percentage_empty_dir_fragment(),
},
}),
Some(ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: storage::HistoricalStorageFragment {
segment_cache: default_free_percentage_empty_dir_fragment(),
},
}),
Resources {
cpu: CpuLimits {
min: Some(Quantity("200m".to_owned())),
max: Some(Quantity("4".to_owned())),
},
memory: MemoryLimits {
limit: Some(Quantity("2Gi".to_owned())),
runtime_limits: NoRuntimeLimits {},
},
storage: storage::HistoricalStorage {
segment_cache: default_free_percentage_empty_dir(),
},
},
)]
fn test_try_merge_ok(
#[case] first: Option<ResourcesFragment<HistoricalStorage>>,
#[case] second: Option<ResourcesFragment<HistoricalStorage>>,
#[case] third: Option<ResourcesFragment<HistoricalStorage>>,
#[case] expected: Resources<HistoricalStorage>,
) {
let got = v1alpha1::DruidCluster::merged_rolegroup_config(
&first.unwrap_or_default(),
&second.unwrap_or_default(),
&third.unwrap_or_default(),
);
assert_eq!(expected, got.unwrap());
}
#[test]
fn test_resources() -> Result<(), Error> {
let cluster = deserialize_yaml_file::<v1alpha1::DruidCluster>(
"test/resources/crd/resource_merge/druid_cluster.yaml",
);
let config = cluster.merged_config().unwrap();
if let Some(RoleGroup {
config:
CommonConfiguration {
config:
MiddleManagerConfig {
resources: middlemanager_resources_from_rg,
..
},
..
},
..
}) = config.middle_managers.get("resources-from-role-group")
{
let expected = Resources {
cpu: CpuLimits {
min: Some(Quantity("300m".to_owned())),
max: Some(Quantity("3".to_owned())),
},
memory: MemoryLimits {
limit: Some(Quantity("3Gi".to_owned())),
runtime_limits: NoRuntimeLimits {},
},
storage: storage::DruidStorage {},
};
assert_eq!(
middlemanager_resources_from_rg, &expected,
"middlemanager resources from role group"
);
} else {
panic!("No role group named [resources-from-role-group] found");
}
if let Some(RoleGroup {
config:
CommonConfiguration {
config:
MiddleManagerConfig {
resources: middlemanager_resources_from_rg,
..
},
..
},
..
}) = config.middle_managers.get("resources-from-role")
{
let expected = Resources {
cpu: CpuLimits {
min: Some(Quantity("100m".to_owned())),
max: Some(Quantity("1".to_owned())),
},
memory: MemoryLimits {
limit: Some(Quantity("1Gi".to_owned())),
runtime_limits: NoRuntimeLimits {},
},
storage: storage::DruidStorage {},
};
assert_eq!(
middlemanager_resources_from_rg, &expected,
"resources from role"
);
} else {
panic!("No role group named [resources-from-role] found");
}
Ok(())
}
#[test]
fn test_segment_cache() -> Result<(), Error> {
let cluster = deserialize_yaml_file::<v1alpha1::DruidCluster>(
"test/resources/crd/resource_merge/segment_cache.yaml",
);
// ---------- default role group
let config = cluster.merged_config().unwrap();
let res = config
.common_config(&DruidRole::Historical, "default")
.unwrap()
.resources;
let mut got = BTreeMap::new();
assert!(res.update_druid_config_file(&mut got).is_ok());
assert!(got.contains_key(PROP_SEGMENT_CACHE_LOCATIONS));
let value = got.get(PROP_SEGMENT_CACHE_LOCATIONS).unwrap();
let expected = Some(r#"[{"path":"/stackable/var/druid/segment-cache","maxSize":"5g","freeSpacePercent":"3"}]"#.to_string());
assert_eq!(value, &expected, "primary");
// ---------- secondary role group
let res = config
.common_config(&DruidRole::Historical, "secondary")
.unwrap()
.resources;
let mut got = BTreeMap::new();
assert!(res.update_druid_config_file(&mut got).is_ok());
assert!(got.contains_key(PROP_SEGMENT_CACHE_LOCATIONS));
let value = got.get(PROP_SEGMENT_CACHE_LOCATIONS).unwrap();
let expected = Some(r#"[{"path":"/stackable/var/druid/segment-cache","maxSize":"2g","freeSpacePercent":"7"}]"#.to_string());
assert_eq!(value, &expected, "secondary");
Ok(())
}
}