Commit 841413f9 authored by Miguel Ángel Adorna Ruiz's avatar Miguel Ángel Adorna Ruiz
Browse files

format code with ruff

parent 742a91cb
Loading
Loading
Loading
Loading
Loading
−14

File deleted.

−8

File deleted.

−29

File deleted.

+6 −4
Changes for opencapif_sdk/__init__.py: 6 added lines, 4 removed lines.
Original line number Original line Diff line number Diff line
from opencapif_sdk.api_schema_translator import api_schema_translator
from opencapif_sdk.capif_event_feature import capif_invoker_event_feature, capif_provider_event_feature
from opencapif_sdk.capif_invoker_connector import capif_invoker_connector
from opencapif_sdk.capif_invoker_connector import capif_invoker_connector
from opencapif_sdk.capif_logging_feature import capif_logging_feature
from opencapif_sdk.capif_provider_connector import capif_provider_connector
from opencapif_sdk.capif_provider_connector import capif_provider_connector
from opencapif_sdk.service_discoverer import service_discoverer
from opencapif_sdk.service_discoverer import service_discoverer
from opencapif_sdk.api_schema_translator import api_schema_translator
from opencapif_sdk.capif_logging_feature import capif_logging_feature
from opencapif_sdk.capif_event_feature import capif_invoker_event_feature, capif_provider_event_feature


__all__ = ["capif_invoker_connector", "service_discoverer", "capif_provider_connector", "api_schema_translator", "capif_logging_feature", "capif_invoker_event_feature", "capif_provider_event_feature"]
__all__ = ['capif_invoker_connector', 'service_discoverer', 'capif_provider_connector',
 No newline at end of file
          'api_schema_translator', 'capif_logging_feature', 'capif_invoker_event_feature',
          'capif_provider_event_feature']
 No newline at end of file
+73 −72
Changes for opencapif_sdk/api_schema_translator.py: 73 added lines, 72 removed lines.
Original line number Original line Diff line number Diff line
@@ -3,6 +3,7 @@ import logging
import os
import os
import re
import re
import socket
import socket

import yaml
import yaml


log_path = 'logs/builder_logs.log'
log_path = 'logs/builder_logs.log'
@@ -25,7 +26,7 @@ logging.basicConfig(


class api_schema_translator:
class api_schema_translator:


    REQUIRED_COMPONENTS = ["openapi", "info", "servers", "paths", "components"]
    REQUIRED_COMPONENTS = ['openapi', 'info', 'servers', 'paths', 'components']


    def __init__(self, api_path):
    def __init__(self, api_path):
        self.api_path = os.path.abspath(api_path)
        self.api_path = os.path.abspath(api_path)
@@ -51,32 +52,32 @@ class api_schema_translator:
        - Assigns default ports for HTTP (80) and HTTPS (443) if missing.
        - Assigns default ports for HTTP (80) and HTTPS (443) if missing.
        """
        """


        pattern = r"^(https?:\/\/)?([\w\.-]+|\[.*\])(?::(\d+))?(\/[\w\/-]+)?\/([\w-]+)\/(v\d+)$"
        pattern = r'^(https?:\/\/)?([\w\.-]+|\[.*\])(?::(\d+))?(\/[\w\/-]+)?\/([\w-]+)\/(v\d+)$'
        match = re.match(pattern, url)
        match = re.match(pattern, url)


        if not match:
        if not match:
            self.logger.error(f"Invalid URL format: {url}")
            self.logger.error(f'Invalid URL format: {url}')
            return None, None, None, None, None, None, None
            return None, None, None, None, None, None, None


        scheme, host, port, api_root, api_name, api_version = match.groups()
        scheme, host, port, api_root, api_name, api_version = match.groups()


        # Asignar puerto por defecto si no está presente
        # Asignar puerto por defecto si no está presente
        if not port:
        if not port:
            port = 443 if scheme == "https" else 80  # Si no hay esquema, asumimos HTTPS
            port = 443 if scheme == 'https' else 80  # Si no hay esquema, asumimos HTTPS
        else:
        else:
            port = int(port)
            port = int(port)


        if not api_name or not api_version:
        if not api_name or not api_version:
            self.logger.error(f"URL must contain API name and version in the format: <apiRoot>/<apiName>/v<version>")
            self.logger.error('URL must contain API name and version in the format: <apiRoot>/<apiName>/v<version>')
            return None, None, None, None, None, None, None
            return None, None, None, None, None, None, None


        # Si apiRoot está presente, eliminar "/" innecesarios
        # Si apiRoot está presente, eliminar "/" innecesarios
        api_root = api_root.strip('/') if api_root else None
        api_root = api_root.strip('/') if api_root else None


        if re.match(r"^\d{1,3}(\.\d{1,3}){3}$", host):  # IPv4
        if re.match(r'^\d{1,3}(\.\d{1,3}){3}$', host):  # IPv4
            return host, port, None, None, api_root, api_name, api_version
            return host, port, None, None, api_root, api_name, api_version
        elif re.match(r"^\[.*\]$", host):  # IPv6 (brackets format)
        elif re.match(r'^\[.*\]$', host):  # IPv6 (brackets format)
            return None, port, None, host.strip("[]"), api_root, api_name, api_version
            return None, port, None, host.strip('[]'), api_root, api_name, api_version
        else:  # FQDN
        else:  # FQDN
            return None, port, host, None, api_root, api_name, api_version
            return None, port, host, None, api_root, api_name, api_version


@@ -96,40 +97,40 @@ class api_schema_translator:


        # Validamos que al menos una dirección sea válida
        # Validamos que al menos una dirección sea válida
        if not (ip or fqdn or ipv6Addr or api_root):
        if not (ip or fqdn or ipv6Addr or api_root):
            self.logger.error("Invalid URL: No valid IP, IPv6, FQDN, or API root found. Aborting build.")
            self.logger.error('Invalid URL: No valid IP, IPv6, FQDN, or API root found. Aborting build.')
            return
            return


        # Validamos IP y puerto si es IPv4
        # Validamos IP y puerto si es IPv4
        if ip and not self.__validate_ip_port(ip, port):
        if ip and not self.__validate_ip_port(ip, port):
            self.logger.error("Invalid IP or port. Aborting build.")
            self.logger.error('Invalid IP or port. Aborting build.')
            return
            return


        # Construcción de la API
        # Construcción de la API
        try:
        try:
            api_data = {
            api_data = {
                "apiName": api_name,
                'apiName': api_name,
                "aefProfiles": self.__build_aef_profiles(ip, port, api_version, fqdn, ipv6Addr),
                'aefProfiles': self.__build_aef_profiles(ip, port, api_version, fqdn, ipv6Addr),
                "description": self.api_info["info"].get("description", "No description provided"),
                'description': self.api_info['info'].get('description', 'No description provided'),
                "supportedFeatures": supported_features,
                'supportedFeatures': supported_features,
                "shareableInfo": {
                'shareableInfo': {
                    "isShareable": True,
                    'isShareable': True,
                    "capifProvDoms": ["string"]
                    'capifProvDoms': ['string']
                },
                },
                "serviceAPICategory": "string",
                'serviceAPICategory': 'string',
                "apiSuppFeats": api_supp_features,
                'apiSuppFeats': api_supp_features,
                "pubApiPath": {
                'pubApiPath': {
                    "ccfIds": ["string"]
                    'ccfIds': ['string']
                },
                },
                "ccfId": "string"
                'ccfId': 'string'
            }
            }


            # Guardamos los datos en un archivo JSON
            # Guardamos los datos en un archivo JSON
            with open(f"{api_name}.json", "w") as outfile:
            with open(f'{api_name}.json', 'w') as outfile:
                json.dump(api_data, outfile, indent=4)
                json.dump(api_data, outfile, indent=4)
            self.logger.info(f"API description saved to {api_name}.json")
            self.logger.info(f'API description saved to {api_name}.json')


        except Exception as e:
        except Exception as e:
            self.logger.error(f"An error occurred during the build process: {e}")
            self.logger.error(f'An error occurred during the build process: {e}')


    def __load_api_file(self, api_file: str):
    def __load_api_file(self, api_file: str):
        """Loads the Swagger API configuration file and converts YAML to JSON format if necessary."""
        """Loads the Swagger API configuration file and converts YAML to JSON format if necessary."""
@@ -142,15 +143,15 @@ class api_schema_translator:
                    return json.load(file)
                    return json.load(file)
                else:
                else:
                    self.logger.warning(
                    self.logger.warning(
                        f"Unsupported file extension for {api_file}. Only .yaml, .yml, and .json are supported.")
                        f'Unsupported file extension for {api_file}. Only .yaml, .yml, and .json are supported.')
                    return {}
                    return {}
        except FileNotFoundError:
        except FileNotFoundError:
            self.logger.warning(
            self.logger.warning(
                f"Configuration file {api_file} not found. Using defaults or environment variables.")
                f'Configuration file {api_file} not found. Using defaults or environment variables.')
            return {}
            return {}
        except (json.JSONDecodeError, yaml.YAMLError) as e:
        except (json.JSONDecodeError, yaml.YAMLError) as e:
            self.logger.error(
            self.logger.error(
                f"Error parsing the configuration file {api_file}: {e}")
                f'Error parsing the configuration file {api_file}: {e}')
            return {}
            return {}


    def __validate_api_info(self):
    def __validate_api_info(self):
@@ -159,100 +160,100 @@ class api_schema_translator:
        if missing_components:
        if missing_components:
            self.logger.warning(f"Missing components in API specification: {', '.join(missing_components)}")
            self.logger.warning(f"Missing components in API specification: {', '.join(missing_components)}")
        else:
        else:
            self.logger.info("All required components are present in the API specification.")
            self.logger.info('All required components are present in the API specification.')


    def __build_aef_profiles(self, ip, port, api_version, fqdn=None, ipv6Addr=None, ):
    def __build_aef_profiles(self, ip, port, api_version, fqdn=None, ipv6Addr=None, ):
        """Builds the aefProfiles section based on the paths and components in the API info."""
        """Builds the aefProfiles section based on the paths and components in the API info."""
        aef_profiles = []
        aef_profiles = []


        resources = []
        resources = []
        for path, methods in self.api_info.get("paths", {}).items():
        for path, methods in self.api_info.get('paths', {}).items():
            for method, details in methods.items():
            for method, details in methods.items():
                resource = {
                resource = {
                    "resourceName": details.get("summary", "Unnamed Resource"),
                    'resourceName': details.get('summary', 'Unnamed Resource'),
                    "commType": "REQUEST_RESPONSE",
                    'commType': 'REQUEST_RESPONSE',
                    "uri": path,
                    'uri': path,
                    "custOpName": f"http_{method}",
                    'custOpName': f'http_{method}',
                    "operations": [method.upper()],
                    'operations': [method.upper()],
                    "description": details.get("description", "")
                    'description': details.get('description', '')
                }
                }
                resources.append(resource)
                resources.append(resource)


        # Create interface description based on the standard
        # Create interface description based on the standard
        interface_description = {
        interface_description = {
            "port": port,
            'port': port,
            "securityMethods": ["OAUTH"]
            'securityMethods': ['OAUTH']
        }
        }
        # Include ipv4Addr, ipv6Addr, or fqdn as per the standard
        # Include ipv4Addr, ipv6Addr, or fqdn as per the standard
        if ip:
        if ip:
            interface_description["ipv4Addr"] = ip
            interface_description['ipv4Addr'] = ip
        elif ipv6Addr:
        elif ipv6Addr:
            interface_description["ipv6Addr"] = ipv6Addr
            interface_description['ipv6Addr'] = ipv6Addr
        elif fqdn:
        elif fqdn:
            interface_description["fqdn"] = fqdn
            interface_description['fqdn'] = fqdn
        else:
        else:
            raise ValueError("At least one of ipv4Addr, ipv6Addr, or fqdn must be provided.")
            raise ValueError('At least one of ipv4Addr, ipv6Addr, or fqdn must be provided.')


        # Example profile creation based on paths, customize as needed
        # Example profile creation based on paths, customize as needed
        aef_profile = {
        aef_profile = {
            "aefId": "",  # Placeholder AEF ID
            'aefId': '',  # Placeholder AEF ID
            "versions": [
            'versions': [
                {
                {
                    "apiVersion": f"{api_version}",
                    'apiVersion': f'{api_version}',
                    "expiry": "2100-11-30T10:32:02.004Z",
                    'expiry': '2100-11-30T10:32:02.004Z',
                    "resources": resources,
                    'resources': resources,
                    "custOperations": [
                    'custOperations': [
                        {
                        {
                            "commType": "REQUEST_RESPONSE",
                            'commType': 'REQUEST_RESPONSE',
                            "custOpName": "string",
                            'custOpName': 'string',
                            "operations": ["POST"],
                            'operations': ['POST'],
                            "description": "string"
                            'description': 'string'
                        },
                        },
                        {
                        {
                            "commType": "REQUEST_RESPONSE",
                            'commType': 'REQUEST_RESPONSE',
                            "custOpName": "check-authentication",
                            'custOpName': 'check-authentication',
                            "operations": [
                            'operations': [
                                "POST"
                                'POST'
                            ],
                            ],
                            "description": "Check authentication request."
                            'description': 'Check authentication request.'
                        },
                        },
                        {
                        {
                            "commType": "REQUEST_RESPONSE",
                            'commType': 'REQUEST_RESPONSE',
                            "custOpName": "revoke-authentication",
                            'custOpName': 'revoke-authentication',
                            "operations": [
                            'operations': [
                                "POST"
                                'POST'
                            ],
                            ],
                            "description": "Revoke authorization for service APIs."
                            'description': 'Revoke authorization for service APIs.'
                        }
                        }
                    ]
                    ]
                }
                }
            ],
            ],
            "protocol": "HTTP_1_1",
            'protocol': 'HTTP_1_1',
            "dataFormat": "JSON",
            'dataFormat': 'JSON',
            "securityMethods": ["OAUTH"],
            'securityMethods': ['OAUTH'],
            "interfaceDescriptions": [interface_description]
            'interfaceDescriptions': [interface_description]
        }
        }
        aef_profiles.append(aef_profile)
        aef_profiles.append(aef_profile)
        return aef_profiles
        return aef_profiles


    def __validate_ip_port(self, ip, port):
    def __validate_ip_port(self, ip, port):
        """Validates that the IP and port have the correct format."""
        """Validates that the IP and port have the correct format."""
        ip_pattern = re.compile(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")
        ip_pattern = re.compile(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$')


        # Validate IP
        # Validate IP
        if not ip_pattern.match(ip):
        if not ip_pattern.match(ip):
            self.logger.warning(f"Invalid IP format: {ip}. Expected IPv4 format.")
            self.logger.warning(f'Invalid IP format: {ip}. Expected IPv4 format.')
            return False
            return False


        # Validate each octet in the IP address
        # Validate each octet in the IP address
        if any(int(octet) > 255 or int(octet) < 0 for octet in ip.split(".")):
        if any(int(octet) > 255 or int(octet) < 0 for octet in ip.split('.')):
            self.logger.warning(f"IP address out of range: {ip}. Each octet should be between 0 and 255.")
            self.logger.warning(f'IP address out of range: {ip}. Each octet should be between 0 and 255.')
            return False
            return False


        # Validate Port
        # Validate Port
        if not (1 <= port <= 65535):
        if not (1 <= port <= 65535):
            self.logger.warning(f"Invalid port number: {port}. Port should be between 1 and 65535.")
            self.logger.warning(f'Invalid port number: {port}. Port should be between 1 and 65535.')
            return False
            return False


        self.logger.info("IP and port have correct format.")
        self.logger.info('IP and port have correct format.')
        return True
        return True
Loading