Commit a0deb9f6 authored by Waleed Akbar's avatar Waleed Akbar
Browse files

feat: Implement AI Analytics Engine Skeletion - REST API with Flask

- Added API blueprint for AI Analytics Engine with endpoints for analysis, health check, and configuration.
- Created clients for interacting with SIMAP and InfluxDB services.
- Implemented decision client for sending analysis results.
- Developed configuration module to manage environment settings.
- Established main orchestrator for initializing and running the Flask application.
- Added tests for API endpoints to ensure functionality and validate responses.
- Included deployment script for building and running the AI Analytics Engine in Docker.
parent de9a392d
Loading
Loading
Loading
Loading
+56 −0
Original line number Original line Diff line number Diff line
# Copyright 2022-2025 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

FROM python:3.13-slim

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Copy common requirements and AI engine requirements
COPY common_requirements_py313.in /app/common_requirements.in
COPY src/tests/mwc26-f5ga/AI_analytics_engine/requirements.in /app/ai_requirements.in

# Install Python dependencies
RUN pip install --no-cache-dir pip-tools && \
    pip-compile --output-file=requirements.txt common_requirements.in ai_requirements.in && \
    pip install --no-cache-dir -r requirements.txt

# Copy minimal TFS common module (required for Settings, etc.)
COPY src/common /app/src/common

# Copy AI Analytics Engine module
COPY src/tests/mwc26-f5ga/AI_analytics_engine /app/src/tests/mwc26-f5ga/AI_analytics_engine

# Set PYTHONPATH to include src directory
ENV PYTHONPATH=/app/src

# Expose default REST API port
EXPOSE 8080

# Set default environment variables (can be overridden at runtime)
ENV AI_ENGINE_REST_HOST=0.0.0.0
ENV AI_ENGINE_REST_PORT=8080
ENV SIMAP_SERVER_SCHEME=http
ENV LOG_LEVEL=INFO

# Note: SIMAP_SERVER_ADDRESS, SIMAP_SERVER_PORT, SIMAP_SERVER_USERNAME,
# and SIMAP_SERVER_PASSWORD should be provided at runtime via --env flags

# Run the AI Analytics Engine
CMD ["python", "-m", "tests.mwc26-f5ga.AI_analytics_engine"]
+54 −0
Original line number Original line Diff line number Diff line
# Copyright 2022-2025 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
AI Analytics Engine module.

Provides REST API for AI-driven SLA policy analysis and violation detection
using data from SIMAP (network topology/devices) and InfluxDB (telemetry metrics).

Module Structure:
    - ai_model: AI/ML processing logic and SLA policy definitions
    - api: Flask REST API endpoints
    - clients: External service clients (SIMAP, InfluxDB, Decision Engine)
    - config: Configuration management
    - tests: Test suite

Public API:
    - AIAnalyticsEngineAPI: Main orchestrator and Flask application
    - AIModelProcessor: AI/ML analysis engine
    - SLAPolicyConfig: SLA policy configuration data model
    - SimapDataFetcher: SIMAP client for device/topology data
    - InfluxDBFetcher: InfluxDB client for telemetry metrics
    - DecisionEngineClient: Decision engine notification client
    - create_ai_analytics_blueprint: Flask blueprint factory
"""

from .ai_model.ai_processor import AIModelProcessor
from .api.api_blueprint import create_ai_analytics_blueprint
from .engine import AIAnalyticsEngineAPI
from .clients.decision_client import DecisionEngineClient
from .clients.influxdb_fetcher import InfluxDBFetcher
from .clients.simap_fetcher import SimapDataFetcher
from .ai_model.sla_policy import SLAPolicyConfig

__all__ = [
    'AIAnalyticsEngineAPI',
    'AIModelProcessor',
    'DecisionEngineClient',
    'InfluxDBFetcher',
    'SimapDataFetcher',
    'SLAPolicyConfig',
    'create_ai_analytics_blueprint',
]
+57 −0
Original line number Original line Diff line number Diff line
# Copyright 2022-2025 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
AI Analytics Engine main entry point.

This module provides the entry point for running the AI Analytics Engine REST API.
"""

# Standard library imports
import logging
import sys

# Local imports
from .engine import AIAnalyticsEngineAPI

# Module-level logger
LOGGER = logging.getLogger(__name__)


def main() -> None:
    """Main entry point for the AI Analytics Engine."""
    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG,
        format="[%(asctime)s] %(levelname)s:%(name)s:[%(funcName)s:%(lineno)d] - %(message)s"
    )
    logging.getLogger('werkzeug').setLevel(logging.DEBUG)

    try:
        LOGGER.info("Starting AI Analytics Engine")
        engine = AIAnalyticsEngineAPI()

        logging.getLogger('werkzeug').setLevel(logging.DEBUG)

        engine.run()
    except KeyboardInterrupt:
        LOGGER.info("AI Analytics Engine stopped by user")
        sys.exit(0)
    except Exception as e:
        LOGGER.exception(f"AI Analytics Engine failed to start: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()
+13 −0
Original line number Original line Diff line number Diff line
# Copyright 2022-2025 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+84 −0
Original line number Original line Diff line number Diff line
# Copyright 2022-2025 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
AI Model Processor module.
Provides AI/ML processing functionality for SLA analysis.
"""

import logging
from datetime import datetime, UTC
from random import Random
from typing import Any, Dict

from .sla_policy import SLAPolicyConfig

LOGGER = logging.getLogger(__name__)


class AIModelProcessor:
    """
    Processes data through AI models for SLA analysis.

    This class implements the AI/ML processing logic to analyze device
    and performance data against SLA policies, detecting violations and
    generating recommendations.
    """

    def __init__(self) -> None:
        """
        Initialize the AIModelProcessor.

        Loads AI models and prepares the processor for data analysis.
        """
        LOGGER.info("AIModelProcessor initialized")
        # TODO: Load AI/ML models here
        # Example: self.model = load_model('sla_violation_detector.h5')

    def process_data(
        self,
        device_data: Dict[str, Any],
        performance_data: Dict[str, Any],
        sla_policy: SLAPolicyConfig
    ) -> Dict[str, Any]:
        """
        Process device and performance data through AI models.

        Analyzes the collected data against the SLA policy thresholds,
        detects violations, and generates recommendations for remediation.

        Args:
            device_data: Device and topology data from SIMAP.
            performance_data: Performance metrics from InfluxDB.
            sla_policy: The SLA policy configuration with thresholds.

        Returns:
            Dictionary containing:
                - 'violations': List of detected SLA violations with details.
                - 'recommendations': List of recommended actions.
                - 'summary': Dictionary with analysis summary statistics.
        """
        LOGGER.debug("Processing data through AI models")
        # TODO: Implement actual AI/ML processing logic
        # Example:
        # violations = self.model.predict(features)
        # recommendations = self.generate_recommendations(violations)
        return {
            'violations': [],
            'confidence_scores': round(Random().random(), 2),  
            'summary': {
            'sla_policy': sla_policy.to_dict(),
            'timestamp': datetime.now(UTC).isoformat()
            }
        }
Loading