-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.rs
1298 lines (1130 loc) · 41.9 KB
/
app.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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
use crate::config::{Config, StorageType};
use crate::error::WorkerError;
use crate::metric::{
BLOCK_ID_NUMBER, GAUGE_APP_NUMBER, GAUGE_HUGE_PARTITION_NUMBER, GAUGE_PARTITION_NUMBER,
GAUGE_TOPN_APP_RESIDENT_BYTES, PURGE_FAILED_COUNTER, RESIDENT_BYTES, TOTAL_APP_FLUSHED_BYTES,
TOTAL_APP_NUMBER, TOTAL_HUGE_PARTITION_NUMBER, TOTAL_HUGE_PARTITION_REQUIRE_BUFFER_FAILED,
TOTAL_PARTITION_NUMBER, TOTAL_READ_DATA, TOTAL_READ_DATA_FROM_LOCALFILE,
TOTAL_READ_DATA_FROM_MEMORY, TOTAL_READ_INDEX_FROM_LOCALFILE, TOTAL_RECEIVED_DATA,
TOTAL_REQUIRE_BUFFER_FAILED,
};
use crate::readable_size::ReadableSize;
use crate::runtime::manager::RuntimeManager;
use crate::store::hybrid::HybridStore;
use crate::store::{Block, RequireBufferResponse, ResponseData, ResponseDataIndex, Store};
use crate::util::{now_timestamp_as_millis, now_timestamp_as_sec};
use anyhow::{anyhow, Result};
use bytes::Bytes;
use croaring::{JvmLegacy, Treemap};
use dashmap::DashMap;
use log::{debug, error, info, warn};
use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::str::FromStr;
use crate::await_tree::AWAIT_TREE_REGISTRY;
use crate::block_id_manager::{get_block_id_manager, BlockIdManager};
use crate::constant::ALL_LABEL;
use crate::grpc::protobuf::uniffle::{BlockIdLayout, RemoteStorage};
use crate::id_layout::IdLayout;
use crate::storage::HybridStorage;
use crate::store::local::LocalfileStoreStat;
use crate::store::mem::capacity::CapacitySnapshot;
use crate::util;
use await_tree::InstrumentAwait;
use crossbeam::epoch::Atomic;
use once_cell::sync::OnceCell;
use parking_lot::RwLock;
use prometheus::core::Collector;
use prometheus::proto::MetricType::GAUGE;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tracing::Instrument;
pub static SHUFFLE_SERVER_ID: OnceLock<String> = OnceLock::new();
pub static SHUFFLE_SERVER_IP: OnceLock<String> = OnceLock::new();
pub static APP_MANAGER_REF: OnceCell<AppManagerRef> = OnceCell::new();
#[derive(Debug, Clone)]
pub enum DataDistribution {
NORMAL,
#[allow(non_camel_case_types)]
LOCAL_ORDER,
}
pub const MAX_CONCURRENCY_PER_PARTITION_TO_WRITE: i32 = 20;
#[derive(Debug, Clone)]
pub struct AppConfigOptions {
pub data_distribution: DataDistribution,
pub max_concurrency_per_partition_to_write: i32,
pub remote_storage_config_option: Option<RemoteStorageConfig>,
}
impl AppConfigOptions {
pub fn new(
data_distribution: DataDistribution,
max_concurrency_per_partition_to_write: i32,
remote_storage_config_option: Option<RemoteStorageConfig>,
) -> Self {
Self {
data_distribution,
max_concurrency_per_partition_to_write,
remote_storage_config_option,
}
}
}
impl Default for AppConfigOptions {
fn default() -> Self {
AppConfigOptions {
data_distribution: DataDistribution::LOCAL_ORDER,
max_concurrency_per_partition_to_write: 20,
remote_storage_config_option: None,
}
}
}
// =============================================================
#[derive(Clone, Debug)]
pub struct RemoteStorageConfig {
pub root: String,
pub configs: HashMap<String, String>,
}
impl From<RemoteStorage> for RemoteStorageConfig {
fn from(remote_conf: RemoteStorage) -> Self {
let root = remote_conf.path;
let mut confs = HashMap::new();
for kv in remote_conf.remote_storage_conf {
confs.insert(kv.key, kv.value);
}
Self {
root,
configs: confs,
}
}
}
// =============================================================
pub struct App {
app_id: String,
app_config_options: AppConfigOptions,
latest_heartbeat_time: AtomicU64,
store: Arc<HybridStore>,
huge_partition_marked_threshold: Option<u64>,
huge_partition_memory_max_available_size: Option<u64>,
total_received_data_size: AtomicU64,
total_resident_data_size: AtomicU64,
huge_partition_number: AtomicU64,
pub(crate) registry_timestamp: u128,
// key: shuffle_id, val: shuffle's all block_ids bitmap
block_id_manager: Arc<Box<dyn BlockIdManager>>,
// key: (shuffle_id, partition_id)
partition_meta_infos: DashMap<(i32, i32), PartitionedMeta>,
}
#[derive(Clone)]
struct PartitionedMeta {
inner: Arc<RwLock<PartitionedMetaInner>>,
}
struct PartitionedMetaInner {
total_size: u64,
is_huge_partition: bool,
}
impl PartitionedMeta {
fn new() -> Self {
PartitionedMeta {
inner: Arc::new(RwLock::new(PartitionedMetaInner {
total_size: 0,
is_huge_partition: false,
})),
}
}
fn get_size(&self) -> Result<u64> {
let meta = self.inner.read();
Ok(meta.total_size)
}
fn inc_size(&mut self, data_size: i32) -> Result<()> {
let mut meta = self.inner.write();
meta.total_size += data_size as u64;
Ok(())
}
fn is_huge_partition(&self) -> bool {
self.inner.read().is_huge_partition
}
fn mark_as_huge_partition(&mut self) {
let mut meta = self.inner.write();
meta.is_huge_partition = true
}
}
impl App {
fn from(
app_id: String,
config_options: AppConfigOptions,
store: Arc<HybridStore>,
runtime_manager: RuntimeManager,
config: &Config,
) -> Self {
// todo: should throw exception if register failed.
let copy_app_id = app_id.to_string();
let app_options = config_options.clone();
match store.register_app(RegisterAppContext {
app_id: copy_app_id,
app_config_options: app_options,
}) {
Err(error) => {
error!("Errors on registering app to store: {:#?}", error,);
}
_ => {}
}
let huge_partition_marked_threshold =
match &config.app_config.huge_partition_marked_threshold {
Some(v) => Some(
ReadableSize::from_str(v.clone().as_str())
.unwrap()
.as_bytes(),
),
_ => None,
};
let mem_capacity = ReadableSize::from_str(&config.memory_store.clone().unwrap().capacity)
.unwrap()
.as_bytes();
let huge_partition_backpressure_size =
match &config.app_config.huge_partition_memory_limit_percent {
Some(v) => Some(((mem_capacity as f64) * *v) as u64),
_ => None,
};
if huge_partition_backpressure_size.is_some() && huge_partition_marked_threshold.is_some() {
info!(
"Huge partition limitation is enabled for app: {}",
app_id.as_str()
);
}
let block_id_manager = get_block_id_manager(&config.app_config.block_id_manager_type);
info!(
"Using the block id manager: {} for app: {}",
&config.app_config.block_id_manager_type, &app_id
);
App {
app_id,
app_config_options: config_options,
latest_heartbeat_time: AtomicU64::new(now_timestamp_as_sec()),
store,
partition_meta_infos: DashMap::new(),
huge_partition_marked_threshold,
huge_partition_memory_max_available_size: huge_partition_backpressure_size,
total_received_data_size: Default::default(),
total_resident_data_size: Default::default(),
huge_partition_number: Default::default(),
registry_timestamp: now_timestamp_as_millis(),
block_id_manager,
}
}
pub fn reported_block_id_number(&self) -> u64 {
self.block_id_manager.get_blocks_number().unwrap_or(0)
}
pub fn huge_partition_number(&self) -> u64 {
self.huge_partition_number.load(SeqCst)
}
pub fn partition_number(&self) -> usize {
self.partition_meta_infos.len()
}
fn get_latest_heartbeat_time(&self) -> u64 {
self.latest_heartbeat_time.load(SeqCst)
}
pub fn heartbeat(&self) -> Result<()> {
let timestamp = now_timestamp_as_sec();
self.latest_heartbeat_time.store(timestamp, SeqCst);
Ok(())
}
pub fn register_shuffle(&self, shuffle_id: i32) -> Result<()> {
self.heartbeat()?;
Ok(())
}
pub async fn insert(&self, ctx: WritingViewContext) -> Result<i32, WorkerError> {
self.heartbeat()?;
let len: u64 = ctx.data_size;
TOTAL_RECEIVED_DATA.inc_by(len);
// add the partition size into the meta
self.inc_partition_size(&ctx.uid, len)?;
self.total_received_data_size.fetch_add(len, SeqCst);
self.total_resident_data_size.fetch_add(len, SeqCst);
RESIDENT_BYTES.add(len as i64);
self.store.insert(ctx).await?;
Ok(len as i32)
}
pub async fn select(&self, ctx: ReadingViewContext) -> Result<ResponseData, WorkerError> {
self.heartbeat()?;
let response = self.store.get(ctx).await;
response.map(|data| {
match &data {
ResponseData::Local(local_data) => {
let length = local_data.data.len() as u64;
TOTAL_READ_DATA_FROM_LOCALFILE.inc_by(length);
TOTAL_READ_DATA.inc_by(length);
}
ResponseData::Mem(mem_data) => {
let length = mem_data.data.len() as u64;
TOTAL_READ_DATA_FROM_MEMORY.inc_by(length);
TOTAL_READ_DATA.inc_by(length);
}
};
data
})
}
pub async fn list_index(
&self,
ctx: ReadingIndexViewContext,
) -> Result<ResponseDataIndex, WorkerError> {
self.heartbeat()?;
let response = self.store.get_index(ctx).await;
response.map(|data| {
match &data {
ResponseDataIndex::Local(local_data) => {
let len = local_data.index_data.len();
TOTAL_READ_INDEX_FROM_LOCALFILE.inc_by(len as u64);
TOTAL_READ_DATA.inc_by(len as u64);
}
_ => {}
};
data
})
}
pub fn is_huge_partition(&self, uid: &PartitionedUId) -> Result<bool> {
// is configured with the associated huge_partition config options
if self.huge_partition_marked_threshold.is_none() {
return Ok(false);
}
if self.huge_partition_memory_max_available_size.is_none() {
return Ok(false);
}
let huge_partition_threshold = self.huge_partition_marked_threshold.unwrap();
let mut meta = self.get_partition_meta(uid);
if meta.is_huge_partition() {
Ok(true)
} else {
let data_size = meta.get_size()?;
if data_size > huge_partition_threshold {
meta.mark_as_huge_partition();
self.add_huge_partition_metric();
warn!("Partition is marked as huge partition. uid: {:?}", uid);
Ok(true)
} else {
Ok(false)
}
}
}
fn add_huge_partition_metric(&self) {
self.huge_partition_number.fetch_add(1, Ordering::SeqCst);
TOTAL_HUGE_PARTITION_NUMBER.inc();
GAUGE_HUGE_PARTITION_NUMBER
.with_label_values(&[ALL_LABEL])
.inc();
GAUGE_HUGE_PARTITION_NUMBER
.with_label_values(&[self.app_id.as_str()])
.inc();
}
fn sub_huge_partition_metric(&self) {
let number = self.huge_partition_number.load(SeqCst);
if number > 0 {
GAUGE_HUGE_PARTITION_NUMBER
.with_label_values(&vec![ALL_LABEL])
.sub(number as i64);
if let Err(e) = GAUGE_HUGE_PARTITION_NUMBER.remove_label_values(&[&self.app_id]) {
error!(
"Errors on unregistering metric of huge partition number for app:{}. error: {}",
&self.app_id, e
)
}
}
}
pub async fn is_backpressure_for_huge_partition(&self, uid: &PartitionedUId) -> Result<bool> {
if !self.is_huge_partition(uid)? {
return Ok(false);
}
let huge_partition_memory_used = &self.huge_partition_memory_max_available_size;
let huge_partition_memory = *(&huge_partition_memory_used.unwrap());
let memory_used = self.store.get_memory_buffer_size(uid).await?;
if memory_used > huge_partition_memory {
info!(
"[{:?}] with huge partition, it has been limited of writing speed.",
uid
);
TOTAL_HUGE_PARTITION_REQUIRE_BUFFER_FAILED.inc();
Ok(true)
} else {
Ok(false)
}
}
pub fn dec_allocated_from_budget(&self, size: i64) -> Result<bool> {
self.store.release_allocated_from_hot_store(size)
}
pub fn move_allocated_used_from_budget(&self, size: i64) -> Result<bool> {
self.store.move_allocated_to_used_from_hot_store(size)
}
pub async fn require_buffer(
&self,
ctx: RequireBufferContext,
) -> Result<RequireBufferResponse, WorkerError> {
self.heartbeat()?;
if self.is_backpressure_for_huge_partition(&ctx.uid).await? {
TOTAL_REQUIRE_BUFFER_FAILED.inc();
return Err(WorkerError::MEMORY_USAGE_LIMITED_BY_HUGE_PARTITION);
}
self.store.require_buffer(ctx).await.map_err(|err| {
TOTAL_REQUIRE_BUFFER_FAILED.inc();
err
})
}
pub async fn release_ticket(&self, ticket_id: i64) -> Result<i64, WorkerError> {
self.store
.release_ticket(ReleaseTicketContext::from(ticket_id))
.await
}
fn get_partition_meta(&self, uid: &PartitionedUId) -> PartitionedMeta {
let shuffle_id = uid.shuffle_id;
let partition_id = uid.partition_id;
let partitioned_meta = self
.partition_meta_infos
.entry((shuffle_id, partition_id))
.or_insert_with(|| {
TOTAL_PARTITION_NUMBER.inc();
GAUGE_PARTITION_NUMBER.inc();
PartitionedMeta::new()
});
partitioned_meta.clone()
}
pub fn inc_partition_size(&self, uid: &PartitionedUId, size: u64) -> Result<()> {
let mut partitioned_meta = self.get_partition_meta(&uid);
partitioned_meta.inc_size(size as i32)
}
pub async fn get_multi_block_ids(&self, ctx: GetMultiBlockIdsContext) -> Result<Bytes> {
self.heartbeat()?;
self.block_id_manager.get_multi_block_ids(ctx).await
}
pub async fn report_multi_block_ids(&self, ctx: ReportMultiBlockIdsContext) -> Result<()> {
self.heartbeat()?;
let number = self.block_id_manager.report_multi_block_ids(ctx).await?;
BLOCK_ID_NUMBER.add(number as i64);
Ok(())
}
pub async fn purge(&self, reason: &PurgeReason) -> Result<()> {
let (app_id, shuffle_id) = reason.extract();
let removed_size = self.store.purge(&PurgeDataContext::new(reason)).await?;
self.total_resident_data_size
.fetch_sub(removed_size as u64, SeqCst);
RESIDENT_BYTES.sub(removed_size);
if let Some(shuffle_id) = shuffle_id {
// shuffle level bitmap deletion
let purged_number = self.block_id_manager.purge_block_ids(shuffle_id).await?;
BLOCK_ID_NUMBER.sub(purged_number as i64);
let mut deletion_keys = vec![];
let view = self.partition_meta_infos.clone().into_read_only();
for entry in view.iter() {
let key = entry.0;
if shuffle_id == key.0 {
deletion_keys.push(key);
}
}
GAUGE_PARTITION_NUMBER.sub(deletion_keys.len() as i64);
let mut huge_partition_cnt = 0;
for deletion_key in deletion_keys {
if let Some(meta) = self.partition_meta_infos.remove(deletion_key) {
if meta.1.is_huge_partition() {
huge_partition_cnt += 1;
}
}
}
GAUGE_HUGE_PARTITION_NUMBER
.with_label_values(&vec![ALL_LABEL])
.sub(huge_partition_cnt as i64);
} else {
// app level deletion
GAUGE_PARTITION_NUMBER.sub(self.partition_meta_infos.len() as i64);
self.sub_huge_partition_metric();
BLOCK_ID_NUMBER.sub(self.block_id_manager.get_blocks_number()? as i64);
}
Ok(())
}
pub fn total_received_data_size(&self) -> u64 {
self.total_received_data_size.load(SeqCst)
}
pub fn total_resident_data_size(&self) -> u64 {
self.total_resident_data_size.load(SeqCst)
}
}
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum PurgeReason {
SHUFFLE_LEVEL_EXPLICIT_UNREGISTER(String, i32),
APP_LEVEL_EXPLICIT_UNREGISTER(String),
APP_LEVEL_HEARTBEAT_TIMEOUT(String),
}
impl PurgeReason {
pub fn extract(&self) -> (String, Option<i32>) {
match &self {
PurgeReason::SHUFFLE_LEVEL_EXPLICIT_UNREGISTER(x, y) => (x.to_owned(), Some(*y)),
PurgeReason::APP_LEVEL_EXPLICIT_UNREGISTER(x) => (x.to_owned(), None),
PurgeReason::APP_LEVEL_HEARTBEAT_TIMEOUT(x) => (x.to_owned(), None),
}
}
pub fn extract_app_id(&self) -> String {
match &self {
PurgeReason::SHUFFLE_LEVEL_EXPLICIT_UNREGISTER(x, y) => x.to_owned(),
PurgeReason::APP_LEVEL_EXPLICIT_UNREGISTER(x) => x.to_owned(),
PurgeReason::APP_LEVEL_HEARTBEAT_TIMEOUT(x) => x.to_owned(),
}
}
}
#[derive(Debug, Clone)]
pub struct PurgeDataContext {
pub purge_reason: PurgeReason,
}
impl PurgeDataContext {
pub fn new(reason: &PurgeReason) -> PurgeDataContext {
PurgeDataContext {
purge_reason: reason.clone(),
}
}
}
impl Deref for PurgeDataContext {
type Target = PurgeReason;
fn deref(&self) -> &Self::Target {
&self.purge_reason
}
}
#[derive(Debug, Clone)]
pub struct ReportBlocksContext {
pub(crate) uid: PartitionedUId,
pub(crate) blocks: Vec<i64>,
}
#[derive(Debug, Clone)]
pub struct ReportMultiBlockIdsContext {
pub shuffle_id: i32,
pub block_ids: HashMap<i32, Vec<i64>>,
}
impl ReportMultiBlockIdsContext {
pub fn new(shuffle_id: i32, block_ids: HashMap<i32, Vec<i64>>) -> ReportMultiBlockIdsContext {
Self {
shuffle_id,
block_ids,
}
}
}
#[derive(Debug, Clone)]
pub struct GetMultiBlockIdsContext {
pub shuffle_id: i32,
pub partition_ids: Vec<i32>,
pub layout: IdLayout,
}
#[derive(Debug, Clone)]
pub struct GetBlocksContext {
pub(crate) uid: PartitionedUId,
}
#[derive(Debug, Clone)]
pub struct WritingViewContext {
pub uid: PartitionedUId,
pub data_blocks: Vec<Block>,
pub data_size: u64,
}
impl WritingViewContext {
// only for test
pub fn create_for_test(uid: PartitionedUId, data_blocks: Vec<Block>) -> Self {
WritingViewContext {
uid,
data_blocks,
data_size: 0,
}
}
// only for test
pub fn new_with_size(uid: PartitionedUId, data_blocks: Vec<Block>, data_size: u64) -> Self {
WritingViewContext {
uid,
data_blocks,
data_size,
}
}
pub fn new(uid: PartitionedUId, data_blocks: Vec<Block>) -> Self {
let len: u64 = data_blocks.iter().map(|block| block.length).sum::<i32>() as u64;
WritingViewContext {
uid,
data_blocks,
data_size: len,
}
}
}
#[derive(Debug, Clone)]
pub struct ReadingViewContext {
pub uid: PartitionedUId,
pub reading_options: ReadingOptions,
pub serialized_expected_task_ids_bitmap: Option<Treemap>,
}
pub struct ReadingIndexViewContext {
pub partition_id: PartitionedUId,
}
#[derive(Debug, Clone)]
pub struct RequireBufferContext {
pub uid: PartitionedUId,
pub size: i64,
}
#[derive(Debug, Clone)]
pub struct RegisterAppContext {
pub app_id: String,
pub app_config_options: AppConfigOptions,
}
#[derive(Debug, Clone)]
pub struct ReleaseTicketContext {
pub(crate) ticket_id: i64,
}
impl From<i64> for ReleaseTicketContext {
fn from(value: i64) -> Self {
Self { ticket_id: value }
}
}
impl RequireBufferContext {
pub fn new(uid: PartitionedUId, size: i64) -> Self {
Self { uid, size }
}
}
#[derive(Debug, Clone)]
pub enum ReadingOptions {
#[allow(non_camel_case_types)]
MEMORY_LAST_BLOCK_ID_AND_MAX_SIZE(i64, i64),
#[allow(non_camel_case_types)]
FILE_OFFSET_AND_LEN(i64, i64),
}
// ==========================================================
#[derive(Debug, Clone)]
pub struct PurgeEvent {
reason: PurgeReason,
}
pub type AppManagerRef = Arc<AppManager>;
pub struct AppManager {
// key: app_id
pub(crate) apps: DashMap<String, Arc<App>>,
receiver: async_channel::Receiver<PurgeEvent>,
sender: async_channel::Sender<PurgeEvent>,
store: Arc<HybridStore>,
app_heartbeat_timeout_min: u32,
config: Config,
runtime_manager: RuntimeManager,
}
impl AppManager {
fn new(runtime_manager: RuntimeManager, config: Config, storage: &HybridStorage) -> Self {
let (sender, receiver) = async_channel::unbounded();
let app_heartbeat_timeout_min = config.app_config.app_heartbeat_timeout_min;
let manager = AppManager {
apps: DashMap::new(),
receiver,
sender,
store: storage.clone(),
app_heartbeat_timeout_min,
config,
runtime_manager: runtime_manager.clone(),
};
manager
}
}
impl AppManager {
pub fn get_ref(
runtime_manager: RuntimeManager,
config: Config,
storage: &HybridStorage,
) -> AppManagerRef {
let app_ref = Arc::new(AppManager::new(runtime_manager.clone(), config, storage));
let app_manager_ref_cloned = app_ref.clone();
runtime_manager.default_runtime.spawn(async move {
let await_root = AWAIT_TREE_REGISTRY.clone()
.register(format!("App heartbeat periodic checker"))
.await;
await_root.instrument(async move {
info!("Starting app heartbeat checker...");
loop {
// task1: find out heartbeat timeout apps
tokio::time::sleep(Duration::from_secs(10))
.instrument_await("sleeping for 10s...")
.await;
for item in app_manager_ref_cloned.apps.iter() {
let (key, app) = item.pair();
let last_time = app.get_latest_heartbeat_time();
let current = now_timestamp_as_sec();
if current - last_time
> (app_manager_ref_cloned.app_heartbeat_timeout_min * 60) as u64
{
info!("Detected app:{:?} heartbeat timeout. now: {:?}, latest heartbeat: {:?}. timeout threshold: {:?}(min)",
key, current, last_time, app_manager_ref_cloned.app_heartbeat_timeout_min);
if app_manager_ref_cloned
.sender
.send(PurgeEvent {
reason: PurgeReason::APP_LEVEL_HEARTBEAT_TIMEOUT(key.clone()),
})
.await
.is_err()
{
error!(
"Errors on sending purge event when app: {} heartbeat timeout",
key
);
}
}
}
}
}).await;
});
// calculate topN app shuffle data size
let app_manager_ref = app_ref.clone();
runtime_manager.default_runtime.spawn(async move {
let await_root = AWAIT_TREE_REGISTRY
.clone()
.register(format!("App topN periodic statistics"))
.await;
await_root
.instrument(async move {
info!("Starting calculating topN app shuffle data size...");
loop {
tokio::time::sleep(Duration::from_secs(10))
.instrument_await("sleeping for 10s...")
.await;
let view = app_manager_ref.apps.clone().into_read_only();
let mut apps: Vec<_> = view.values().collect();
apps.sort_by_key(|x| 0 - x.total_resident_data_size());
let top_n = 10;
let limit = if apps.len() > top_n {
top_n
} else {
apps.len()
};
for idx in 0..limit {
let app = apps[idx];
if app.total_resident_data_size() <= 0 {
continue;
}
GAUGE_TOPN_APP_RESIDENT_BYTES
.with_label_values(&[&app.app_id])
.set(apps[idx].total_resident_data_size() as i64);
}
}
})
.await;
});
let app_manager_cloned = app_ref.clone();
runtime_manager.default_runtime.spawn(async move {
let await_root = AWAIT_TREE_REGISTRY
.clone()
.register(format!("App periodic purger"))
.await;
await_root
.instrument(async move {
info!("Starting purge event handler...");
while let Ok(event) = app_manager_cloned
.receiver
.recv()
.instrument_await("waiting events coming...")
.await
{
let reason = event.reason;
info!("Purging data with reason: {:?}", &reason);
if let Err(err) = app_manager_cloned.purge_app_data(&reason).await {
PURGE_FAILED_COUNTER.inc();
error!(
"Errors on purging data with reason: {:?}. err: {:?}",
&reason, err
);
}
}
})
.await;
});
app_ref
}
pub fn app_is_exist(&self, app_id: &str) -> bool {
self.apps.contains_key(app_id)
}
pub async fn store_is_healthy(&self) -> Result<bool> {
self.store.is_healthy().await
}
pub async fn store_memory_snapshot(&self) -> Result<CapacitySnapshot> {
self.store.mem_snapshot()
}
pub fn store_localfile_stat(&self) -> Result<LocalfileStoreStat> {
self.store.localfile_stat()
}
pub fn store_memory_spill_event_num(&self) -> Result<u64> {
self.store.get_spill_event_num()
}
async fn purge_app_data(&self, reason: &PurgeReason) -> Result<()> {
let (app_id, shuffle_id_option) = reason.extract();
let app = self.get_app(&app_id).ok_or(anyhow!(format!(
"App:{} don't exist when purging data, this should not happen",
&app_id
)))?;
if shuffle_id_option.is_none() {
self.apps.remove(&app_id);
GAUGE_APP_NUMBER.dec();
let _ = GAUGE_TOPN_APP_RESIDENT_BYTES.remove_label_values(&[&app_id]);
let _ = TOTAL_APP_FLUSHED_BYTES.remove_label_values(&[
app_id.as_str(),
format!("{:?}", StorageType::LOCALFILE).as_str(),
]);
let _ = TOTAL_APP_FLUSHED_BYTES.remove_label_values(&[
app_id.as_str(),
format!("{:?}", StorageType::HDFS).as_str(),
]);
}
app.purge(reason).await?;
Ok(())
}
pub fn get_app(&self, app_id: &str) -> Option<Arc<App>> {
self.apps.get(app_id).map(|v| v.value().clone())
}
pub fn get_alive_app_number(&self) -> usize {
self.apps.len()
}
pub fn register(
&self,
app_id: String,
shuffle_id: i32,
app_config_options: AppConfigOptions,
) -> Result<()> {
info!(
"Accepting registry. app_id: {}, shuffle_id: {}",
app_id.clone(),
shuffle_id
);
let app_ref = self
.apps
.entry(app_id.clone())
.or_insert_with(|| {
TOTAL_APP_NUMBER.inc();
GAUGE_APP_NUMBER.inc();
Arc::new(App::from(
app_id,
app_config_options,
self.store.clone(),
self.runtime_manager.clone(),
&self.config,
))
})
.clone();
app_ref.register_shuffle(shuffle_id)
}
pub async fn unregister_shuffle(&self, app_id: String, shuffle_id: i32) -> Result<()> {
self.sender
.send(PurgeEvent {
reason: PurgeReason::SHUFFLE_LEVEL_EXPLICIT_UNREGISTER(app_id, shuffle_id),
})
.await?;
Ok(())
}
pub async fn unregister_app(&self, app_id: String) -> Result<()> {
self.sender
.send(PurgeEvent {
reason: PurgeReason::APP_LEVEL_EXPLICIT_UNREGISTER(app_id),
})
.await?;
Ok(())
}
pub fn runtime_manager(&self) -> RuntimeManager {
self.runtime_manager.clone()
}
}
#[derive(Ord, PartialOrd, Eq, PartialEq, Default, Debug, Hash, Clone)]
pub struct PartitionedUId {
pub app_id: String,
pub shuffle_id: i32,
pub partition_id: i32,
}
impl PartitionedUId {
pub fn from(app_id: String, shuffle_id: i32, partition_id: i32) -> PartitionedUId {
PartitionedUId {
app_id,
shuffle_id,
partition_id,
}
}
pub fn get_hash(uid: &PartitionedUId) -> u64 {
let mut hasher = DefaultHasher::new();
uid.hash(&mut hasher);
let hash_value = hasher.finish();
hash_value
}
}
#[cfg(test)]
pub(crate) mod test {
use crate::app::{