aboutsummaryrefslogtreecommitdiffstats
path: root/src/onapsdk/k8s/definition.py
blob: 305bca2adef4f23b47f5a0e9b1efd8c670fbacbb (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
"""Definition 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 typing import Iterator
from dataclasses import dataclass
from onapsdk.utils.jinja import jinja_env
from .k8splugin_service import GVK, RemovableK8sPlugin


# pylint: disable=too-many-arguments, too-few-public-methods
class DefinitionBase(RemovableK8sPlugin):
    """DefinitionBase class."""

    def __init__(self, rb_name: str,
                 rb_version: str) -> None:
        """Definition-Base object initialization.

        Args:
            rb_name (str): Definition name
            rb_version (str): Definition version
        """
        super().__init__()
        self.rb_name: str = rb_name
        self.rb_version: str = rb_version

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

        Returns:
            str: URL to RB Definition

        """
        return f"{self.base_url_and_version()}/rb/definition/{self.rb_name}/{self.rb_version}"

    def upload_artifact(self, package: bytes = None):
        """Upload artifact.

        Args:
            package (bytes): Artifact to be uploaded to multicloud-k8s plugin

        """
        url: str = f"{self.url}/content"
        self.send_message(
            "POST",
            "Upload Artifact content",
            url,
            data=package,
            headers={}
        )


@dataclass
class Profile(DefinitionBase):
    """Profile class."""

    def __init__(self, rb_name: str,
                 rb_version: str,
                 profile_name: str,
                 namespace: str,
                 kubernetes_version: str,
                 labels: dict = None,
                 release_name: str = None,
                 extra_resource_types: list = None) -> None:
        """Profile object initialization.

        Args:
            rb_name (str): Definition name
            rb_version (str): Definition version
            profile_name (str): Name of profile
            release_name (str): Release name, if release_name is not provided,
            namespace (str): Namespace that service is created in
            kubernetes_version (str): Required Kubernetes version
            labels (dict): Extra Labels for k8s resources
            extra_resource_types (list): Extra k8s resources types (GVK) for status monitoring
        """
        super().__init__(rb_name, rb_version)
        self.profile_name: str = profile_name
        if release_name is None:
            release_name = profile_name
        self.release_name: str = release_name
        self.namespace: str = namespace
        self.kubernetes_version: str = kubernetes_version
        self.labels: dict = labels
        if self.labels is None:
            self.labels = {}
        self.extra_resource_types: dict = extra_resource_types
        if self.extra_resource_types is None:
            self.extra_resource_types = {}

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

        Returns:
            str: URL to RB Profile

        """
        return f"{self.base_url_and_version()}/rb/definition/{self.rb_name}/{self.rb_version}"\
               f"/profile/{self.profile_name}"

    def update(self) -> "Profile":
        """Update Profile for Definition.

        Returns:
            Profile: Updated object

        """
        profile: dict = self.send_message_json(
            "PUT",
            "Update profile for definition",
            self.url,
            data=jinja_env().get_template("multicloud_k8s_create_profile_"
                                          "for_definition.json.j2").render(
                                              rb_name=self.rb_name,
                                              rb_version=self.rb_version,
                                              profile_name=self.profile_name,
                                              release_name=self.release_name,
                                              namespace=self.namespace,
                                              kubernetes_version=self.kubernetes_version,
                                              labels=self.labels,
                                              extra_types=self.extra_resource_types
                                          )
        )
        return self.__class__(
            self.rb_name,
            self.rb_version,
            profile["profile-name"],
            profile["namespace"],
            profile.get("kubernetes-version"),
            profile.get("labels"),
            profile.get("release-name")
        )


@dataclass
class ConfigurationTemplate(DefinitionBase):
    """ConfigurationTemplate class."""

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

        Returns:
            str: URL to Configuration template in Multicloud-k8s API.

        """
        return f"{self.base_url_and_version()}/rb/definition/{self.rb_name}/{self.rb_version}"\
               f"/config-template/{self.template_name}"

    def __init__(self, rb_name: str,
                 rb_version: str,
                 template_name: str,
                 description: str,
                 chart_name="",
                 has_content=False) -> None:
        """Configuration-Template object initialization.

        Args:
            rb_name (str): Definition name
            rb_version (str): Definition version
            template_name (str): Configuration template name
            description (str): Namespace that service is created in
            chart_name (str): Name of the charft of uploaded content
            has_content (bool): If false cotent is taken fro mthe main definition
        """
        super().__init__(rb_name, rb_version)
        self.template_name: str = template_name
        self.description: str = description
        self.chart_name: str = chart_name
        self.has_content: bool = has_content

    def update(self) -> "ConfigurationTemplate":
        """Update Configuration Template for Definition.

        Returns:
            ConfigurationTemplate: Updated object

        """
        template: dict = self.send_message_json(
            "PUT",
            "Update config template for definition",
            self.url,
            data=jinja_env().get_template("multicloud_k8s_create_configuration_"
                                          "template.json.j2").render(
                                              template_name=self.template_name,
                                              description=self.description
                                          )
        )
        return self.__class__(
            self.rb_name,
            self.rb_version,
            template["template-name"],
            template.get("description"),
            template.get("chart-name"),
            template.get("has-content")
        )


@dataclass
class Definition(DefinitionBase):
    """Definition class."""

    profile_class = Profile
    config_template_class = ConfigurationTemplate

    def __init__(self, rb_name: str,
                 rb_version: str,
                 chart_name: str,
                 description: str,
                 labels: dict) -> None:
        """Definition object initialization.

        Args:
            rb_name (str): Definition name
            rb_version (str): Definition version
            chart_name (str): Chart name, optional field, will be detected if it is not provided
            description (str): Definition description
            labels (str): Labels
        """
        super().__init__(rb_name, rb_version)
        self.chart_name: str = chart_name
        self.description: str = description
        self.labels: dict = labels

    @classmethod
    def get_all(cls):
        """Get all definitions.

        Yields:
            Definition: Definition object

        """
        for definition in cls.send_message_json("GET",
                                                "Get definitions",
                                                f"{cls.base_url_and_version()}/rb/definition"):
            yield cls(
                definition["rb-name"],
                definition["rb-version"],
                definition.get("chart-name"),
                definition.get("description"),
                definition.get("labels")
            )

    @classmethod
    def get_definition_by_name_version(cls, rb_name: str, rb_version: str) -> "Definition":
        """Get definition by it's name and version.

        Args:
            rb_name (str): definition name
            rb_version (str): definition version

        Returns:
            Definition: Definition object

        """
        url: str = f"{cls.base_url_and_version()}/rb/definition/{rb_name}/{rb_version}"
        definition: dict = cls.send_message_json(
            "GET",
            "Get definition",
            url
        )
        return cls(
            definition["rb-name"],
            definition["rb-version"],
            definition.get("chart-name"),
            definition.get("description"),
            definition.get("labels")
        )

    @classmethod
    def create(cls, rb_name: str,
               rb_version: str,
               chart_name: str = "",
               description: str = "",
               labels=None) -> "Definition":
        """Create Definition.

        Args:
            rb_name (str): Definition name
            rb_version (str): Definition version
            chart_name (str): Chart name, optional field, will be detected if it is not provided
            description (str): Definition description
            labels (str): Labels

        Returns:
            Definition: Created object

        """
        if labels is None:
            labels = {}
        url: str = f"{cls.base_url_and_version()}/rb/definition"
        cls.send_message(
            "POST",
            "Create definition",
            url,
            data=jinja_env().get_template("multicloud_k8s_add_definition.json.j2").render(
                rb_name=rb_name,
                rb_version=rb_version,
                chart_name=chart_name,
                description=description,
                labels=labels
            )
        )
        return cls.get_definition_by_name_version(rb_name, rb_version)

    def update(self) -> "Definition":
        """Update Definition.

        Returns:
            Definition: Updated object

        """
        self.send_message(
            "PUT",
            "Update definition",
            self.url,
            data=jinja_env().get_template("multicloud_k8s_add_definition.json.j2").render(
                rb_name=self.rb_name,
                rb_version=self.rb_version,
                chart_name=self.chart_name,
                description=self.description,
                labels=self.labels
            )
        )
        return self.get_definition_by_name_version(self.rb_name, self.rb_version)

    def create_profile(self, profile_name: str,
                       namespace: str,
                       kubernetes_version: str,
                       release_name: str = None,
                       labels: dict = None,
                       extra_resource_types: list = None) -> "Profile":
        """Create Profile for Definition.

        Args:
            profile_name (str): Name of profile
            namespace (str): Namespace that service is created in
            kubernetes_version (str): Required Kubernetes version
            release_name (str): Release name
            labels (dict): Extra labels to assign for each
            extra_resource_types (list): GVK list for extra k8s resource types to check status

        Returns:
            Profile: Created object

        """
        url: str = f"{self.url}/profile"
        if release_name is None:
            release_name = profile_name
        if labels is None:
            labels = {}
        if extra_resource_types is None:
            extra_resource_types = []
        self.send_message(
            "POST",
            "Create profile for definition",
            url,
            data=jinja_env().get_template("multicloud_k8s_create_profile_"
                                          "for_definition.json.j2").render(
                                              rb_name=self.rb_name,
                                              rb_version=self.rb_version,
                                              profile_name=profile_name,
                                              release_name=release_name,
                                              namespace=namespace,
                                              kubernetes_version=kubernetes_version,
                                              labels=labels,
                                              extra_types=extra_resource_types
                                          )
        )
        return self.get_profile_by_name(profile_name)

    def get_all_profiles(self) -> Iterator["Profile"]:
        """Get all profiles.

        Yields:
            Profile: Profile object

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

        for profile in self.send_message_json("GET",
                                              "Get profiles",
                                              url):
            yield self.profile_class(
                profile["rb-name"],
                profile["rb-version"],
                profile["profile-name"],
                profile["namespace"],
                profile.get("kubernetes-version"),
                profile.get("labels"),
                profile.get("release-name"),
                GVK.to_list_of_gvk(profile.get("extra-resource-types"))
            )

    def get_profile_by_name(self, profile_name: str) -> "Profile":
        """Get profile by it's name.

        Args:
            profile_name (str): profile name

        Returns:
            Profile: Profile object

        """
        url: str = f"{self.url}/profile/{profile_name}"

        profile: dict = self.send_message_json(
            "GET",
            "Get profile",
            url
        )
        return self.profile_class(
            profile["rb-name"],
            profile["rb-version"],
            profile["profile-name"],
            profile["namespace"],
            profile.get("kubernetes-version"),
            profile.get("labels"),
            profile.get("release-name"),
            GVK.to_list_of_gvk(profile.get("extra-resource-types"))
        )

    def get_all_configuration_templates(self):
        """Get all configuration templates.

        Yields:
            ConfigurationTemplate: ConfigurationTemplate object

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

        for template in self.send_message_json("GET",
                                               "Get configuration templates",
                                               url):
            yield self.config_template_class(
                self.rb_name,
                self.rb_version,
                template["template-name"],
                template.get("description"),
                template.get("chart-name"),
                template.get("has-content")
            )

    def create_configuration_template(self, template_name: str,
                                      description="") -> "ConfigurationTemplate":
        """Create configuration template.

        Args:
            template_name (str): Name of the template
            description (str): Description

        Returns:
            ConfigurationTemplate: Created object

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

        self.send_message(
            "POST",
            "Create configuration template",
            url,
            data=jinja_env().get_template("multicloud_k8s_create_configuration_"
                                          "template.json.j2").render(
                                              template_name=template_name,
                                              description=description
                                          )
        )

        return self.get_configuration_template_by_name(template_name)

    def get_configuration_template_by_name(self, template_name: str) -> "ConfigurationTemplate":
        """Get configuration template.

        Args:
            template_name (str): Name of the template

        Returns:
            ConfigurationTemplate: object

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

        template: dict = self.send_message_json(
            "GET",
            "Get Configuration template",
            url
        )
        return self.config_template_class(
            self.rb_name,
            self.rb_version,
            template["template-name"],
            template.get("description"),
            template.get("chart-name"),
            template.get("has-content")
        )