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
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::time::Duration;
use anyhow::anyhow;
use chrono::{DateTime, Utc};
use differential_dataflow::lattice::Lattice;
use futures::stream::{BoxStream, StreamExt, TryStreamExt};
use mz_ore::halt;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use timely::progress::Timestamp;
use tracing::{error, warn};
use mz_cluster_client::client::ClusterReplicaLocation;
use mz_compute_client::controller::{
ComputeInstanceId, ComputeReplicaConfig, ComputeReplicaLogging,
};
use mz_compute_client::logging::LogVariant;
use mz_compute_client::service::{ComputeClient, ComputeGrpcClient};
use mz_orchestrator::{
CpuLimit, LabelSelectionLogic, LabelSelector, MemoryLimit, Service, ServiceConfig,
ServiceEvent, ServicePort,
};
use mz_ore::task::{AbortOnDropHandle, JoinHandleExt};
use mz_repr::GlobalId;
use crate::Controller;
pub use mz_compute_client::controller::DEFAULT_COMPUTE_REPLICA_LOGGING_INTERVAL_MICROS as DEFAULT_REPLICA_LOGGING_INTERVAL_MICROS;
pub type ClusterId = ComputeInstanceId;
pub struct ClusterConfig {
pub arranged_logs: BTreeMap<LogVariant, GlobalId>,
}
pub type ClusterStatus = mz_orchestrator::ServiceStatus;
pub type ReplicaId = mz_compute_client::controller::ReplicaId;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReplicaConfig {
pub location: ReplicaLocation,
pub compute: ComputeReplicaConfig,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReplicaAllocation {
pub memory_limit: Option<MemoryLimit>,
pub cpu_limit: Option<CpuLimit>,
pub scale: u16,
pub workers: usize,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ReplicaLocation {
Unmanaged(UnmanagedReplicaLocation),
Managed(ManagedReplicaLocation),
}
impl ReplicaLocation {
pub fn availability_zone(&self) -> Option<&str> {
match self {
ReplicaLocation::Unmanaged(_) => None,
ReplicaLocation::Managed(m) => Some(&m.availability_zone),
}
}
pub fn num_processes(&self) -> usize {
match self {
ReplicaLocation::Unmanaged(UnmanagedReplicaLocation {
computectl_addrs, ..
}) => computectl_addrs.len(),
ReplicaLocation::Managed(ManagedReplicaLocation { allocation, .. }) => {
allocation.scale.into()
}
}
}
}
pub enum ClusterRole {
SystemCritical,
System,
User,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UnmanagedReplicaLocation {
pub storagectl_addrs: Vec<String>,
pub storage_addrs: Vec<String>,
pub computectl_addrs: Vec<String>,
pub compute_addrs: Vec<String>,
pub workers: usize,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ManagedReplicaLocation {
pub allocation: ReplicaAllocation,
pub size: String,
pub availability_zone: String,
pub az_user_specified: bool,
}
pub type ReplicaLogging = ComputeReplicaLogging;
pub type ProcessId = u64;
#[derive(Debug, Clone, Serialize)]
pub struct ClusterEvent {
pub cluster_id: ClusterId,
pub replica_id: ReplicaId,
pub process_id: ProcessId,
pub status: ClusterStatus,
pub time: DateTime<Utc>,
}
impl<T> Controller<T>
where
T: Timestamp + Lattice,
ComputeGrpcClient: ComputeClient<T>,
{
pub fn create_cluster(
&mut self,
id: ClusterId,
config: ClusterConfig,
) -> Result<(), anyhow::Error> {
self.storage.create_instance(id);
self.compute.create_instance(id, config.arranged_logs)?;
Ok(())
}
pub fn drop_cluster(&mut self, id: ClusterId) {
self.storage.drop_instance(id);
self.compute.drop_instance(id);
}
pub async fn create_replicas(
&mut self,
replicas: Vec<(ClusterId, ReplicaId, ClusterRole, ReplicaConfig)>,
) -> Result<(), anyhow::Error> {
let this = &*self;
let replicas: Vec<_> = futures::stream::iter(replicas)
.map(|(cluster_id, replica_id, role, config)| async move {
match config.location {
ReplicaLocation::Unmanaged(UnmanagedReplicaLocation {
storagectl_addrs,
storage_addrs,
computectl_addrs,
compute_addrs,
workers,
}) => {
let compute_location = ClusterReplicaLocation {
ctl_addrs: computectl_addrs,
dataflow_addrs: compute_addrs,
workers,
};
let storage_location = ClusterReplicaLocation {
ctl_addrs: storagectl_addrs,
dataflow_addrs: storage_addrs,
workers,
};
Ok::<_, anyhow::Error>((
cluster_id,
replica_id,
config.compute,
storage_location,
compute_location,
None,
))
}
ReplicaLocation::Managed(m) => {
let workers = m.allocation.workers;
let (service, metrics_task_join_handle) = this
.provision_replica(cluster_id, replica_id, role, m)
.await?;
let storage_location = ClusterReplicaLocation {
ctl_addrs: service.addresses("storagectl"),
dataflow_addrs: service.addresses("storage"),
workers,
};
let compute_location = ClusterReplicaLocation {
ctl_addrs: service.addresses("computectl"),
dataflow_addrs: service.addresses("compute"),
workers,
};
Ok((
cluster_id,
replica_id,
config.compute,
storage_location,
compute_location,
Some(metrics_task_join_handle),
))
}
}
})
.buffer_unordered(50)
.try_collect()
.await?;
for (
cluster_id,
replica_id,
compute_config,
storage_location,
compute_location,
metrics_task_join_handle,
) in replicas
{
if let Some(jh) = metrics_task_join_handle {
self.metrics_tasks.insert(replica_id, jh);
}
self.storage.connect_replica(cluster_id, storage_location);
self.active_compute().add_replica_to_instance(
cluster_id,
replica_id,
compute_location,
compute_config,
)?;
}
Ok(())
}
pub async fn drop_replica(
&mut self,
cluster_id: ClusterId,
replica_id: ReplicaId,
) -> Result<(), anyhow::Error> {
self.deprovision_replica(cluster_id, replica_id).await?;
self.metrics_tasks.remove(&replica_id);
self.active_compute().drop_replica(cluster_id, replica_id)?;
Ok(())
}
pub async fn remove_orphaned_replicas(
&mut self,
next_replica_id: ReplicaId,
) -> Result<(), anyhow::Error> {
let desired: BTreeSet<_> = self.metrics_tasks.keys().copied().collect();
let actual: BTreeSet<_> = self
.orchestrator
.list_services()
.await?
.iter()
.map(|s| parse_replica_service_name(s))
.collect::<Result<_, _>>()?;
for (cluster_id, replica_id) in actual {
if replica_id >= next_replica_id {
halt!(
"found replica id ({}) in orchestrator >= next id ({})",
replica_id,
next_replica_id
);
}
if !desired.contains(&replica_id) {
self.deprovision_replica(cluster_id, replica_id).await?;
}
}
Ok(())
}
pub fn events_stream(&self) -> BoxStream<'static, ClusterEvent> {
fn translate_event(event: ServiceEvent) -> Result<ClusterEvent, anyhow::Error> {
let (cluster_id, replica_id) = parse_replica_service_name(&event.service_id)?;
Ok(ClusterEvent {
cluster_id,
replica_id,
process_id: event.process_id,
status: event.status,
time: event.time,
})
}
let stream = self
.orchestrator
.watch_services()
.map(|event| event.and_then(translate_event))
.filter_map(|event| async {
match event {
Ok(event) => Some(event),
Err(error) => {
error!("service watch error: {error}");
None
}
}
});
Box::pin(stream)
}
async fn provision_replica(
&self,
cluster_id: ClusterId,
replica_id: ReplicaId,
role: ClusterRole,
location: ManagedReplicaLocation,
) -> Result<(Box<dyn Service>, AbortOnDropHandle<()>), anyhow::Error> {
let service_name = generate_replica_service_name(cluster_id, replica_id);
let role_label = match role {
ClusterRole::SystemCritical => "system-critical",
ClusterRole::System => "system",
ClusterRole::User => "user",
};
let service = self
.orchestrator
.ensure_service(
&service_name,
ServiceConfig {
image: self.clusterd_image.clone(),
init_container_image: self.init_container_image.clone(),
args: &|assigned| {
vec![
format!(
"--storage-controller-listen-addr={}",
assigned["storagectl"]
),
format!(
"--compute-controller-listen-addr={}",
assigned["computectl"]
),
format!("--internal-http-listen-addr={}", assigned["internal-http"]),
format!("--opentelemetry-resource=cluster_id={}", cluster_id),
format!("--opentelemetry-resource=replica_id={}", replica_id),
]
},
ports: vec![
ServicePort {
name: "storagectl".into(),
port_hint: 2100,
},
ServicePort {
name: "storage".into(),
port_hint: 2103,
},
ServicePort {
name: "computectl".into(),
port_hint: 2101,
},
ServicePort {
name: "compute".into(),
port_hint: 2102,
},
ServicePort {
name: "internal-http".into(),
port_hint: 6878,
},
],
cpu_limit: location.allocation.cpu_limit,
memory_limit: location.allocation.memory_limit,
scale: location.allocation.scale,
labels: BTreeMap::from([
("replica-id".into(), replica_id.to_string()),
("cluster-id".into(), cluster_id.to_string()),
("type".into(), "cluster".into()),
("replica-role".into(), role_label.into()),
]),
availability_zone: Some(location.availability_zone),
anti_affinity: Some(vec![
LabelSelector {
label_name: "cluster-id".to_string(),
logic: LabelSelectionLogic::Eq {
value: cluster_id.to_string(),
},
},
LabelSelector {
label_name: "replica-id".into(),
logic: LabelSelectionLogic::NotEq {
value: replica_id.to_string(),
},
},
]),
},
)
.await?;
let metrics_task = mz_ore::task::spawn(|| format!("replica-metrics-{replica_id}"), {
let tx = self.metrics_tx.clone();
let orchestrator = Arc::clone(&self.orchestrator);
let service_name = service_name.clone();
async move {
const METRICS_INTERVAL: Duration = Duration::from_secs(10);
let mut interval = tokio::time::interval(METRICS_INTERVAL);
loop {
interval.tick().await;
match orchestrator.fetch_service_metrics(&service_name).await {
Ok(metrics) => {
let _ = tx.send((replica_id, metrics));
}
Err(e) => {
warn!("failed to get metrics for replica {replica_id}: {e}");
}
}
}
}
});
Ok((service, metrics_task.abort_on_drop()))
}
async fn deprovision_replica(
&mut self,
cluster_id: ClusterId,
replica_id: ReplicaId,
) -> Result<(), anyhow::Error> {
let service_name = generate_replica_service_name(cluster_id, replica_id);
self.orchestrator.drop_service(&service_name).await
}
}
fn generate_replica_service_name(cluster_id: ClusterId, replica_id: ReplicaId) -> String {
format!("{cluster_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)^([us]\d+)-replica-(\d+)$").unwrap());
let caps = SERVICE_NAME_RE
.captures(service_name)
.ok_or_else(|| anyhow!("invalid service name: {service_name}"))?;
let cluster_id = caps.get(1).unwrap().as_str().parse().unwrap();
let replica_id = caps.get(2).unwrap().as_str().parse().unwrap();
Ok((cluster_id, replica_id))
}