future updates, upgrade of api translator and adaptation to supported features...

future updates, upgrade of api translator and adaptation to supported features requierement for new release

Merge request reports

Loading
+1 −1
Changes for doc/sdk_developers.md: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -56,7 +56,7 @@ This article explains how to solve it [here](https://laict.medium.com/install-py
2. Clone GitHub repository:

```console
git clone https://github.com/Telefonica/pesp_capif_sdk.git
git clone https://labs.etsi.org/rep/ocf/sdk.git
```

```console
+29 −11
Changes for doc/sdk_full_documentation.md: 29 added lines, 11 removed lines.
Original line number Diff line number Diff line
@@ -12,7 +12,6 @@ Before using the SDK, the following steps should be completed:
- Follow the [installation instructions](./sdk_developers.md),
- Configure the SDK by completing the relevant sections in the [configuration guide](./sdk_configuration.md), depending on the CAPIF role the Network App will assume.


## Available SDK Usage Modes

![GENERAL CAPIF USAGE FLOW](./images/flows-updated_opencapif.jpg)
@@ -72,10 +71,12 @@ The provider_capif_ids variable stores the `provider_service_ids.json` content i
### Provider Onboarding

OpenCAPIF SDK references:
- **Function**: `onboard_provider()`
- **Function**: `onboard_provider(supp_features)`
- **Script**: `provider_capif_connector.py`

The SDK simplifies the onboarding process, allowing providers to register multiple APFs and AEFs. All APFs, AEFs, and AMF certificates are created and stored in `provider_service_ids.json`.
`supp_features` parameter is optional and it stands for communicating to the CCF the supported features.It's default value its 0.


![Provider_onboard](./images/flows-provider_onboard.jpg)

@@ -153,12 +154,14 @@ Retrieve information about all previously published services in `service_receive
### Update and Offboard Provider

OpenCAPIF SDK references:
- **Functions**: `update_provider()` and `offboard_provider()`
- **Functions**: `update_provider(supp_features)` and `offboard_provider()`
- **Scripts**: `provider_capif_connector_update.py` and `provider_capif_connector_offboarding.py`

`update_provider()`: The provider updates his features such as `APFs`, `AEFs`, etc...
`update_provider(supp_features)`: The provider updates his features such as `APFs`, `AEFs`, etc...
`offboard_provider()`: The provider offboards from CAPIF, this will cause the erase of the published APIs that were currently exposed. 

`supp_features` parameter is optional and it stands for communicating to the CCF the supported features.It's default value its 0.

The provider must be onboarded before using these features.

![Provider_update-offboard](./images/flows-provider_update_offboard.jpg)
@@ -166,10 +169,12 @@ The provider must be onboarded before using these features.
### Create logs

OpenCAPIF SDK references:
- **Function**: `create_logs(aefId, jwt)`
- **Function**: `create_logs(aefId, jwt, supp_features)`

The provider notifies to the CCF that the published API has been used by certain invoker.

`supp_features` parameter is optional and it stands for communicating to the CCF the supported features.It's default value its 0.

For leveraging this feature the Provider must have onboarded and published an API previously.

**Required SDK input**:
@@ -182,10 +187,12 @@ For leveraging this feature the Provider must have onboarded and published an AP
### Create subscription

OpenCAPIF SDK references:
- **Function**: `create_subscription(name, id)`
- **Function**: `create_subscription(name, id, supp_features)`

The provider ask to the CCF about notifications related to services such as SERVICE_API_AVAILABLE or API_INVOKER_UPDATED.

`supp_features` parameter is optional and it stands for communicating to the CCF the supported features.It's default value its 0.

This services are specificated in [CAPIF Events API management](https://github.com/jdegre/5GC_APIs/blob/Rel-18/TS29222_CAPIF_Events_API.yaml) explained in [SDK configuration](./sdk_configuration.md#descriptions-of-capif_sdk_config-fields)

For leveraging this feature the Provider must have onboarded previously.
@@ -213,12 +220,14 @@ For leveraging this feature the Provider must have onboarded and created a subsc
### Update subscription

OpenCAPIF SDK references:
- **Function**: `update_subscription(name, id)`
- **Function**: `update_subscription(name, id, supp_features)`

The provider ask to the CCF about updating the subscription for receiving different services such as SERVICE_API_AVAILABLE or API_INVOKER_UPDATED, changing the URL for receiving the notifications...

This services are specificated in [CAPIF Events API management](https://github.com/jdegre/5GC_APIs/blob/Rel-18/TS29222_CAPIF_Events_API.yaml) explained in [SDK configuration](./sdk_configuration.md#descriptions-of-capif_sdk_config-fields)

`supp_features` parameter is optional and it stands for communicating to the CCF the supported features.It's default value its 0.

For leveraging this feature the Provider must have onboarded and created a subscription previously.

![Events_feature](./images/flows-event_subscription.jpg)
@@ -238,6 +247,8 @@ OpenCAPIF SDK references:

The provider ask to the CCF about updating the subscription for receiving different services such as SERVICE_API_AVAILABLE or API_INVOKER_UPDATED.

`supp_features` parameter is optional and it stands for communicating to the CCF the supported features.It's default value its 0.

This services are specificated in [CAPIF Events API management](https://github.com/jdegre/5GC_APIs/blob/Rel-18/TS29222_CAPIF_Events_API.yaml) explained in [SDK configuration](./sdk_configuration.md#events_configuration)

For leveraging this feature the Provider must have onboarded and created a subscription previously.
@@ -271,11 +282,14 @@ The invoker_capif_details variable stores the `capif_api_security_context_detail
### Invoker onboarding

OpenCAPIF SDK references:
- **Function**: `onboard_invoker()`
- **Function**: `onboard_invoker(supp_features)`
- **Script**: `invoker_capif_connector.py`

The SDK streamlines the invoker onboarding process, storing the `api_invoker_id` in the `capif_api_security_context_details.json`.

`supp_features` parameter is optional and it stands for communicating to the CCF the supported features.It's default value its 0.


![Invoker_onboard](./images/flows-invoker_onboard.jpg)

### Service Discovery
@@ -295,10 +309,11 @@ Use the [discover_filter](./sdk_configuration.md) to retrieve access to target A
### Obtain JWT Tokens

OpenCAPIF SDK references:
- **Function**: `get_tokens()`
- **Function**: `get_tokens(supp_features)`
- **Script**: `invoker_service_get_token.py`

The SDK facilitates JWT token creation for secure access to target APIs. This process stores JWT access token in `capif_api_security_context_details.json`.
`supp_features` parameter is optional and it stands for retrieve the token of the services that have certain supported features.It's default value its 0.

![Invoker_get_token](./images/flows-invoker_get_tokens.jpg)

@@ -319,11 +334,14 @@ It is mandatory to have obtained the [JWT token](#obtain-jwt-tokens) previously.
### Update and Offboard Invoker

OpenCAPIF SDK references:
- **Functions**: `update_invoker()` and `offboard_invoker()`
- **Functions**: `update_invoker(supp_features)` and `offboard_invoker()`
- **Scripts**: `invoker_capif_connector_update.py` and `invoker_capif_connector_offboarding.py`

Onboarding is required before utilizing these functions.

`supp_features` parameter is optional and it stands for communicating to the CCF the supported features.It's default value its 0.


![Invoker_update-offboard](./images/flows-invoker_update_offboard.jpg)

## Other Features
@@ -337,7 +355,7 @@ This schema could be obtained by applying this code.
    import opencapif_sdk
    
    translator = opencapif_sdk.api_schema_translator("./path/to/openapi.yaml")
    translator.build("api_description_name",ip="0.0.0.0",port=9090,supported_features="0",api_supp_features="0")
    translator.build("https://192.168.1.10:8080/exampleAPI/v1", "0", "0")
```
This code will read `openapi.yaml`, ensure the structure of it and translate the content into ServiceAPIDescription schema, then will create a .json named `api_description_name`. Also it is necessary to fill the ip and port fields to create correctly the schema.
The supported_features and api_supp_features fields corresponds to the capabilities of the provider and the service that the user is sharing.
+64 −15
Changes for opencapif_sdk/api_schema_translator.py: 64 added lines, 15 removed lines.
Original line number Diff line number Diff line
@@ -2,9 +2,9 @@ import json
import logging
import os
import re
import socket
import yaml


log_path = 'logs/builder_logs.log'

log_dir = os.path.dirname(log_path)
@@ -34,31 +34,81 @@ class api_schema_translator:
        self.api_info = self.__load_api_file(self.api_path)
        self.__validate_api_info()

    def build(self, api_name, supported_features, api_supp_features, ip=None, port=None, fqdn=None, ipv6Addr=None):
    def __validate_ip_port(self, ip, port):
        """Validates if an IP address and port are correctly formatted."""
        try:
            socket.inet_aton(ip)  # Validate IPv4
            return isinstance(port, int) and 0 < port < 65536
        except socket.error:
            return False

    def __parse_url(self, url):
        """
        Parses the URL to extract apiRoot, apiName, and apiVersion.
        Handles:
        - URLs with or without ports.
        - API root as an IP, FQDN, or preconfigured prefix.
        - Assigns default ports for HTTP (80) and HTTPS (443) if missing.
        """

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

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

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

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

        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>")
            return None, None, None, None, None, None, None

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

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

    def build(self, url, supported_features, api_supp_features):
        """
        Builds the API description and saves it to a JSON file.
        Supports either IPv4 (ip), IPv6 (ipv6Addr), or FQDN (fqdn).
        Extracts apiRoot, apiName, and apiVersion.
        Supports IP, FQDN, and URLs with or without explicit ports.
        """
        # Validate required fields
        # Validación de campos requeridos
        if not supported_features or not api_supp_features:
            self.logger.error("Both 'supported_features' and 'api_supp_features' are required. Aborting build.")
            return

        # Validate that at least one of ip, ipv6Addr, or fqdn is provided
        if not (ip or ipv6Addr or fqdn):
            self.logger.error("At least one of 'ip', 'ipv6Addr', or 'fqdn' must be provided. Aborting build.")
        # Parseamos la URL
        ip, port, fqdn, ipv6Addr, api_root, api_name, api_version = self.__parse_url(url)

        # Validamos que al menos una dirección sea válida
        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.")
            return

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

        # Build the API data
        # Construcción de la API
        try:
            api_data = {
                "apiName": self.api_info["info"].get("title", api_name),
                "aefProfiles": self.__build_aef_profiles(ip, port, fqdn, ipv6Addr),
                "apiName": api_name,
                "aefProfiles": self.__build_aef_profiles(ip, port, api_version, fqdn, ipv6Addr),
                "description": self.api_info["info"].get("description", "No description provided"),
                "supportedFeatures": supported_features,
                "shareableInfo": {
@@ -73,7 +123,7 @@ class api_schema_translator:
                "ccfId": "string"
            }

            # Save the API data to a JSON file
            # Guardamos los datos en un archivo JSON
            with open(f"{api_name}.json", "w") as outfile:
                json.dump(api_data, outfile, indent=4)
            self.logger.info(f"API description saved to {api_name}.json")
@@ -81,7 +131,6 @@ class api_schema_translator:
        except Exception as e:
            self.logger.error(f"An error occurred during the build process: {e}")


    def __load_api_file(self, api_file: str):
        """Loads the Swagger API configuration file and converts YAML to JSON format if necessary."""
        try:
@@ -112,7 +161,7 @@ class api_schema_translator:
        else:
            self.logger.info("All required components are present in the API specification.")

    def __build_aef_profiles(self, ip, port, 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."""
        aef_profiles = []

@@ -149,7 +198,7 @@ class api_schema_translator:
            "aefId": "",  # Placeholder AEF ID
            "versions": [
                {
                    "apiVersion": "v1",
                    "apiVersion": f"{api_version}",
                    "expiry": "2100-11-30T10:32:02.004Z",
                    "resources": resources,
                    "custOperations": [
+10 −10
Changes for opencapif_sdk/capif_event_feature.py: 10 added lines, 10 removed lines.
Original line number Diff line number Diff line
@@ -30,7 +30,7 @@ logging.basicConfig(

class capif_invoker_event_feature(capif_invoker_connector):

    def create_subscription(self, name):
    def create_subscription(self, name, supp_features="0"):

        invoker_capif_details = self.invoker_capif_details

@@ -48,7 +48,7 @@ class capif_invoker_event_feature(capif_invoker_connector):
                "websocketUri": f"{self.capif_callback_url}",
                "requestWebsocketUri": True
            },
            "supportedFeatures": f"{self.supported_features}"
            "supportedFeatures": f"{supp_features}"
        }

        try:
@@ -150,7 +150,7 @@ class capif_invoker_event_feature(capif_invoker_connector):
            self.logger.error("Subscription file not found at path: %s", path)
            return None, {"error": "Subscription file not found"}

    def update_subcription(self, name):
    def update_subcription(self, name, supp_features="0"):
        invoker_capif_details = self.invoker_capif_details

        subscriberId = invoker_capif_details["api_invoker_id"]
@@ -167,7 +167,7 @@ class capif_invoker_event_feature(capif_invoker_connector):
                "websocketUri": f"{self.capif_callback_url}",
                "requestWebsocketUri": True
            },
            "supportedFeatures": f"{self.supported_features}"
            "supportedFeatures": f"{supp_features}"
        }
        if os.path.exists(path):
            subscription = self._load_config_file(path)
@@ -209,7 +209,7 @@ class capif_invoker_event_feature(capif_invoker_connector):

class capif_provider_event_feature(capif_provider_connector):

    def create_subscription(self, name, id):
    def create_subscription(self, name, id, supp_features="0"):

        subscriberId = id

@@ -226,7 +226,7 @@ class capif_provider_event_feature(capif_provider_connector):
            "notificationDestination": f"{self.notification_destination}",
            "requestTestNotification": True,
            "websockNotifConfig": self.websock_notif_config,
            "supportedFeatures": f"{self.supported_features}"
            "supportedFeatures": f"{supp_features}"
        }

        number_low = number.lower()
@@ -345,7 +345,7 @@ class capif_provider_event_feature(capif_provider_connector):
            self.logger.error("Subscription file not found at path: %s", path)
            return None, {"error": "Subscription file not found"}

    def update_subcription(self, name, id):
    def update_subcription(self, name, id, supp_features="0"):

        subscriberId = id

@@ -362,7 +362,7 @@ class capif_provider_event_feature(capif_provider_connector):
            "notificationDestination": f"{self.notification_destination}",
            "requestTestNotification": True,
            "websockNotifConfig": self.websock_notif_config,
            "supportedFeatures": f"{self.supported_features}"
            "supportedFeatures": f"{supp_features}"
        }

        if os.path.exists(path):
@@ -420,5 +420,5 @@ class capif_provider_event_feature(capif_provider_connector):
            self.logger.error("Subscription file not found at path: %s", path)
            return None, {"error": "Subscription file not found"}

    def patch_subcription(self, name, id):
        self.update_subcription(self, name, id)
    def patch_subcription(self, name, id, supp_features="0"):
        self.update_subcription(self, name, id, supp_features)
Loading
Loading