-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
451 lines (372 loc) Β· 15.4 KB
/
main.py
File metadata and controls
451 lines (372 loc) Β· 15.4 KB
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
#!/usr/bin/env python3
"""
Main entry point for the Webex Contact Center BYOVA Gateway.
This script loads configuration, initializes the virtual agent router,
creates the gRPC server, and starts listening for requests.
"""
import logging
import sys
import threading
from concurrent import futures
from pathlib import Path
from typing import Optional
import grpc
import yaml
# Add src and src/core to Python path for imports
sys.path.insert(0, str(Path(__file__).parent / "src"))
sys.path.insert(0, str(Path(__file__).parent / "src" / "core"))
from grpc_health.v1 import health_pb2_grpc
from auth.jwt_interceptor import JWTAuthInterceptor
# Import JWT authentication components (required)
from auth.jwt_validator import JWTValidator
from core.health_service import HealthCheckService
from core.virtual_agent_router import VirtualAgentRouter
from core.wxcc_gateway_server import WxCCGatewayServer
from monitoring.app import run_web_app
from src.generated.voicevirtualagent_pb2_grpc import (
add_VoiceVirtualAgentServicer_to_server,
)
def setup_logging(config: dict) -> None:
"""
Set up logging configuration.
Args:
config: Configuration dictionary containing logging settings
"""
logging_config = config.get("logging", {})
# Configure gateway logging
gateway_config = logging_config.get("gateway", {})
gateway_log_level = getattr(logging, gateway_config.get("level", "INFO").upper())
gateway_log_format = gateway_config.get(
"format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
gateway_log_file = gateway_config.get("file", "logs/gateway.log")
# Create logs directory if it doesn't exist
if gateway_log_file:
log_path = Path(gateway_log_file)
log_path.parent.mkdir(parents=True, exist_ok=True)
print(f"Gateway log file path: {log_path.absolute()}")
# Clear any existing handlers
logging.getLogger().handlers.clear()
# Configure gateway logging handlers
handlers = [logging.StreamHandler(sys.stdout)]
# Add file handler for gateway logging
if gateway_log_file:
try:
file_handler = logging.FileHandler(gateway_log_file)
file_handler.setFormatter(logging.Formatter(gateway_log_format))
handlers.append(file_handler)
print(f"Gateway logging enabled: {gateway_log_file}")
except Exception as e:
print(f"Warning: Could not create gateway log file {gateway_log_file}: {e}")
# Configure gateway logging
logging.basicConfig(
level=gateway_log_level,
format=gateway_log_format,
handlers=handlers,
force=True, # Force reconfiguration
)
# Test logging
logging.info("Gateway logging system initialized")
print(
f"Gateway logging level set to: {logging.getLevelName(logging.getLogger().level)}"
)
# Configure web logging separately
web_config = logging_config.get("web", {})
web_log_level = getattr(logging, web_config.get("level", "WARNING").upper())
web_log_format = web_config.get(
"format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
web_log_file = web_config.get("file", "logs/web.log")
# Create web log file if specified
if web_log_file:
web_log_path = Path(web_log_file)
web_log_path.parent.mkdir(parents=True, exist_ok=True)
print(f"Web log file path: {web_log_path.absolute()}")
try:
# Configure web-specific loggers
web_logger = logging.getLogger("werkzeug")
web_logger.setLevel(web_log_level)
# Add file handler for web logging
web_file_handler = logging.FileHandler(web_log_file)
web_file_handler.setFormatter(logging.Formatter(web_log_format))
web_logger.addHandler(web_file_handler)
# Also configure Flask logger
flask_logger = logging.getLogger("flask")
flask_logger.setLevel(web_log_level)
flask_logger.addHandler(web_file_handler)
print(f"Web logging enabled: {web_log_file}")
except Exception as e:
print(f"Warning: Could not create web log file {web_log_file}: {e}")
def load_config(config_path: str = "config/config.yaml") -> dict:
"""
Load configuration from YAML file.
Args:
config_path: Path to the configuration file
Returns:
Configuration dictionary
Raises:
FileNotFoundError: If config file doesn't exist
yaml.YAMLError: If config file is invalid
"""
try:
with open(config_path) as file:
config = yaml.safe_load(file)
logging.info(f"Configuration loaded from {config_path}")
return config
except FileNotFoundError:
logging.error(f"Configuration file not found: {config_path}")
raise
except yaml.YAMLError as e:
logging.error(f"Invalid YAML in configuration file: {e}")
raise
def create_router_config(config: dict) -> dict:
"""
Extract router configuration from the main config.
Args:
config: Main configuration dictionary
Returns:
Router configuration dictionary
"""
# The connectors config is already in the correct dictionary format
connectors_config = config.get("connectors", {})
# Ensure each connector has the required fields
for connector_id, connector_config in connectors_config.items():
if not isinstance(connector_config, dict):
raise ValueError(
f"Connector {connector_id} configuration must be a dictionary"
)
# Ensure required fields exist
if "class" not in connector_config:
raise ValueError(f"Connector {connector_id} missing required 'class' field")
if "module" not in connector_config:
raise ValueError(
f"Connector {connector_id} missing required 'module' field"
)
if "config" not in connector_config:
connectors_config[connector_id]["config"] = {}
return {"connectors": connectors_config}
def create_jwt_interceptor(
config: dict, logger: logging.Logger
) -> Optional[JWTAuthInterceptor]:
"""
Create JWT authentication interceptor if configured.
Args:
config: Configuration dictionary containing JWT settings
logger: Logger instance
Returns:
JWTAuthInterceptor instance or None if not configured
Raises:
ValueError: If JWT validation is enabled but datasource_url is not configured
"""
jwt_config = config.get("jwt_validation", {})
if not jwt_config.get("enabled", False):
logger.info("JWT validation is disabled in configuration")
return None
# Validate required configuration
datasource_url = jwt_config.get("datasource_url", "")
if not datasource_url:
error_msg = (
"JWT validation is enabled but datasource_url is not configured. "
"Please set jwt_validation.datasource_url in config.yaml or disable JWT validation."
)
logger.error(error_msg)
raise ValueError(error_msg)
# Get configuration values
datasource_schema_uuid = jwt_config.get(
"datasource_schema_uuid", "5397013b-7920-4ffc-807c-e8a3e0a18f43"
)
cache_duration_minutes = jwt_config.get("cache_duration_minutes", 60)
enforce_validation = jwt_config.get("enforce_validation", True)
try:
# Create JWT validator
validator = JWTValidator(
datasource_url=datasource_url,
datasource_schema_uuid=datasource_schema_uuid,
cache_duration_minutes=cache_duration_minutes,
)
# Create interceptor
interceptor = JWTAuthInterceptor(
jwt_validator=validator,
enabled=True,
enforce=enforce_validation,
)
logger.info("JWT authentication interceptor created successfully")
logger.info(f"Datasource URL: {datasource_url}")
logger.info(
f"Enforcement: {'ENABLED' if enforce_validation else 'DISABLED (logging only)'}"
)
return interceptor
except Exception as e:
logger.error(f"Failed to create JWT interceptor: {e}")
# If JWT validation is enabled, this is a fatal error
jwt_config = config.get("jwt_validation", {})
if jwt_config.get("enabled", True):
error_msg = (
"Failed to create JWT interceptor but JWT validation is enabled. "
"This is a fatal configuration error. Please check your configuration and dependencies."
)
logger.error(error_msg)
raise RuntimeError(error_msg) from e
else:
logger.warning(
"JWT validation is disabled, continuing without JWT interceptor"
)
return None
def main():
"""
Main entry point for the BYOVA Gateway.
This function:
1. Loads configuration from YAML file
2. Sets up logging
3. Creates and configures the VirtualAgentRouter
4. Creates the WxCCGatewayServer
5. Starts the gRPC server
"""
logger = None
server = None
try:
# Load configuration
config_path = "config/config.yaml"
config = load_config(config_path)
# Set up logging
setup_logging(config)
logger = logging.getLogger(__name__)
logger.info("Starting Webex Contact Center BYOVA Gateway")
# Create VirtualAgentRouter
router = VirtualAgentRouter()
logger.info("VirtualAgentRouter created")
# Load connectors
router_config = create_router_config(config)
router.load_connectors(router_config)
logger.info("Connectors loaded successfully")
# Create WxCCGatewayServer
server = WxCCGatewayServer(router)
logger.info("WxCCGatewayServer created")
# Create health service with router for real health monitoring
health_service = HealthCheckService(router)
logger.info("HealthCheckService created with real health monitoring")
# Get server configuration
gateway_config = config.get("gateway", {})
host = gateway_config.get("host", "0.0.0.0")
port = gateway_config.get("port", 50051)
# Create JWT interceptor if configured
jwt_interceptor = create_jwt_interceptor(config, logger)
interceptors = []
if jwt_interceptor:
interceptors.append(jwt_interceptor)
# Create gRPC server with interceptors
if interceptors:
grpc_server = grpc.server(
futures.ThreadPoolExecutor(max_workers=10),
interceptors=interceptors,
options=[
("grpc.max_send_message_length", 50 * 1024 * 1024), # 50MB
("grpc.max_receive_message_length", 50 * 1024 * 1024), # 50MB
("grpc.max_concurrent_streams", 100),
],
)
logger.info(f"gRPC server created with {len(interceptors)} interceptor(s)")
else:
grpc_server = grpc.server(
futures.ThreadPoolExecutor(max_workers=10),
options=[
("grpc.max_send_message_length", 50 * 1024 * 1024), # 50MB
("grpc.max_receive_message_length", 50 * 1024 * 1024), # 50MB
("grpc.max_concurrent_streams", 100),
],
)
logger.info("gRPC server created without interceptors")
# Add servicer to the server
add_VoiceVirtualAgentServicer_to_server(server, grpc_server)
# Add health service to the server
health_pb2_grpc.add_HealthServicer_to_server(health_service, grpc_server)
logger.info("Health service registered with gRPC server")
# Bind server to address
server_address = f"{host}:{port}"
grpc_server.add_insecure_port(server_address)
# Start the server
grpc_server.start()
# Start Flask monitoring app in a separate thread
monitoring_config = config.get("monitoring", {})
if monitoring_config.get("enabled", True): # Enable by default
monitoring_host = monitoring_config.get("host", "0.0.0.0")
monitoring_port = monitoring_config.get("port", 8080)
# Create and start Flask app in a separate thread
flask_thread = threading.Thread(
target=run_web_app,
args=(router, server),
kwargs={
"host": monitoring_host,
"port": monitoring_port,
"debug": monitoring_config.get("debug", False),
},
daemon=True, # Make it a daemon thread so it stops when main thread stops
)
flask_thread.start()
logger.info(
f"Flask monitoring app started on {monitoring_host}:{monitoring_port}"
)
# Print startup information
print("\n" + "=" * 60)
print("π Webex Contact Center BYOVA Gateway")
print("=" * 60)
print(f"π‘ gRPC Server: {server_address}")
print(f"π Access URL: grpc://{host}:{port}")
print(f"π Configuration: {config_path}")
print(f"π Log Level: {gateway_config.get('level', 'INFO')}")
print(f"π§ Gateway Version: {gateway_config.get('version', '1.0.0')}")
print()
# Print connector information
print("π Loaded Connectors:")
router_info = router.get_connector_info()
for connector_name in router_info["loaded_connectors"]:
print(f" β’ {connector_name}")
print()
print("π― Available Agents:")
available_agents = router.get_all_available_agents()
for agent in available_agents:
print(f" β’ {agent}")
print()
print("π Monitoring Interface:")
if monitoring_config.get("enabled", True):
print(f" β’ Web UI: http://{monitoring_host}:{monitoring_port}")
print(f" β’ Status: http://{monitoring_host}:{monitoring_port}/status")
print(f" β’ Health: http://{monitoring_host}:{monitoring_port}/health")
else:
print(" β’ Disabled")
print()
print("π JWT Authentication:")
jwt_config = config.get("jwt_validation", {})
if jwt_config.get("enabled", False) and jwt_interceptor:
print(" β’ Status: ENABLED")
print(
f" β’ Enforcement: {'ENABLED' if jwt_config.get('enforce_validation', True) else 'DISABLED (logging only)'}"
)
print(
f" β’ Datasource URL: {jwt_config.get('datasource_url', 'Not configured')}"
)
else:
print(" β’ Status: DISABLED")
print()
print("β
Gateway is running! Press Ctrl+C to stop.")
print("=" * 60)
# Keep the server running
try:
grpc_server.wait_for_termination()
except KeyboardInterrupt:
logger.info("Received shutdown signal")
finally:
# Graceful shutdown
logger.info("Shutting down gateway...")
if server:
server.shutdown()
grpc_server.stop(grace=5)
logger.info("Gateway shutdown complete")
except Exception as e:
if logger:
logger.error(f"Failed to start gateway: {e}")
else:
print(f"Failed to start gateway: {e}")
sys.exit(1)
if __name__ == "__main__":
main()