worker_initializer.rs 18.3 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
30
31
32
33
34
    ) -> Result<(), String> {
        info!("Initializing workers for routing mode: {:?}", config.mode);

        match &config.mode {
            RoutingMode::Regular { worker_urls } => {
                Self::create_regular_workers(
                    worker_urls,
                    &config.connection_mode,
                    config,
                    worker_registry,
35
                    policy_registry,
36
37
38
39
40
41
42
43
44
45
46
47
48
                )
                .await?;
            }
            RoutingMode::PrefillDecode {
                prefill_urls,
                decode_urls,
                ..
            } => {
                Self::create_prefill_workers(
                    prefill_urls,
                    &config.connection_mode,
                    config,
                    worker_registry,
49
                    policy_registry,
50
51
52
53
54
55
56
                )
                .await?;
                Self::create_decode_workers(
                    decode_urls,
                    &config.connection_mode,
                    config,
                    worker_registry,
57
                    policy_registry,
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
                )
                .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],
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
85
        policy_registry: Option<&Arc<PolicyRegistry>>,
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    ) -> 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,
        };

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

112
113
114
115
116
117
118
119
120
        for url in urls {
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
            let worker = BasicWorkerBuilder::new(url.clone())
                .worker_type(WorkerType::Regular)
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
                .health_config(health_config.clone())
                .build();

121
122
123
            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));
124
            info!("Registered regular worker {} with ID {:?}", url, worker_id);
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

            // 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);
            }
143
144
145
146
147
148
149
150
151
152
153
        }

        Ok(())
    }

    /// Create prefill workers for disaggregated routing mode
    async fn create_prefill_workers(
        prefill_entries: &[(String, Option<u16>)],
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
154
        policy_registry: Option<&Arc<PolicyRegistry>>,
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
    ) -> 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,
        };

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

184
185
186
187
188
189
190
191
192
193
194
        for (url, bootstrap_port) in prefill_entries {
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
            let worker = BasicWorkerBuilder::new(url.clone())
                .worker_type(WorkerType::Prefill {
                    bootstrap_port: *bootstrap_port,
                })
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
                .health_config(health_config.clone())
                .build();

195
196
197
            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));
198
            info!("Registered prefill worker {} with ID {:?}", url, worker_id);
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

            // 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, &[]);
222
223
224
225
226
227
228
229
230
231
232
        }

        Ok(())
    }

    /// Create decode workers for disaggregated routing mode
    async fn create_decode_workers(
        urls: &[String],
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
233
        policy_registry: Option<&Arc<PolicyRegistry>>,
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    ) -> 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,
        };

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

260
261
262
263
264
265
266
267
268
        for url in urls {
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
            let worker = BasicWorkerBuilder::new(url.clone())
                .worker_type(WorkerType::Decode)
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
                .health_config(health_config.clone())
                .build();

269
270
271
            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));
272
            info!("Registered decode worker {} with ID {:?}", url, worker_id);
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295

            // 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);
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
        }

        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>,
369
370
        policy_registry: Option<&Arc<PolicyRegistry>>,
        grpc_clients: &mut HashMap<String, crate::grpc::SglangSchedulerClient>,
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
    ) -> 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,
        };

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

398
399
400
401
402
403
404
405
406
407
        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();

408
409
410
                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));
411
                info!("Registered gRPC worker {} with ID {:?}", url, worker_id);
412
413
414
415
416
417
418
419
420
421
422

                // 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);
                }
423
424
425
426
427
            } else {
                warn!("No gRPC client available for worker {}, skipping", url);
            }
        }

428
429
430
431
432
433
434
        // 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);
            }
        }

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
        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
        ));
    }
}