aboutsummaryrefslogtreecommitdiffstats
path: root/src/onapsdk/k8s/instance.py
blob: f08733d7b169395b3055252273e86ef205e3bc2f (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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
"""Instantiation 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.
import json
from typing import Any, Dict, Iterator
from dataclasses import dataclass

from onapsdk.utils.jinja import jinja_env
from .k8splugin_service import QueryResourceStatusMixin, ResourceStatus, RemovableK8sPlugin


# pylint: disable=too-many-arguments
@dataclass
class InstantiationRequest:
    """Instantiation Request class."""

    def __init__(self, request: dict) -> None:
        """Request object initialization.

        Args:
            cloud_region_id (str): Cloud region ID
            profile_name (str): Name of profile
            rb_name (str): Definition name
            rb_version (str): Definition version
            override_values (dict): Optional parameters
            labels (dict): Optional labels
        """
        super().__init__()
        self.cloud_region_id: str = request["cloud-region"]
        self.profile_name: str = request["profile-name"]
        self.rb_name: str = request["rb-name"]
        self.rb_version: str = request["rb-version"]
        self.override_values: dict = request["override-values"]
        self.labels: dict = request["labels"]


@dataclass
class InstantiationParameter:
    """Class to store instantiation parameters used to pass override_values and labels.

    Contains two values: name of parameter and it's value
    """

    name: str
    value: str


class InstanceBase(RemovableK8sPlugin):
    """InstanceBase class."""

    def __init__(self, instance_id: str) -> None:
        """Instance-Base object initialization.

        Args:
            instance_id (str): instance ID
        """
        super().__init__()
        self.instance_id: str = instance_id

    @property
    def url(self) -> str:
        """URL address.

        Returns:
            str: URL to Instance

        """
        return f"{self.base_url_and_version()}/instance/{self.instance_id}"


@dataclass
class ConfigurationTag:
    """Class to store configuration tag information.

    Contains two values: name of tag and version of associated configuration
    """

    config_tag: str
    config_version: str


class Configuration(InstanceBase):
    """Configuration class."""

    def __init__(self, instance_id: str,
                 config_name: str,
                 template_name: str,
                 description: str,
                 config_version: str,
                 config_tag: str,
                 values: dict = None) -> None:
        """Initialize Configuration object.

        Args:
            instance_id (str): instance ID
            config_name (str): Name of the configuration
            template_name (str): Name of the template
            description (str): Description
            config_version (str): Config version
            config_tag (str): Config tag
            values (dict): Overrides values used to create configuration
        """
        super().__init__(instance_id)
        self.name = config_name
        self.template_name = template_name
        self.config_version = str(config_version)
        self.config_tag = config_tag
        self.description = description
        self.values = values

    @property
    def url(self) -> str:
        """URL address for Configuration calls.

        Returns:
            str: URL to Configuration

        """
        return f"{self.base_url_and_version()}/instance/{self.instance_id}/config/{self.name}"

    def rollback_to(self, config_version: str, config_tag: str) -> None:
        """Rollback configuration to specific version.

        Args:
            config_version (str): version of configuration
            config_tag (str): tag of configuration

        """
        url: str = f"{self.url}/rollback"

        params = {}
        if config_version is not None:
            params["config-version"] = config_version
        if config_tag is not None:
            params["config-tag"] = config_tag
        self.send_message_json(
            "POST",
            "Rollback Configuration",
            url,
            data=json.dumps(params),
            headers={}
        )
        self.config_version = config_version
        self.config_tag = config_tag

    def update(self, override_values: dict) -> "Configuration":
        """Update configuration.

        Args:
            override_values (dict): Override values

        Returns:
            Configuration: Updated object

        """
        body = json.dumps(override_values)

        config: dict = self.send_message_json(
            "PUT",
            "Update configuration",
            self.url,
            data=jinja_env().get_template("multicloud_k8s_create_configuration_for_"
                                          "instance.json.j2").render(
                                              config_name=self.name,
                                              template_name=self.template_name,
                                              description=self.description,
                                              override_values=body
                                          )
        )
        return self.get_config_by_version(str(config["config-version"]))

    def tag_config_version(self, config_tag: str) -> None:
        """Tag configuration.

        Args:
            config_tag (str): Tag name of the configuration version

        """
        body = json.dumps({"tag-name": config_tag})

        self.send_message(
            "POST",
            "Tag configuration",
            f"{self.url}/tagit",
            data=body
        )

    def get_config_by_version(self, config_version: str) -> "Configuration":
        """Get configuration by version.

        Args:
            config_version (str): Config version

        Returns:
            Configuration: object

        """
        config: dict = self.send_message_json(
            "GET",
            "Get Configuration by version",
            f"{self.url}/version/{config_version}"
        )
        return self.__class__(
            self.instance_id,
            self.name,
            config["template-name"],
            config["description"],
            config["config-version"],
            config["config-tag"],
            config["values"]
        )

    def get_config_versions(self) -> Iterator["Configuration"]:
        """Get List of configuration versions.

        Returns:
            List of versions for configuration

        """
        for config in self.send_message_json("GET",
                                             "Get config versions",
                                             f"{self.url}/version"):
            yield self.__class__(
                self.instance_id,
                self.name,
                config["template-name"],
                config["description"],
                config["config-version"],
                config["config-tag"],
                config["values"]
            )

    def get_config_by_tag(self, config_tag: str) -> "Configuration":
        """Get configuration by tag.

        Args:
            config_tag (str): Name of tag

        Returns:
            Configuration: object

        """
        config: dict = self.send_message_json(
            "GET",
            "Get Configuration by tag",
            f"{self.url}/tag/{config_tag}"
        )
        return self.__class__(
            self.instance_id,
            self.name,
            config["template-name"],
            config["description"],
            config["config-version"],
            config["config-tag"],
            config["values"]
        )

    def get_config_tags(self) -> Iterator["ConfigurationTag"]:
        """Get List of Tags.

        Returns:
            List of tags for configuration

        """
        for tag in self.send_message_json("GET",
                                          "Get config tags",
                                          f"{self.url}/tag"):
            yield ConfigurationTag(
                config_tag=tag["config-tag"],
                config_version=str(tag["config-version"])
            )

    def create_delete_version(self) -> "Configuration":
        """Create delete version of configuration."""
        url: str = f"{self.url}/delete"

        config: dict = self.send_message_json(
            "POST",
            "Delete Resources Configuration",
            url
        )
        return self.__class__(
            self.instance_id,
            self.name,
            config["template-name"],
            config["description"],
            config["config-version"],
            config["config-tag"],
            config["values"]
        )

    def delete_without_resources(self) -> None:
        """Delete Instance Based object."""
        self.send_message(
            "DELETE",
            f"Delete {self.__class__.__name__}",
            f"{self.url}?deleteConfigOnly=true"
        )


@dataclass
class InstanceStatus:
    """Class to store status of the Instance."""

    instance_id: str
    request: InstantiationRequest
    resource_count: str
    ready: bool
    resources_status: list


class Instance(InstanceBase, QueryResourceStatusMixin):
    """Instance class."""

    config_class = Configuration
    request_class = InstantiationRequest

    def __init__(self, instance_id: str,
                 namespace: str,
                 request: InstantiationRequest,
                 resources: dict = None,
                 override_values: dict = None) -> None:
        """Instance object initialization.

        Args:
            instance_id (str): instance ID
            namespace (str): namespace that instance is created in
            request (InstantiationRequest): datails of the instantiation request
            resources (dict): Created resources
            override_values (dict): Optional values
        """
        super().__init__(instance_id)
        self.namespace: str = namespace
        self.request: InstantiationRequest = request
        self.resources: dict = resources
        self.override_values: dict = override_values

    @classmethod
    def get_all(cls) -> Iterator["Instance"]:
        """Get all instantiated Kubernetes resources.

        Yields:
            Instantiation: Instantiation object

        """
        for resource in cls.send_message_json("GET",
                                              "Get Kubernetes resources",
                                              f"{cls.base_url_and_version()}/instance"):
            yield cls(
                instance_id=resource["id"],
                namespace=resource["namespace"],
                request=cls.request_class(resource["request"])
            )

    @classmethod
    def get_by_id(cls, instance_id: str) -> "Instance":
        """Get Kubernetes resource by id.

        Args:
            instance_id (str): instance ID

        Returns:
            Instantiation: Instantiation object

        """
        url: str = f"{cls.base_url_and_version()}/instance/{instance_id}"
        resource: dict = cls.send_message_json(
            "GET",
            "Get Kubernetes resource by id",
            url
        )
        return cls(
            instance_id=resource["id"],
            namespace=resource["namespace"],
            request=cls.request_class(resource["request"]),
            resources=resource["resources"],
            override_values=resource.get("override-values")
        )

    @classmethod
    def create(cls,
               cloud_region_id: str,
               profile_name: str,
               rb_name: str,
               rb_version: str,
               override_values: dict = None,
               labels: dict = None) -> "Instance":
        """Create Instance.

        Args:
            cloud_region_id (str): Cloud region ID
            profile_name (str): Name of profile to be instantiated
            rb_name: (bytes): Definition name
            rb_version (str): Definition version
            override_values (dict): List of optional override values
            labels (dict): List of optional labels

        Returns:
            Instance: Created object

        """
        if labels is None:
            labels = {}
        if override_values is None:
            override_values = {}
        url: str = f"{cls.base_url_and_version()}/instance"
        response: dict = cls.send_message_json(
            "POST",
            "Create Instance",
            url,
            data=jinja_env().get_template("multicloud_k8s_instantiate.json.j2").render(
                cloud_region_id=cloud_region_id,
                profile_name=profile_name,
                rb_name=rb_name,
                rb_version=rb_version,
                override_values=override_values,
                labels=labels),
            headers={}
        )
        return cls(
            instance_id=response["id"],
            namespace=response["namespace"],
            request=cls.request_class(response["request"]),
            resources=response["resources"],
            override_values=response.get("override-values")
        )

    def upgrade(self,
                cloud_region_id: str,
                profile_name: str,
                rb_name: str,
                rb_version: str,
                override_values: dict = None,
                labels: dict = None) -> "Instance":
        """Upgrade Instance.

        Args:
            cloud_region_id (str): Cloud region ID
            profile_name (str): Name of profile to be instantiated
            rb_name: (bytes): Definition name
            rb_version (str): Definition version
            override_values (dict): List of optional override values
            labels (dict): List of optional labels

        Returns:
            Instance: Created object

        """
        if labels is None:
            labels = {}
        if override_values is None:
            override_values = {}
        url: str = f"{self.url}/upgrade"
        response: dict = self.send_message_json(
            "POST",
            "Upgrade Instance",
            url,
            data=jinja_env().get_template("multicloud_k8s_instantiate.json.j2").render(
                cloud_region_id=cloud_region_id,
                profile_name=profile_name,
                rb_name=rb_name,
                rb_version=rb_version,
                override_values=override_values,
                labels=labels),
            headers={}
        )
        return self.__class__(
            instance_id=response["id"],
            namespace=response["namespace"],
            request=self.request_class(response["request"]),
            resources=response["resources"],
            override_values=response.get("override-values")
        )

    def create_configuration(self, config_name: str,
                             template_name: str,
                             override_values: dict = None,
                             description="") -> "Configuration":
        """Create configuration instance.

        Args:
            config_name (str): Name of the configuration
            template_name (str): Name of the template
            description (str): Description
            override_values (dict): Override values

        Returns:
            Configuration: Created object

        """
        url: str = f"{self.url}/config"

        body = json.dumps(override_values)

        self.send_message(
            "POST",
            "Create configuration",
            url,
            data=jinja_env().get_template("multicloud_k8s_create_configuration_for_"
                                          "instance.json.j2").render(
                                              config_name=config_name,
                                              template_name=template_name,
                                              description=description,
                                              override_values=body
                                          )
        )

        return self.get_configuration_by_name(config_name)

    def get_all_configurations(self) -> Iterator["Configuration"]:
        """Get List of configurations.

        Returns:
            List of configurations

        """
        for config in self.send_message_json("GET",
                                             "Get all configurations",
                                             f"{self.url}/config"):
            yield self.config_class(
                self.instance_id,
                config["config-name"],
                config["template-name"],
                config["description"],
                config["config-version"],
                config["config-tag"],
                config["values"]
            )

    def get_configuration_by_name(self, config_name: str) -> "Configuration":
        """Get configuration.

        Args:
            config_name (str): Name of the configuration

        Returns:
            Configuration: object

        """
        url: str = f"{self.url}/config/{config_name}"

        config: dict = self.send_message_json(
            "GET",
            "Get Configuration by name",
            url
        )
        return self.config_class(
            self.instance_id,
            config_name,
            config["template-name"],
            config["description"],
            config["config-version"],
            config["config-tag"],
            config["values"]
        )

    def get_status(self) -> "InstanceStatus":
        """Get instance status.

        Returns:
            Status of the instance

        """
        status: dict = self.send_message_json(
            "GET",
            "Get status",
            f"{self.url}/status"
        )
        resources_status = []
        for res_status in status["resourcesStatus"]:
            resources_status.append(ResourceStatus(res_status))
        return InstanceStatus(
            self.instance_id,
            request=self.request_class(status["request"]),
            resource_count=int(status["resourceCount"]),
            ready=bool(status["ready"]),
            resources_status=resources_status
        )

    def query_status(self,
                     kind: str,
                     api_version: str,
                     name: str = None,
                     labels: dict = None) -> "InstanceStatus":
        """Query instance status.

        Args:
            kind (str): Kind of k8s resource
            api_version (str): Api version of k8s resource
            name (str): Name of k8s resource
            labels (dict): Lables of k8s resource

        Returns:
            Filtered status of the instance

        """
        url = f"{self.url}/query"
        status: Dict[Any] = self.query_resource_status(url,
                                                       api_version=api_version,
                                                       kind=kind,
                                                       name=name,
                                                       labels=labels)
        return InstanceStatus(
            self.instance_id,
            request=self.request_class(status["request"]),
            resource_count=int(status["resourceCount"]),
            ready=bool(status["ready"]),
            resources_status=[ResourceStatus(res_status) for
                              res_status in status["resourcesStatus"]]
        )