Commit 1eee74c0 authored by Laskaratos Dimitris's avatar Laskaratos Dimitris
Browse files

Fixed bugs related to edge cloud management api

parent 2d9454f7
Loading
Loading
Loading
Loading
+64 −48
Original line number Original line Diff line number Diff line
@@ -98,14 +98,18 @@ def get_app(appId, x_correlator=None): # noqa: E501
def delete_app(appId, x_correlator=None):  # noqa: E501
def delete_app(appId, x_correlator=None):  # noqa: E501
    """Delete Application metadata from an Edge Cloud Provider"""
    """Delete Application metadata from an Edge Cloud Provider"""
    try:
    try:
        with MongoManager() as db:
        pi_edge_factory = PiEdgeAPIClientFactory()
            number_of_deleted_documents = db.delete_document("apps", {"_id": appId})
        api_client = pi_edge_factory.create_pi_edge_api_client()
            if number_of_deleted_documents == 0:
        response = api_client.delete_app(appId=appId)
                raise NotFound404Exception()
        return response.json()
            elif number_of_deleted_documents == 1:
        # with MongoManager() as db:
                return ("", 204)
        #     number_of_deleted_documents = db.delete_document("apps", {"_id": appId})
            else:
        #     if number_of_deleted_documents == 0:
                raise Exception(f"deleted {number_of_deleted_documents} documents")
        #         raise NotFound404Exception()
        #     elif number_of_deleted_documents == 1:
        #         return ("", 204)
        #     else:
        #         raise Exception(f"deleted {number_of_deleted_documents} documents")


    except NotFound404Exception:
    except NotFound404Exception:
        return (
        return (
@@ -136,25 +140,27 @@ def create_app_instance():
            return jsonify({"error": "Missing required fields: appId or appZones"}), 400
            return jsonify({"error": "Missing required fields: appId or appZones"}), 400


        # Step 3: Connect to Mongo and check if app exists
        # Step 3: Connect to Mongo and check if app exists
        with MongoManager() as mongo_manager:
        # with MongoManager() as mongo_manager:
            app_data = mongo_manager.find_document("apps", {"_id": app_id})
        #     app_data = mongo_manager.find_document("apps", {"_id": app_id})
        pi_edge_client_factory = PiEdgeAPIClientFactory()
        pi_edge_client = pi_edge_client_factory.create_pi_edge_api_client()
        # app_data = pi_edge_client.get_app(app_id)


        if not app_data:
        # if len(app_data)<1:
            logger.warning(f"No application found with ID {app_id}")
        #     logger.warning(f"No application found with ID {app_id}")
            return jsonify({"error": "App not found", "details": f"No application found with ID {app_id}"}), 404
        #     return jsonify({"error": "App not found", "details": f"No application found with ID {app_id}"}), 404


        logger.info(f"Application {app_id} found in database")
        # logger.info(f"Application {app_id} found in database")


        # Step 4: Deploy app instance using Pi-Edge client
        # Step 4: Deploy app instance using Pi-Edge client
        pi_edge_client_factory = PiEdgeAPIClientFactory()
        pi_edge_client = pi_edge_client_factory.create_pi_edge_api_client()
    
    
        logger.info(f"Preparing to send deployment request to Pi-Edge for appId={app_id}")


        deployment_payload = [{
        logger.info(f"Preparing to send deployment request to SRM for appId={app_id}")

        deployment_payload = {
            "appId": app_id,
            "appId": app_id,
            "appZones": app_zones
            "appZones": app_zones
        }]
        }


        #Print everything before sending
        #Print everything before sending
        print("\n=== Preparing Deployment Request ===")
        print("\n=== Preparing Deployment Request ===")
@@ -174,7 +180,7 @@ def create_app_instance():
                    "details": response
                    "details": response
                }), 202  # Still accept the request but warn
                }), 202  # Still accept the request but warn


            logger.info(f"Deployment response from Pi-Edge: {response}")
            logger.info(f"Deployment response from SRM: {response}")


        except Exception as inner_error:
        except Exception as inner_error:
            logger.error(f"Exception while trying to deploy to SRM: {inner_error}")
            logger.error(f"Exception while trying to deploy to SRM: {inner_error}")
@@ -198,16 +204,22 @@ def get_app_instance(app_id=None, x_correlator=None, app_instance_id=None, regio
    Supports filtering by app_id, app_instance_id, and region.
    Supports filtering by app_id, app_instance_id, and region.
    """
    """
    try:
    try:
        query = {}
        # query = {}
        if app_id:
        # if app_id:
            query["appId"] = app_id
        #     query["appId"] = app_id
        if app_instance_id:
        # if app_instance_id:
            query["appInstanceId"] = app_instance_id
        #     query["appInstanceId"] = app_instance_id
        if region:
        # if region:
            query["edgeCloudZone.edgeCloudRegion"] = region
        #     query["edgeCloudZone.edgeCloudRegion"] = region

        # with MongoManager() as db:
        #     instances = list(db.find_documents("appinstances", query))
        instances = None
        pi_edge_client_factory = PiEdgeAPIClientFactory()
        pi_edge_client = pi_edge_client_factory.create_pi_edge_api_client()


        with MongoManager() as db:
        if app_id is None and app_instance_id is None:
            instances = list(db.find_documents("appinstances", query))
            instances = pi_edge_client.get_app_instances()


        if not instances:
        if not instances:
            return jsonify({
            return jsonify({
@@ -227,7 +239,7 @@ def get_app_instance(app_id=None, x_correlator=None, app_instance_id=None, regio
        }), 500
        }), 500




def delete_app_instance(app_id, app_instance_id, x_correlator=None):
def delete_app_instance(appInstanceId: str, x_correlator=None):
    """
    """
    Terminate an Application Instance
    Terminate an Application Instance


@@ -235,24 +247,28 @@ def delete_app_instance(app_id, app_instance_id, x_correlator=None):
    - Returns 204 if deleted, 404 if not found.
    - Returns 204 if deleted, 404 if not found.
    """
    """
    try:
    try:
        with MongoManager() as db:
        pi_edge_client_factory = PiEdgeAPIClientFactory()
            query = {
        pi_edge_client = pi_edge_client_factory.create_pi_edge_api_client()
                "appInstanceId": app_instance_id,
        response = pi_edge_client.delete_app_instance(appInstanceId)
                "appId": app_id
        return jsonify({'result': response.text, 'status': response.status_code})
            }
        # with MongoManager() as db:
            deleted_count = db.delete_document("appinstances", query)
        #     query = {
        #         "appInstanceId": app_instance_id,
        #         "appId": app_id
        #     }
        #     deleted_count = db.delete_document("appinstances", query)


            if deleted_count == 0:
        #     if deleted_count == 0:
                return (
        #         return (
                    jsonify({
        #             jsonify({
                        "status": 404,
        #                 "status": 404,
                        "code": "NOT_FOUND",
        #                 "code": "NOT_FOUND",
                        "message": "App instance not found"
        #                 "message": "App instance not found"
                    }),
        #             }),
                    404,
        #             404,
                )
        #         )


            return "", 204  # Successfully deleted
        #     return "", 204  # Successfully deleted


    except Exception as e:
    except Exception as e:
        return (
        return (
+72 −3
Original line number Original line Diff line number Diff line
@@ -139,6 +139,29 @@ class PiEdgeAPIClient:
                "status_code": response.status_code,
                "status_code": response.status_code,
            }
            }
        
        
    def delete_app(self, appId:str):
        """
        Remove app metadata from SRM
        """
        url = f"{self.base_url}/serviceFunction/"+appId
        try:
            response = requests.delete(url,headers=self._get_headers(), verify=False)
            response.raise_for_status()
            return response
        except Timeout:
            return {"error": "The request to the external API timed out. Please try again later."}

        except ConnectionError:
            return {"error": "Failed to connect to the external API service. Service might be unavailable."}

        except requests.exceptions.HTTPError as http_err:
            return {
                "error": f"HTTP error occurred: {http_err}.",
                "status_code": response.status_code,
            }

        except Exception as err:
            return {"error": f"An unexpected error occurred: {err}"}


    def deploy_service_function(self, data: list):
    def deploy_service_function(self, data: list):
        """
        """
@@ -146,8 +169,9 @@ class PiEdgeAPIClient:
        """
        """
        url = f"{self.base_url}/deployedServiceFunction"
        url = f"{self.base_url}/deployedServiceFunction"
        try:
        try:
            response = requests.post(url, json=data, headers=self._get_headers())
            response = requests.post(url, json=data, headers=self._get_headers(), verify=False)
            response.raise_for_status()
            response.raise_for_status()
            return response.json()
        except Timeout:
        except Timeout:
            return {"error": "The request to the external API timed out. Please try again later."}
            return {"error": "The request to the external API timed out. Please try again later."}


@@ -163,6 +187,51 @@ class PiEdgeAPIClient:
        except Exception as err:
        except Exception as err:
            return {"error": f"An unexpected error occurred: {err}"}
            return {"error": f"An unexpected error occurred: {err}"}
        
        

    def get_app_instances(self):
        """
        Retrieve all app instances.
        """
        url = f"{self.base_url}/deployedServiceFunction"
        try:
            response = requests.get(url, headers=self._get_headers(), verify=False)
            response.raise_for_status()
            return response.json()
        except Timeout:
            return {"error": "The request to the external API timed out. Please try again later."}

        except ConnectionError:
            return {"error": "Failed to connect to the external API service. Service might be unavailable."}

        except requests.exceptions.HTTPError as http_err:
            return {
                "error": f"HTTP error occurred: {http_err}.",
                "status_code": response.status_code,
            }
        

    def delete_app_instance(self, app_instance_id:str):
        """
        Remove app instance.
        """
        url = f"{self.base_url}/deployedServiceFunction/"+app_instance_id
        try:
            response = requests.delete(url, headers=self._get_headers(), verify=False)
            response.raise_for_status()
            return response
        except Timeout:
            return {"error": "The request to the external API timed out. Please try again later."}

        except ConnectionError:
            return {"error": "Failed to connect to the external API service. Service might be unavailable."}

        except requests.exceptions.HTTPError as http_err:
            return {
                "error": f"HTTP error occurred: {http_err}.",
                "status_code": response.status_code,
            }


    def edge_cloud_zones(self):
    def edge_cloud_zones(self):
        """
        """
        Get list of edge zones from /node endpoint.
        Get list of edge zones from /node endpoint.
@@ -170,7 +239,7 @@ class PiEdgeAPIClient:
        url = f"{self.base_url}/node"
        url = f"{self.base_url}/node"
        #try:
        #try:
        request_headers = self._get_headers()
        request_headers = self._get_headers()
        response = requests.get(url, headers=request_headers)
        response = requests.get(url, headers=request_headers,verify=False)
        response.raise_for_status()
        response.raise_for_status()
        nodes = response.json()
        nodes = response.json()
        if not nodes:
        if not nodes: