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
use std::collections::{BTreeMap, HashMap};
use std::num::NonZeroUsize;
use std::sync::Arc;
use anyhow::anyhow;
use chrono::{DateTime, Utc};
use derivative::Derivative;
use differential_dataflow::lattice::Lattice;
use futures::stream::{BoxStream, StreamExt};
use maplit::hashmap;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use timely::order::TotalOrder;
use timely::progress::frontier::{Antichain, AntichainRef};
use timely::progress::Timestamp;
use tokio::sync::Mutex;
use tokio_stream::StreamMap;
use mz_orchestrator::{
CpuLimit, MemoryLimit, NamespacedOrchestrator, Orchestrator, ServiceConfig, ServiceEvent,
ServicePort,
};
use mz_persist_client::cache::PersistClientCache;
use mz_persist_client::PersistLocation;
use mz_persist_types::Codec64;
use mz_proto::RustType;
use crate::client::{
ComputeClient, ComputeCommand, ComputeInstanceId, ComputeResponse,
ConcreteComputeInstanceReplicaConfig, ControllerResponse, ProcessId, ReplicaId, StorageCommand,
StorageResponse,
};
use crate::client::{ComputeGrpcClient, GenericClient};
use crate::logging::LoggingConfig;
use crate::{TailBatch, TailResponse};
pub use mz_orchestrator::ServiceStatus as ComputeInstanceStatus;
pub use crate::client::controller::compute::{ComputeController, ComputeControllerMut};
pub use crate::client::controller::storage::{StorageController, StorageControllerState};
use super::ActiveReplicationResponse;
mod compute;
pub mod storage;
#[derive(Debug, Clone)]
pub struct ControllerConfig {
pub orchestrator: Arc<dyn Orchestrator>,
pub linger: bool,
pub persist_location: PersistLocation,
pub persist_clients: Arc<Mutex<PersistClientCache>>,
pub storage_stash_url: String,
pub storaged_image: String,
pub computed_image: String,
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct ClusterReplicaSizeConfig {
pub memory_limit: Option<MemoryLimit>,
pub cpu_limit: Option<CpuLimit>,
pub scale: NonZeroUsize,
pub workers: NonZeroUsize,
}
#[derive(Clone, Debug, Deserialize)]
pub struct ClusterReplicaSizeMap(pub HashMap<String, ClusterReplicaSizeConfig>);
impl Default for ClusterReplicaSizeMap {
fn default() -> Self {
let mut inner = (0..=5)
.map(|i| {
let workers = 1 << i;
(
workers.to_string(),
ClusterReplicaSizeConfig {
memory_limit: None,
cpu_limit: None,
scale: NonZeroUsize::new(1).unwrap(),
workers: NonZeroUsize::new(workers).unwrap(),
},
)
})
.collect::<HashMap<_, _>>();
inner.insert(
"2-1".to_string(),
ClusterReplicaSizeConfig {
memory_limit: None,
cpu_limit: None,
scale: NonZeroUsize::new(2).unwrap(),
workers: NonZeroUsize::new(1).unwrap(),
},
);
inner.insert(
"2-2".to_string(),
ClusterReplicaSizeConfig {
memory_limit: None,
cpu_limit: None,
scale: NonZeroUsize::new(2).unwrap(),
workers: NonZeroUsize::new(2).unwrap(),
},
);
inner.insert(
"2-4".to_string(),
ClusterReplicaSizeConfig {
memory_limit: None,
cpu_limit: None,
scale: NonZeroUsize::new(2).unwrap(),
workers: NonZeroUsize::new(4).unwrap(),
},
);
Self(inner)
}
}
fn generate_replica_service_name(instance_id: ComputeInstanceId, replica_id: ReplicaId) -> String {
format!("cluster-{instance_id}-replica-{replica_id}")
}
fn parse_replica_service_name(
service_name: &str,
) -> Result<(ComputeInstanceId, ReplicaId), anyhow::Error> {
static SERVICE_NAME_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?-u)^cluster-(\d+)-replica-(\d+)$").unwrap());
let caps = SERVICE_NAME_RE
.captures(service_name)
.ok_or_else(|| anyhow!("invalid service name: {service_name}"))?;
let instance_id = caps.get(1).unwrap().as_str().parse().unwrap();
let replica_id = caps.get(2).unwrap().as_str().parse().unwrap();
Ok((instance_id, replica_id))
}
#[derive(Debug, Clone, Serialize)]
pub struct ComputeInstanceEvent {
pub instance_id: ComputeInstanceId,
pub replica_id: ReplicaId,
pub process_id: ProcessId,
pub status: ComputeInstanceStatus,
pub time: DateTime<Utc>,
}
enum UnderlyingControllerResponse<T> {
Storage(StorageResponse<T>),
Compute(ComputeInstanceId, ActiveReplicationResponse<T>),
}
pub struct Controller<T = mz_repr::Timestamp> {
linger: bool,
storage_controller: Box<dyn StorageController<Timestamp = T>>,
compute_orchestrator: Arc<dyn NamespacedOrchestrator>,
computed_image: String,
compute: BTreeMap<ComputeInstanceId, compute::ComputeControllerState<T>>,
stashed_response: Option<UnderlyingControllerResponse<T>>,
}
impl<T> Controller<T>
where
T: Timestamp + Lattice + Codec64 + Copy + Unpin,
ComputeCommand<T>: RustType<super::ProtoComputeCommand>,
ComputeResponse<T>: RustType<super::ProtoComputeResponse>,
{
pub async fn create_instance(
&mut self,
instance: ComputeInstanceId,
logging: Option<LoggingConfig>,
) -> Result<(), anyhow::Error> {
self.compute.insert(
instance,
compute::ComputeControllerState::new(&logging).await?,
);
Ok(())
}
pub async fn add_replica_to_instance(
&mut self,
instance_id: ComputeInstanceId,
replica_id: ReplicaId,
config: ConcreteComputeInstanceReplicaConfig,
) -> Result<(), anyhow::Error> {
assert!(
self.compute.contains_key(&instance_id),
"call Controller::create_instance before calling add_replica_to_instance"
);
match config {
ConcreteComputeInstanceReplicaConfig::Remote { replicas } => {
let mut compute_instance = self.compute_mut(instance_id).unwrap();
let client = ComputeGrpcClient::new_partitioned(replicas.into_iter().collect());
let client: Box<dyn ComputeClient<T>> = Box::new(client);
compute_instance.add_replica(replica_id, client);
}
ConcreteComputeInstanceReplicaConfig::Managed {
size_config,
size_name: _,
availability_zone,
} => {
let service_name = generate_replica_service_name(instance_id, replica_id);
let service = self
.compute_orchestrator
.ensure_service(
&service_name,
ServiceConfig {
image: self.computed_image.clone(),
args: &|assigned| {
let mut compute_opts = vec![
format!(
"--listen-addr={}:{}",
assigned.listen_host, assigned.ports["controller"]
),
format!(
"--internal-http-listen-addr={}:{}",
assigned.listen_host, assigned.ports["internal-http"]
),
format!("--workers={}", size_config.workers),
format!("--opentelemetry-resource=instance_id={}", instance_id),
format!("--opentelemetry-resource=replica_id={}", replica_id),
];
compute_opts.extend(
assigned.peers.iter().map(|(host, ports)| {
format!("{host}:{}", ports["compute"])
}),
);
if let Some(index) = assigned.index {
compute_opts.push(format!("--process={index}"));
compute_opts.push(format!(
"--opentelemetry-resource=replica_index={}",
index
));
}
if self.linger {
compute_opts.push(format!("--linger"));
}
compute_opts
},
ports: vec![
ServicePort {
name: "controller".into(),
port_hint: 2100,
},
ServicePort {
name: "compute".into(),
port_hint: 2102,
},
ServicePort {
name: "internal-http".into(),
port_hint: 6875,
},
],
cpu_limit: size_config.cpu_limit,
memory_limit: size_config.memory_limit,
scale: size_config.scale,
labels: hashmap! {
"cluster-id".into() => instance_id.to_string(),
"type".into() => "cluster".into(),
},
availability_zone,
},
)
.await?;
let client = ComputeGrpcClient::new_partitioned(service.addresses("controller"));
let client: Box<dyn ComputeClient<T>> = Box::new(client);
self.compute_mut(instance_id)
.unwrap()
.add_replica(replica_id, client);
}
}
Ok(())
}
pub async fn drop_replica(
&mut self,
instance_id: ComputeInstanceId,
replica_id: ReplicaId,
config: ConcreteComputeInstanceReplicaConfig,
) -> Result<(), anyhow::Error> {
if let ConcreteComputeInstanceReplicaConfig::Managed {
size_config: _,
size_name: _,
availability_zone: _,
} = config
{
let service_name = generate_replica_service_name(instance_id, replica_id);
self.compute_orchestrator
.drop_service(&service_name)
.await?;
}
let mut compute = self.compute_mut(instance_id).unwrap();
compute.remove_replica(replica_id);
Ok(())
}
pub async fn drop_instance(
&mut self,
instance: ComputeInstanceId,
) -> Result<(), anyhow::Error> {
if let Some(mut compute) = self.compute.remove(&instance) {
assert!(
compute.client.get_replica_ids().next().is_none(),
"cannot drop instances with provisioned replicas; call `drop_replica` first"
);
self.compute_orchestrator
.drop_service(&format!("cluster-{instance}"))
.await?;
compute.client.send(ComputeCommand::DropInstance).await?;
}
Ok(())
}
pub fn watch_compute_services(&self) -> BoxStream<'static, ComputeInstanceEvent> {
fn translate_event(event: ServiceEvent) -> Result<ComputeInstanceEvent, anyhow::Error> {
let (instance_id, replica_id) = parse_replica_service_name(&event.service_id)?;
Ok(ComputeInstanceEvent {
instance_id,
replica_id,
process_id: event.process_id,
status: event.status,
time: event.time,
})
}
let stream = self
.compute_orchestrator
.watch_services()
.map(|event| event.and_then(translate_event))
.filter_map(|event| async {
match event {
Ok(event) => Some(event),
Err(error) => {
tracing::error!("service watch error: {error}");
None
}
}
});
Box::pin(stream)
}
}
impl<T> Controller<T> {
#[inline]
pub fn storage(&self) -> &dyn StorageController<Timestamp = T> {
&*self.storage_controller
}
#[inline]
pub fn storage_mut(&mut self) -> &mut dyn StorageController<Timestamp = T> {
&mut *self.storage_controller
}
#[inline]
pub fn compute(&self, instance: ComputeInstanceId) -> Option<ComputeController<T>> {
let compute = self.compute.get(&instance)?;
Some(ComputeController {
instance,
compute,
storage_controller: self.storage(),
})
}
#[inline]
pub fn compute_mut(&mut self, instance: ComputeInstanceId) -> Option<ComputeControllerMut<T>> {
let compute = self.compute.get_mut(&instance)?;
Some(ComputeControllerMut {
instance,
compute,
storage_controller: &mut *self.storage_controller,
})
}
}
impl<T> Controller<T>
where
T: Timestamp + Lattice + Codec64,
{
pub async fn ready(&mut self) -> Result<(), anyhow::Error> {
if self.stashed_response.is_some() {
Ok(())
} else {
let mut compute_stream: StreamMap<_, _> = self
.compute
.iter_mut()
.map(|(id, compute)| (*id, compute.client.as_stream()))
.collect();
loop {
tokio::select! {
Some((instance, response)) = compute_stream.next() => {
let response = response?;
assert!(self.stashed_response.is_none());
self.stashed_response = Some(UnderlyingControllerResponse::Compute(instance, response));
return Ok(());
}
response = self.storage_controller.recv() => {
if let Some(response) = response? {
assert!(self.stashed_response.is_none());
self.stashed_response = Some(UnderlyingControllerResponse::Storage(response));
return Ok(());
}
}
}
}
}
}
pub async fn process(&mut self) -> Result<Option<ControllerResponse<T>>, anyhow::Error> {
let stashed = self.stashed_response.take().expect("`process` is not allowed to block indefinitely -- `ready` should be polled to completion first.");
match stashed {
UnderlyingControllerResponse::Storage(response) => match response {
StorageResponse::FrontierUppers(updates) => {
self.storage_controller
.update_write_frontiers(&updates)
.await?;
Ok(None)
}
StorageResponse::LinearizedTimestamps(res) => {
Ok(Some(ControllerResponse::LinearizedTimestamps(res)))
}
},
UnderlyingControllerResponse::Compute(
instance,
ActiveReplicationResponse::ComputeResponse(response),
) => {
match response {
ComputeResponse::FrontierUppers(updates) => {
self.compute_mut(instance)
.expect("Reference to absent instance")
.update_write_frontiers(&updates)
.await?;
Ok(None)
}
ComputeResponse::PeekResponse(uuid, peek_response, otel_ctx) => {
self.compute_mut(instance)
.expect("Reference to absent instance")
.remove_peeks(std::iter::once(uuid))
.await?;
Ok(Some(ControllerResponse::PeekResponse(
uuid,
peek_response,
otel_ctx,
)))
}
ComputeResponse::TailResponse(global_id, response) => {
let mut changes = timely::progress::ChangeBatch::new();
match &response {
TailResponse::Batch(TailBatch { lower, upper, .. }) => {
changes.extend(upper.iter().map(|time| (time.clone(), 1)));
changes.extend(lower.iter().map(|time| (time.clone(), -1)));
}
TailResponse::DroppedAt(frontier) => {
changes.extend(frontier.iter().map(|time| (time.clone(), -1)));
}
}
self.compute_mut(instance)
.expect("Reference to absent instance")
.update_write_frontiers(&[(global_id, changes)])
.await?;
Ok(Some(ControllerResponse::TailResponse(global_id, response)))
}
}
}
UnderlyingControllerResponse::Compute(
_instance,
ActiveReplicationResponse::ReplicaHeartbeat(replica_id, when),
) => Ok(Some(ControllerResponse::ComputeReplicaHeartbeat(
replica_id, when,
))),
}
}
}
impl<T> Controller<T>
where
T: Timestamp + Lattice + TotalOrder + TryInto<i64> + TryFrom<i64> + Codec64 + Unpin,
<T as TryInto<i64>>::Error: std::fmt::Debug,
<T as TryFrom<i64>>::Error: std::fmt::Debug,
StorageCommand<T>: RustType<super::ProtoStorageCommand>,
StorageResponse<T>: RustType<super::ProtoStorageResponse>,
{
pub async fn new(config: ControllerConfig) -> Self {
let storage_controller = crate::client::controller::storage::Controller::new(
config.storage_stash_url,
config.persist_location,
config.persist_clients,
config.orchestrator.namespace("storage"),
config.storaged_image,
)
.await;
Self {
linger: config.linger,
storage_controller: Box::new(storage_controller),
compute_orchestrator: config.orchestrator.namespace("compute"),
computed_image: config.computed_image,
compute: BTreeMap::default(),
stashed_response: None,
}
}
}
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub enum ReadPolicy<T> {
ValidFrom(Antichain<T>),
LagWriteFrontier(
#[derivative(Debug = "ignore")] Arc<dyn Fn(AntichainRef<T>) -> Antichain<T> + Send + Sync>,
),
Multiple(Vec<ReadPolicy<T>>),
}
impl ReadPolicy<mz_repr::Timestamp> {
pub fn lag_writes_by(lag: mz_repr::Timestamp) -> Self {
Self::LagWriteFrontier(Arc::new(move |upper| {
if upper.is_empty() {
Antichain::from_elem(Timestamp::minimum())
} else {
let mut time = upper[0];
if lag != 0 {
time = time.saturating_sub(lag);
time = time.saturating_sub(time % lag);
}
Antichain::from_elem(time)
}
}))
}
}
impl<T: Timestamp> ReadPolicy<T> {
pub fn frontier(&self, write_frontier: AntichainRef<T>) -> Antichain<T> {
match self {
ReadPolicy::ValidFrom(frontier) => frontier.clone(),
ReadPolicy::LagWriteFrontier(logic) => logic(write_frontier),
ReadPolicy::Multiple(policies) => {
let mut frontier = Antichain::new();
for policy in policies.iter() {
for time in policy.frontier(write_frontier).iter() {
frontier.insert(time.clone());
}
}
frontier
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lag_writes_by_zero() {
let policy = ReadPolicy::lag_writes_by(0);
let write_frontier = Antichain::from_elem(5);
assert_eq!(policy.frontier(write_frontier.borrow()), write_frontier);
}
}