worker_initializer.rs 19.8 KB
Newer Older
1
2
3
4
5
// Worker Initialization Module
// Separates worker lifecycle management from router construction

use crate::config::types::{ConnectionMode as ConfigConnectionMode, RouterConfig, RoutingMode};
use crate::core::{
6
    BasicWorkerBuilder, CircuitBreakerConfig, ConnectionMode, HealthConfig, Worker, WorkerRegistry,
7
8
    WorkerType,
};
9
10
use crate::policies::PolicyRegistry;
use std::collections::HashMap;
11
12
13
14
15
16
17
18
19
20
21
22
23
use std::sync::Arc;
use std::time::Duration;
use tracing::{info, warn};

/// WorkerInitializer handles the creation and registration of workers
/// based on routing configuration, separating this concern from router constructors
pub struct WorkerInitializer;

impl WorkerInitializer {
    /// Initialize workers based on configuration and register them in the WorkerRegistry
    pub async fn initialize_workers(
        config: &RouterConfig,
        worker_registry: &Arc<WorkerRegistry>,
24
        policy_registry: Option<&Arc<PolicyRegistry>>,
25
26
27
28
29
    ) -> Result<(), String> {
        info!("Initializing workers for routing mode: {:?}", config.mode);

        match &config.mode {
            RoutingMode::Regular { worker_urls } => {
30
31
32
                // use router's api_key, repeat for each worker
                let worker_api_keys: Vec<Option<String>> =
                    worker_urls.iter().map(|_| config.api_key.clone()).collect();
33
34
                Self::create_regular_workers(
                    worker_urls,
35
                    &worker_api_keys,
36
37
38
                    &config.connection_mode,
                    config,
                    worker_registry,
39
                    policy_registry,
40
41
42
43
44
45
46
47
                )
                .await?;
            }
            RoutingMode::PrefillDecode {
                prefill_urls,
                decode_urls,
                ..
            } => {
48
49
50
51
52
53
54
                // use router's api_key, repeat for each prefill/decode worker
                let prefill_api_keys: Vec<Option<String>> = prefill_urls
                    .iter()
                    .map(|_| config.api_key.clone())
                    .collect();
                let decode_api_keys: Vec<Option<String>> =
                    decode_urls.iter().map(|_| config.api_key.clone()).collect();
55
56
                Self::create_prefill_workers(
                    prefill_urls,
57
                    &prefill_api_keys,
58
59
60
                    &config.connection_mode,
                    config,
                    worker_registry,
61
                    policy_registry,
62
63
64
65
                )
                .await?;
                Self::create_decode_workers(
                    decode_urls,
66
                    &decode_api_keys,
67
68
69
                    &config.connection_mode,
                    config,
                    worker_registry,
70
                    policy_registry,
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
                )
                .await?;
            }
            RoutingMode::OpenAI { .. } => {
                info!("OpenAI routing mode - no local workers to initialize");
            }
        }

        // Wait for workers to be healthy if any were registered
        if worker_registry.stats().total_workers > 0 {
            Self::wait_for_healthy_workers(
                worker_registry,
                config.worker_startup_timeout_secs,
                config.worker_startup_check_interval_secs,
            )
            .await?;
        }

        Ok(())
    }

    /// Create regular workers for standard routing mode
    async fn create_regular_workers(
        urls: &[String],
95
        api_keys: &[Option<String>],
96
97
98
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
99
        policy_registry: Option<&Arc<PolicyRegistry>>,
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    ) -> Result<(), String> {
        info!("Creating {} regular workers", urls.len());

        // Convert config connection mode to core connection mode
        let connection_mode = Self::convert_connection_mode(config_connection_mode, urls.first());

        // Convert circuit breaker config
        let circuit_breaker_config = config.effective_circuit_breaker_config();
        let core_cb_config = CircuitBreakerConfig {
            failure_threshold: circuit_breaker_config.failure_threshold,
            success_threshold: circuit_breaker_config.success_threshold,
            timeout_duration: Duration::from_secs(circuit_breaker_config.timeout_duration_secs),
            window_duration: Duration::from_secs(circuit_breaker_config.window_duration_secs),
        };

        // Convert health check config
        let health_config = HealthConfig {
            timeout_secs: config.health_check.timeout_secs,
            check_interval_secs: config.health_check.check_interval_secs,
            endpoint: config.health_check.endpoint.clone(),
            failure_threshold: config.health_check.failure_threshold,
            success_threshold: config.health_check.success_threshold,
        };

124
125
        let mut registered_workers: HashMap<String, Vec<Arc<dyn Worker>>> = HashMap::new();

126
        for (url, api_key) in urls.iter().zip(api_keys.iter()) {
127
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
128
            let worker_builder = BasicWorkerBuilder::new(url.clone())
129
130
131
                .worker_type(WorkerType::Regular)
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
132
133
134
135
136
137
                .health_config(health_config.clone());
            let worker = if let Some(api_key) = api_key.clone() {
                worker_builder.api_key(api_key).build()
            } else {
                worker_builder.build()
            };
138

139
140
141
            let worker_arc = Arc::new(worker) as Arc<dyn Worker>;
            let model_id = worker_arc.model_id();
            let worker_id = registry.register(Arc::clone(&worker_arc));
142
            info!("Registered regular worker {} with ID {:?}", url, worker_id);
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

            // Track workers by model for cache-aware policy initialization
            registered_workers
                .entry(model_id.to_string())
                .or_default()
                .push(Arc::clone(&worker_arc));

            // Notify policy registry about the worker
            if let Some(policy_reg) = policy_registry {
                policy_reg.on_worker_added(model_id, None);
            }
        }

        // Initialize cache-aware policies with all workers for each model
        if let Some(policy_reg) = policy_registry {
            for (model_id, workers) in registered_workers {
                policy_reg.init_cache_aware_policy(&model_id, &workers);
            }
161
162
163
164
165
166
167
168
        }

        Ok(())
    }

    /// Create prefill workers for disaggregated routing mode
    async fn create_prefill_workers(
        prefill_entries: &[(String, Option<u16>)],
169
        api_keys: &[Option<String>],
170
171
172
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
173
        policy_registry: Option<&Arc<PolicyRegistry>>,
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
    ) -> Result<(), String> {
        info!("Creating {} prefill workers", prefill_entries.len());

        // Convert config connection mode to core connection mode
        let connection_mode = Self::convert_connection_mode(
            config_connection_mode,
            prefill_entries.first().map(|(url, _)| url),
        );

        // Convert circuit breaker config
        let circuit_breaker_config = config.effective_circuit_breaker_config();
        let core_cb_config = CircuitBreakerConfig {
            failure_threshold: circuit_breaker_config.failure_threshold,
            success_threshold: circuit_breaker_config.success_threshold,
            timeout_duration: Duration::from_secs(circuit_breaker_config.timeout_duration_secs),
            window_duration: Duration::from_secs(circuit_breaker_config.window_duration_secs),
        };

        // Convert health check config
        let health_config = HealthConfig {
            timeout_secs: config.health_check.timeout_secs,
            check_interval_secs: config.health_check.check_interval_secs,
            endpoint: config.health_check.endpoint.clone(),
            failure_threshold: config.health_check.failure_threshold,
            success_threshold: config.health_check.success_threshold,
        };

201
202
        let mut registered_workers: HashMap<String, Vec<Arc<dyn Worker>>> = HashMap::new();

203
        for ((url, bootstrap_port), api_key) in prefill_entries.iter().zip(api_keys.iter()) {
204
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
205
            let worker_builder = BasicWorkerBuilder::new(url.clone())
206
207
208
209
210
                .worker_type(WorkerType::Prefill {
                    bootstrap_port: *bootstrap_port,
                })
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
211
212
213
214
215
216
                .health_config(health_config.clone());
            let worker = if let Some(api_key) = api_key.clone() {
                worker_builder.api_key(api_key).build()
            } else {
                worker_builder.build()
            };
217

218
219
220
            let worker_arc = Arc::new(worker) as Arc<dyn Worker>;
            let model_id = worker_arc.model_id();
            let worker_id = registry.register(Arc::clone(&worker_arc));
221
            info!("Registered prefill worker {} with ID {:?}", url, worker_id);
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

            // Track workers by model for cache-aware policy initialization
            registered_workers
                .entry(model_id.to_string())
                .or_default()
                .push(Arc::clone(&worker_arc));

            // Notify policy registry about the worker
            if let Some(policy_reg) = policy_registry {
                policy_reg.on_worker_added(model_id, None);
            }
        }

        // Initialize cache-aware policies for PD mode
        if let Some(policy_reg) = policy_registry {
            // Collect all prefill workers
            let all_prefill_workers: Vec<Arc<dyn Worker>> = registered_workers
                .values()
                .flat_map(|workers| workers.iter().cloned())
                .collect();

            // Initialize PD policies (will handle both prefill and decode, but we only have prefill here)
            policy_reg.init_pd_cache_aware_policies(&all_prefill_workers, &[]);
245
246
247
248
249
250
251
252
        }

        Ok(())
    }

    /// Create decode workers for disaggregated routing mode
    async fn create_decode_workers(
        urls: &[String],
253
        api_keys: &[Option<String>],
254
255
256
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
257
        policy_registry: Option<&Arc<PolicyRegistry>>,
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    ) -> Result<(), String> {
        info!("Creating {} decode workers", urls.len());

        // Convert config connection mode to core connection mode
        let connection_mode = Self::convert_connection_mode(config_connection_mode, urls.first());

        // Convert circuit breaker config
        let circuit_breaker_config = config.effective_circuit_breaker_config();
        let core_cb_config = CircuitBreakerConfig {
            failure_threshold: circuit_breaker_config.failure_threshold,
            success_threshold: circuit_breaker_config.success_threshold,
            timeout_duration: Duration::from_secs(circuit_breaker_config.timeout_duration_secs),
            window_duration: Duration::from_secs(circuit_breaker_config.window_duration_secs),
        };

        // Convert health check config
        let health_config = HealthConfig {
            timeout_secs: config.health_check.timeout_secs,
            check_interval_secs: config.health_check.check_interval_secs,
            endpoint: config.health_check.endpoint.clone(),
            failure_threshold: config.health_check.failure_threshold,
            success_threshold: config.health_check.success_threshold,
        };

282
283
        let mut registered_workers: HashMap<String, Vec<Arc<dyn Worker>>> = HashMap::new();

284
        for (url, api_key) in urls.iter().zip(api_keys.iter()) {
285
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
286
            let worker_builder = BasicWorkerBuilder::new(url.clone())
287
288
289
                .worker_type(WorkerType::Decode)
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
290
291
292
293
294
295
                .health_config(health_config.clone());
            let worker = if let Some(api_key) = api_key.clone() {
                worker_builder.api_key(api_key).build()
            } else {
                worker_builder.build()
            };
296

297
298
299
            let worker_arc = Arc::new(worker) as Arc<dyn Worker>;
            let model_id = worker_arc.model_id();
            let worker_id = registry.register(Arc::clone(&worker_arc));
300
            info!("Registered decode worker {} with ID {:?}", url, worker_id);
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

            // Track workers by model for cache-aware policy initialization
            registered_workers
                .entry(model_id.to_string())
                .or_default()
                .push(Arc::clone(&worker_arc));

            // Notify policy registry about the worker
            if let Some(policy_reg) = policy_registry {
                policy_reg.on_worker_added(model_id, None);
            }
        }

        // Initialize cache-aware policies for PD mode
        if let Some(policy_reg) = policy_registry {
            // Collect all decode workers
            let all_decode_workers: Vec<Arc<dyn Worker>> = registered_workers
                .values()
                .flat_map(|workers| workers.iter().cloned())
                .collect();

            // Initialize PD policies (will handle both prefill and decode, but we only have decode here)
            policy_reg.init_pd_cache_aware_policies(&[], &all_decode_workers);
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
        }

        Ok(())
    }

    /// Convert config connection mode to core connection mode
    fn convert_connection_mode(
        config_mode: &ConfigConnectionMode,
        _sample_url: Option<&String>,
    ) -> ConnectionMode {
        match config_mode {
            ConfigConnectionMode::Http => ConnectionMode::Http,
            ConfigConnectionMode::Grpc => ConnectionMode::Grpc { port: None },
        }
    }

    /// Wait for workers to become healthy
    async fn wait_for_healthy_workers(
        registry: &Arc<WorkerRegistry>,
        timeout_secs: u64,
        check_interval_secs: u64,
    ) -> Result<(), String> {
        let timeout = Duration::from_secs(timeout_secs);
        let check_interval = Duration::from_secs(check_interval_secs);
        let start_time = std::time::Instant::now();

        info!(
            "Waiting for workers to become healthy (timeout: {}s)",
            timeout_secs
        );

        loop {
            let stats = registry.stats();

            if stats.healthy_workers > 0 {
                info!(
                    "Workers healthy: {}/{} workers are ready",
                    stats.healthy_workers, stats.total_workers
                );

                // If we have at least one healthy worker, we can proceed
                // This allows partial degradation rather than total failure
                return Ok(());
            }

            if start_time.elapsed() > timeout {
                let error_msg = format!(
                    "Timeout waiting for workers to become healthy after {}s. Total workers: {}, Healthy: {}",
                    timeout_secs, stats.total_workers, stats.healthy_workers
                );
                warn!("{}", error_msg);

                // If we have workers but none are healthy, it's still a failure
                if stats.total_workers > 0 {
                    return Err(error_msg);
                } else {
                    // No workers at all might be OK for some configurations
                    warn!("No workers registered, proceeding anyway");
                    return Ok(());
                }
            }

            tokio::time::sleep(check_interval).await;
        }
    }

    /// Initialize workers for gRPC connections specifically
    /// This is used when gRPC clients are pre-connected
    pub async fn initialize_grpc_workers(
        worker_urls: &[String],
        worker_type: WorkerType,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
397
398
        policy_registry: Option<&Arc<PolicyRegistry>>,
        grpc_clients: &mut HashMap<String, crate::grpc::SglangSchedulerClient>,
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
    ) -> Result<(), String> {
        info!(
            "Creating {} gRPC workers of type {:?}",
            worker_urls.len(),
            worker_type
        );

        // Convert circuit breaker config
        let circuit_breaker_config = config.effective_circuit_breaker_config();
        let core_cb_config = CircuitBreakerConfig {
            failure_threshold: circuit_breaker_config.failure_threshold,
            success_threshold: circuit_breaker_config.success_threshold,
            timeout_duration: Duration::from_secs(circuit_breaker_config.timeout_duration_secs),
            window_duration: Duration::from_secs(circuit_breaker_config.window_duration_secs),
        };

        // Convert health check config
        let health_config = HealthConfig {
            timeout_secs: config.health_check.timeout_secs,
            check_interval_secs: config.health_check.check_interval_secs,
            endpoint: config.health_check.endpoint.clone(),
            failure_threshold: config.health_check.failure_threshold,
            success_threshold: config.health_check.success_threshold,
        };

424
425
        let mut registered_workers: HashMap<String, Vec<Arc<dyn Worker>>> = HashMap::new();

426
427
428
429
430
431
432
433
434
435
        for url in worker_urls {
            if let Some(client) = grpc_clients.remove(url) {
                let worker = BasicWorkerBuilder::new(url.clone())
                    .worker_type(worker_type.clone())
                    .connection_mode(ConnectionMode::Grpc { port: None })
                    .circuit_breaker_config(core_cb_config.clone())
                    .health_config(health_config.clone())
                    .grpc_client(client)
                    .build();

436
437
438
                let worker_arc = Arc::new(worker) as Arc<dyn Worker>;
                let model_id = worker_arc.model_id();
                let worker_id = registry.register(Arc::clone(&worker_arc));
439
                info!("Registered gRPC worker {} with ID {:?}", url, worker_id);
440
441
442
443
444
445
446
447
448
449
450

                // Track workers by model for cache-aware policy initialization
                registered_workers
                    .entry(model_id.to_string())
                    .or_default()
                    .push(Arc::clone(&worker_arc));

                // Notify policy registry about the worker
                if let Some(policy_reg) = policy_registry {
                    policy_reg.on_worker_added(model_id, None);
                }
451
452
453
454
455
            } else {
                warn!("No gRPC client available for worker {}, skipping", url);
            }
        }

456
457
458
459
460
461
462
        // Initialize cache-aware policies with all workers for each model
        if let Some(policy_reg) = policy_registry {
            for (model_id, workers) in registered_workers {
                policy_reg.init_cache_aware_policy(&model_id, &workers);
            }
        }

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
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_convert_connection_mode() {
        // HTTP mode
        assert!(matches!(
            WorkerInitializer::convert_connection_mode(
                &ConfigConnectionMode::Http,
                Some(&"http://localhost:8080".to_string())
            ),
            ConnectionMode::Http
        ));

        // gRPC mode
        assert!(matches!(
            WorkerInitializer::convert_connection_mode(
                &ConfigConnectionMode::Grpc,
                Some(&"grpc://localhost:50051".to_string())
            ),
            ConnectionMode::Grpc { .. }
        ));

        // No URL provided
        assert!(matches!(
            WorkerInitializer::convert_connection_mode(&ConfigConnectionMode::Http, None),
            ConnectionMode::Http
        ));
    }
}