aboutsummaryrefslogtreecommitdiffstats
path: root/src/onapsdk/sdc/component.py
blob: 9b26bef7966ecdee5fe632c232b3b9fcf6e81ac7 (plain)
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
"""SDC Component module."""
#   Copyright 2022 Orange, Deutsche Telekom AG
#
#   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 dataclasses import dataclass
from typing import Any, Dict, Iterator, List, Optional
from onapsdk.exceptions import ParameterError

from onapsdk.sdc.properties import ComponentProperty
from onapsdk.utils.jinja import jinja_env


@dataclass
class Component:  # pylint: disable=too-many-instance-attributes
    """Component dataclass."""

    created_from_csar: bool
    actual_component_uid: str
    unique_id: str
    normalized_name: str
    name: str
    origin_type: str
    customization_uuid: str
    component_uid: str
    component_version: str
    tosca_component_name: str
    component_name: str
    group_instances: Optional[List[Dict[str, Any]]]
    sdc_resource: "SdcResource"
    parent_sdc_resource: "SdcResource"

    @classmethod
    def create_from_api_response(cls,
                                 api_response: Dict[str, Any],
                                 sdc_resource: "SdcResource",
                                 parent_sdc_resource: "SdcResource") -> "Component":
        """Create component from api response.

        Args:
            api_response (Dict[str, Any]): component API response
            sdc_resource (SdcResource): component's SDC resource
            parent_sdc_resource (SdcResource): component's parent SDC resource

        Returns:
            Component: Component created using api_response and SDC resource

        """
        return cls(created_from_csar=api_response["createdFromCsar"],
                   actual_component_uid=api_response["actualComponentUid"],
                   unique_id=api_response["uniqueId"],
                   normalized_name=api_response["normalizedName"],
                   name=api_response["name"],
                   origin_type=api_response["originType"],
                   customization_uuid=api_response["customizationUUID"],
                   component_uid=api_response["componentUid"],
                   component_version=api_response["componentVersion"],
                   tosca_component_name=api_response["toscaComponentName"],
                   component_name=api_response["componentName"],
                   group_instances=api_response["groupInstances"],
                   sdc_resource=sdc_resource,
                   parent_sdc_resource=parent_sdc_resource)

    @property
    def properties_url(self) -> str:
        """Url to get component's properties.

        Returns:
            str: Compoent's properties url

        """
        return self.parent_sdc_resource.get_component_properties_url(self)

    @property
    def properties_value_url(self) -> str:
        """Url to set component property value.

        Returns:
            str: Url to set component property value

        """
        return self.parent_sdc_resource.get_component_properties_value_set_url(self)

    @property
    def properties(self) -> Iterator["ComponentProperty"]:
        """Component properties.

        In SDC it's named as properties, but we uses "inputs" endpoint to fetch them.
            Structure is also input's like, but it's a property.

        Yields:
            ComponentProperty: Component property object

        """
        for component_property in self.sdc_resource.send_message_json(\
                "GET",
                f"Get {self.name} component properties",
                self.properties_url):
            yield ComponentProperty(unique_id=component_property["uniqueId"],
                                    name=component_property["name"],
                                    property_type=component_property["type"],
                                    _value=component_property.get("value"),
                                    component=self)

    def get_property(self, property_name: str) -> "ComponentProperty":
        """Get component property by it's name.

        Args:
            property_name (str): property name

        Raises:
            ParameterError: Component has no property with given name

        Returns:
            ComponentProperty: Component's property object

        """
        for property_obj in self.properties:
            if property_obj.name == property_name:
                return property_obj
        msg = f"Component has no property with {property_name} name"
        raise ParameterError(msg)

    def set_property_value(self, property_obj: "ComponentProperty", value: Any) -> None:
        """Set property value.

        Set given value to component property

        Args:
            property_obj (ComponentProperty): Component property object
            value (Any): Property value to set

        """
        self.sdc_resource.send_message_json(
            "POST",
            f"Set {self.name} component property {property_obj.name} value",
            self.properties_value_url,
            data=jinja_env().get_template(\
                "sdc_resource_component_set_property_value.json.j2").\
                render(
                    component=self,
                    value=value,
                    property=property_obj
                )
        )

    def delete(self) -> None:
        """Delete component."""
        self.sdc_resource.send_message_json(
            "DELETE",
            f"Delete {self.name} component",
            f"{self.parent_sdc_resource.resource_inputs_url}/resourceInstance/{self.unique_id}"
        )