aboutsummaryrefslogtreecommitdiffstats
path: root/onap_data_provider/resources/service_instance_resource.py
blob: b23de403bc8a54546918258f2e5871e340d9f7e5 (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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
"""Service instance resource module."""
"""
   Copyright 2021 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.
"""
import logging
from typing import Any, Dict, List

from onapsdk.aai.cloud_infrastructure import CloudRegion, Tenant  # type: ignore
from onapsdk.aai.business import Customer, OwningEntity  # type: ignore
from onapsdk.aai.service_design_and_creation import Service as AaiService  # type: ignore
from onapsdk.sdc.service import Service  # type: ignore
from onapsdk.vid import LineOfBusiness, Platform, Project  # type: ignore
from onapsdk.aai.business import ServiceSubscription
from onapsdk.aai.business import ServiceInstance
from onapsdk.so.instantiation import (  # type: ignore
    ServiceInstantiation,
    SoService,
    SoServicePnf,
    SoServiceVfModule,
    SoServiceVnf
)

from .resource import Resource
from onapsdk.exceptions import APIError, ResourceNotFound  # type: ignore


class ServiceInstanceResource(Resource):
    """Service instance resource class.

    Creates service instance.
    """

    def __init__(self, data: Dict[str, Any]) -> None:
        """Service instance resource initialization.

        Args:
            data (Dict[str, Any]): Data needed to create service instance

        """
        super().__init__(data)
        self._customer: Customer = None
        self._service_subscription: ServiceSubscription = None
        self._service_instance: ServiceInstance = None
        self._aai_service: AaiService = None

    def create(self) -> None:
        """Create ServiceInstance resource."""
        if not self.exists:

            service: Service = Service(name=self.data["service_name"])
            if not service.distributed:
                raise AttributeError(
                    "Service not distrbuted - instance can't be created"
                )
            if (cloud_region_id := self.data.get("cloud_region_id")) is not None:
                cloud_region: CloudRegion = CloudRegion.get_by_id(
                    cloud_owner=self.data["cloud_owner"],
                    cloud_region_id=cloud_region_id,
                )
                tenant: Tenant = None
                if tenant_name := self.data.get("tenant_name"):
                    # TODO: https://jira.onap.org/browse/INT-2056 refactor below when ONAP SDK 9.2.3 is released
                    cr_tenants = [
                        x for x in cloud_region.tenants if x.name == tenant_name
                    ]
                    if len(cr_tenants) > 1:
                        msg = "\n".join(
                            [
                                "===================",
                                f"There are more than one tenant with given name '{tenant_name}':",
                                "\n".join(
                                    f"{t.name}: {t.tenant_id}" for t in cr_tenants
                                ),
                                "Use tenant-id instead of tenant-name to specify which tenant should be used during the instantiation.",
                                "===================",
                            ]
                        )
                        logging.error(msg)
                        raise ValueError(
                            "Value provided for 'tenant_name' is ambiguous."
                        )
                    if not cr_tenants:
                        raise ValueError(f"Tenant '{tenant_name}' not found.")
                    tenant = cr_tenants.pop()
                else:
                    tenant = cloud_region.get_tenant(self.data["tenant_id"])
                self.service_subscription.link_to_cloud_region_and_tenant(
                    cloud_region, tenant
                )
            else:
                cloud_region, tenant = None, None
            try:
                owning_entity = OwningEntity.get_by_owning_entity_name(
                    self.data["owning_entity"]
                )
            except APIError:
                owning_entity = OwningEntity.create(self.data["owning_entity"])

            try:
                aai_service = next(
                    AaiService.get_all(service_id=self.data["aai_service"])
                )
            except StopIteration:
                raise ValueError(
                    f"A&AI Service {self.data['aai_service']} does not exist"
                )

            service_instantiation: ServiceInstantiation = (
                ServiceInstantiation.instantiate_macro(
                    sdc_service=service,
                    customer=self.customer,
                    owning_entity=owning_entity,
                    project=Project(self.data["project"]),
                    line_of_business=LineOfBusiness(self.data["line_of_business"]),
                    platform=Platform(self.data["platform"]),
                    cloud_region=cloud_region,
                    tenant=tenant,
                    service_instance_name=self.data["service_instance_name"],
                    so_service=self.so_service,
                    aai_service=aai_service,
                )
            )
            service_instantiation.wait_for_finish(
                timeout=self.data.get("timeout")
            )  # 20 minutes timeout

            if service_instantiation.failed == True:
                logging.error(
                    "Service instantiation failed for %s",
                    self.data["service_instance_name"],
                )
                return
            self._service_instance = (
                self.service_subscription.get_service_instance_by_name(
                    self.data["service_instance_name"]
                )
            )

    @property
    def exists(self) -> bool:
        """Determine if resource already exists or not.

        Returns:
            bool: True if object exists, False otherwise

        """
        return self.service_instance is not None

    @property
    def service_instance(self) -> ServiceInstance:
        """Serviceinstance property.

        Returns:
            ServiceInstance: ServiceInstance object

        """
        if not self._service_instance:
            try:
                service_instance: ServiceInstance = (
                    self.service_subscription.get_service_instance_by_name(
                        self.data["service_instance_name"]
                    )
                )
                if service_instance:
                    self._service_instance = service_instance
            except ResourceNotFound:
                logging.error(
                    "Customer %s does not exist",
                    self.data["customer_id"],
                )
        return self._service_instance

    @property
    def customer(self) -> Customer:
        """Access to Customer object property.

        Returns:
            Customer: Customer object

        """
        if not self._customer:
            self._customer = Customer.get_by_global_customer_id(
                self.data["customer_id"]
            )
        return self._customer

    @property
    def service_subscription(self) -> ServiceSubscription:
        """Service subscription property.

        Returns:
            ServiceSubscription: ServiceSubscription object

        """
        if not self._service_subscription and self.customer:
            self._service_subscription = (
                self.customer.get_service_subscription_by_service_type(
                    service_type=self.data.get(
                        "service_subscription_type", self.data["service_name"]
                    )
                )
            )
        return self._service_subscription

    @property
    def so_service(self) -> SoService:
        """Create an object with parameters for the service instantiation.

        Based on the instance definition data create an object
        which is used for instantiation.

        Returns:
            SoService: SoService object

        """
        vnfs: List[SoServiceVnf] = []
        pnfs: List[SoServicePnf] = []
        for xnf in self.data.get("instantiation_parameters", []):
            if "vnf_name" in xnf:
                vnfs.append(SoServiceVnf(
                    model_name=xnf["vnf_name"],
                    instance_name=xnf.get("instance_name", xnf["vnf_name"]),
                    parameters=xnf.get("parameters", {}),
                    vf_modules=[SoServiceVfModule(
                        model_name=vf_module["name"],
                        instance_name=vf_module.get("instance_name", vf_module["name"]),
                        parameters=vf_module.get("parameters", {})
                    ) for vf_module in xnf.get("vf_modules", [])]
                ))
            elif "pnf_name" in xnf:
                pnfs.append(SoServicePnf(
                    model_name=xnf["pnf_name"],
                    instance_name=xnf.get("instance_name", xnf["pnf_name"]),
                    parameters=xnf.get("parameters", {})
                ))
            else:
                logging.warning("Invalid content, xNF type not supported")
        return SoService(
            subscription_service_type=self.service_subscription.service_type,
            vnfs=vnfs,
            pnfs=pnfs
        )

    @property
    def aai_service(self) -> AaiService:
        """A&AI service which is used during the instantiation.

        Raises:
            ValueError: AaiService with given service id doesn't exist

        Returns:
            AaiService: AaiService object

        """
        if (
            not self._aai_service
            and (aai_service_id := self.data.get("aai_service")) is not None
        ):
            try:
                self._aai_service = next(AaiService.get_all(service_id=aai_service_id))
            except StopIteration:
                raise ValueError(f"A&AI Service {aai_service_id} does not exist")
        return self._aai_service


class ServiceInstanceResource_1_1(ServiceInstanceResource):
    """Service instance resource class.

    That's the Service instance resource class for 1.1 schema version.
    """

    @property
    def aai_service(self) -> AaiService:
        """A&AI service which is used during the instantiation.

        Raises:
            ValueError: AaiService with given service id doesn't exist

        Returns:
            AaiService: AaiService object

        """
        if not self._aai_service:
            try:
                self._aai_service = next(
                    AaiService.get_all(service_id=self.data["aai_service"])
                )
            except StopIteration:
                raise ValueError(
                    f"A&AI Service {self.data['aai_service']} does not exist"
                )
        return self._aai_service