-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathcluster_service_2_x_tkgm.py
2988 lines (2658 loc) · 139 KB
/
cluster_service_2_x_tkgm.py
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# container-service-extension
# Copyright (c) 2021 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause
import base64
import copy
from dataclasses import asdict
import random
import re
import string
import threading
from typing import Dict, List, Optional, Tuple, Union
import urllib
import pkg_resources
import pyvcloud.vcd.client as vcd_client
import pyvcloud.vcd.org as vcd_org
import pyvcloud.vcd.task as vcd_task
import pyvcloud.vcd.vapp as vcd_vapp
from pyvcloud.vcd.vdc import VDC
import pyvcloud.vcd.vm as vcd_vm
import validators
from container_service_extension.common.constants.server_constants import \
CLOUDINIT_GUEST_USERDATA, \
CLOUDINIT_GUEST_USERDATA_ENCODING, \
CorePkgVersionKeys, \
CPI_DEFAULT_VERSION, \
CPI_NAME, \
CSI_DEFAULT_VERSION, \
CSI_NAME, \
DEFAULT_POST_CUSTOMIZATION_TIMEOUT_SEC, \
DISK_ENABLE_UUID, \
PostCustomizationKubeconfig
from container_service_extension.common.constants.server_constants import ClusterMetadataKey # noqa: E501
from container_service_extension.common.constants.server_constants import ClusterScriptFile # noqa: E501
from container_service_extension.common.constants.server_constants import DefEntityOperation # noqa: E501
from container_service_extension.common.constants.server_constants import DefEntityOperationStatus # noqa: E501
from container_service_extension.common.constants.server_constants import DefEntityPhase # noqa: E501
from container_service_extension.common.constants.server_constants import KUBE_CONFIG # noqa: E501
from container_service_extension.common.constants.server_constants import KUBEADM_TOKEN_INFO # noqa: E501
from container_service_extension.common.constants.server_constants import LocalTemplateKey # noqa: E501
from container_service_extension.common.constants.server_constants import NodeType # noqa: E501
from container_service_extension.common.constants.server_constants import PostCustomizationPhase # noqa: E501
from container_service_extension.common.constants.server_constants import PostCustomizationVersions # noqa: E501
from container_service_extension.common.constants.server_constants import ThreadLocalData # noqa: E501
from container_service_extension.common.constants.server_constants import TKGM_DEFAULT_POD_NETWORK_CIDR # noqa: E501
from container_service_extension.common.constants.server_constants import TKGM_DEFAULT_SERVICE_CIDR # noqa: E501
from container_service_extension.common.constants.server_constants import TkgmNodeSizing # noqa: E501
from container_service_extension.common.constants.server_constants import TKGmProxyKey # noqa: E501
import container_service_extension.common.constants.shared_constants as shared_constants # noqa: E501
from container_service_extension.common.constants.shared_constants import \
CSE_PAGINATION_DEFAULT_PAGE_SIZE, SYSTEM_ORG_NAME
from container_service_extension.common.constants.shared_constants import CSE_PAGINATION_FIRST_PAGE_NUMBER # noqa: E501
import container_service_extension.common.thread_local_data as thread_local_data # noqa: E501
import container_service_extension.common.utils.core_utils as utils
import container_service_extension.common.utils.pyvcloud_utils as vcd_utils
from container_service_extension.common.utils.script_utils import get_cluster_script_file_contents # noqa: E501
import container_service_extension.common.utils.server_utils as server_utils
import container_service_extension.common.utils.thread_utils as thread_utils
import container_service_extension.exception.exceptions as exceptions
import container_service_extension.lib.oauth_client.oauth_service as oauth_service # noqa: E501
import container_service_extension.lib.telemetry.constants as telemetry_constants # noqa: E501
import container_service_extension.lib.telemetry.telemetry_handler as telemetry_handler # noqa: E501
from container_service_extension.lib.tokens_client.tokens_service import TokensService # noqa: E501
from container_service_extension.logging.logger import NULL_LOGGER
from container_service_extension.logging.logger import SERVER_CLOUDAPI_WIRE_LOGGER # noqa: E501
from container_service_extension.logging.logger import SERVER_LOGGER as LOGGER
from container_service_extension.mqi.consumer.mqtt_publisher import MQTTPublisher # noqa: E501
import container_service_extension.rde.acl_service as acl_service
import container_service_extension.rde.backend.common.network_expose_helper as nw_exp_helper # noqa: E501
from container_service_extension.rde.behaviors.behavior_model import BehaviorError, BehaviorTaskStatus # noqa: E501
import container_service_extension.rde.common.entity_service as def_entity_svc
import container_service_extension.rde.constants as def_constants
import container_service_extension.rde.models.common_models as common_models
import container_service_extension.rde.models.rde_2_1_0 as rde_2_x
import container_service_extension.rde.utils as def_utils
from container_service_extension.security.context.behavior_request_context import RequestContext # noqa: E501
import container_service_extension.security.context.operation_context as operation_context # noqa: E501
import container_service_extension.server.abstract_broker as abstract_broker
import container_service_extension.server.compute_policy_manager as compute_policy_manager # noqa: E501
DEFAULT_API_VERSION = vcd_client.ApiVersion.VERSION_36.value
# Hardcode the Antrea CNI version until there's a better way to retrieve it
CNI_NAME = "antrea"
CLUSTER_CREATE_OPERATION_MESSAGE = 'Cluster create'
CLUSTER_RESIZE_OPERATION_MESSAGE = 'Cluster resize'
CLUSTER_DELETE_OPERATION_MESSAGE = 'Cluster delete'
DOWNLOAD_KUBECONFIG_OPERATION_MESSAGE = 'Download kubeconfig'
class ClusterService(abstract_broker.AbstractBroker):
"""Handles cluster operations for native DEF based clusters."""
def __init__(self, ctx: RequestContext):
self.context: Optional[operation_context.OperationContext] = None
# populates above attributes
super().__init__(ctx.op_ctx)
# TODO find an elegant way to dynamically pick the module rde_2_x
self.task = None
self.task_resource = None
self.task_id = ctx.task_id
client_v36 = self.context.get_client(api_version=DEFAULT_API_VERSION)
self.task_href = client_v36.get_api_uri() + f"/task/{self.task_id}"
self.task_status = None
self.entity_id = ctx.entity_id
self.mqtt_publisher: MQTTPublisher = ctx.mqtt_publisher
cloudapi_client_v36 = self.context.get_cloudapi_client(
api_version=DEFAULT_API_VERSION)
self.entity_svc = def_entity_svc.DefEntityService(
cloudapi_client=cloudapi_client_v36)
sysadmin_cloudapi_client_v36 = \
self.context.get_sysadmin_cloudapi_client(
api_version=DEFAULT_API_VERSION)
self.sysadmin_entity_svc = def_entity_svc.DefEntityService(
cloudapi_client=sysadmin_cloudapi_client_v36)
def get_cluster_info(self, cluster_id: str) -> common_models.DefEntity:
"""Get the corresponding defined entity of the native cluster.
This method ensures to return the latest state of the cluster vApp.
It syncs the defined entity with the state of the cluster vApp before
returning the defined entity.
"""
telemetry_handler.record_user_action_details(
cse_operation=telemetry_constants.CseOperation.V36_CLUSTER_INFO,
cse_params={
telemetry_constants.PayloadKey.CLUSTER_ID: cluster_id,
telemetry_constants.PayloadKey.SOURCE_DESCRIPTION: thread_local_data.get_thread_local_data(ThreadLocalData.USER_AGENT) # noqa: E501
}
)
return self._sync_def_entity(cluster_id)
def get_clusters_by_page(self, filters: dict = None,
page_number=CSE_PAGINATION_FIRST_PAGE_NUMBER,
page_size=CSE_PAGINATION_DEFAULT_PAGE_SIZE):
"""List clusters by page number and page size.
:param dict filters: filters to use to filter the cluster response
:param int page_number: page number of the clusters to be fetched
:param int page_size: page size of the result
:return: paginated response containing native clusters
:rtype: dict
"""
if not filters:
filters = {}
ent_type: common_models.DefEntityType = server_utils.get_registered_def_entity_type() # noqa: E501
return self.entity_svc.get_entities_per_page_by_entity_type(
vendor=ent_type.vendor,
nss=ent_type.nss,
version=ent_type.version,
filters=filters,
page_number=page_number,
page_size=page_size)
def list_clusters(self, filters: dict = None) -> list:
"""List corresponding defined entities of all native clusters.
:param dict filters: filters to use to filter the cluster response
:return: list of all native clusters
:rtype: list
"""
if not filters:
filters = {}
ent_type: common_models.DefEntityType = server_utils.get_registered_def_entity_type() # noqa: E501
return self.entity_svc.list_entities_by_entity_type(
vendor=ent_type.vendor,
nss=ent_type.nss,
version=ent_type.version,
filters=filters)
def get_cluster_config(self, cluster_id: str):
"""Get the cluster's kube config contents.
:param str cluster_id:
:return: Dictionary containing cluster config.
:rtype: dict
"""
curr_rde = self.entity_svc.get_entity(cluster_id)
curr_native_entity: rde_2_x.NativeEntity = curr_rde.entity
if curr_rde.state != def_constants.DEF_RESOLVED_STATE:
msg = f"Cluster {curr_rde.name} with id {cluster_id} is " \
"not in a valid state for this operation. " \
"Please contact the administrator"
LOGGER.error(msg)
raise exceptions.CseServerError(msg)
msg = f"{DOWNLOAD_KUBECONFIG_OPERATION_MESSAGE} ({cluster_id})"
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
# Get kube config from RDE
kube_config = None
if hasattr(curr_native_entity.status,
shared_constants.RDEProperty.PRIVATE.value) and \
hasattr(curr_native_entity.status.private,
shared_constants.RDEProperty.KUBE_CONFIG.value):
kube_config = curr_native_entity.status.private.kube_config
if not kube_config:
msg = "Failed to get cluster kube-config"
LOGGER.error(msg)
raise exceptions.ClusterOperationError(msg)
return self.mqtt_publisher.construct_behavior_payload(
message=kube_config,
status=BehaviorTaskStatus.SUCCESS.value)
def create_cluster(self, entity_id: str, input_native_entity: rde_2_x.NativeEntity): # noqa: E501
"""Start the cluster creation operation.
Creates corresponding defined entity in vCD for every native cluster.
Updates the defined entity with new properties after the cluster
creation.
**telemetry: Optional
:return: dictionary representing mqtt response published
:rtype: dict
"""
cluster_name: Optional[str] = None
org_name: Optional[str] = None
ovdc_name: Optional[str] = None
curr_rde: Optional[Union[common_models.DefEntity, Tuple[common_models.DefEntity, dict]]] = None # noqa: E501
try:
cluster_name = input_native_entity.metadata.name
org_name = input_native_entity.metadata.org_name
ovdc_name = input_native_entity.metadata.virtual_data_center_name
template_name = input_native_entity.spec.distribution.template_name
template_revision = 1 # templateRevision for TKGm is always 1
vcd_site = input_native_entity.metadata.site
# check that the vcd site is a valid url
if not _is_valid_vcd_url(vcd_site):
raise exceptions.CseServerError(
f"'{vcd_site}' should have a https scheme"
f" and match CSE server config file.")
# check that cluster name is syntactically valid
if not _is_valid_cluster_name(cluster_name):
raise exceptions.CseServerError(
f"Invalid cluster name '{cluster_name}'")
# Check that cluster name doesn't already exist.
# Do not replace the below with the check to verify if defined
# entity already exists. It will not give accurate result as even
# sys-admin cannot view all the defined entities unless
# native entity type admin view right is assigned.
client_v36 = \
self.context.get_client(api_version=DEFAULT_API_VERSION)
if _cluster_exists(client_v36, cluster_name,
org_name=org_name,
ovdc_name=ovdc_name):
raise exceptions.ClusterAlreadyExistsError(
f"Cluster '{cluster_name}' already exists.")
# check that requested/default template is valid
template = _get_tkgm_template(template_name)
k8_distribution = rde_2_x.Distribution(
template_name=template_name,
template_revision=1,
)
cloud_properties = rde_2_x.CloudProperties(
distribution=k8_distribution,
org_name=org_name,
virtual_data_center_name=ovdc_name,
ovdc_network_name=input_native_entity.spec.settings.ovdc_network, # noqa: E501
rollback_on_failure=input_native_entity.spec.settings.rollback_on_failure, # noqa: E501
ssh_key=input_native_entity.spec.settings.ssh_key
)
msg = f"Creating cluster '{cluster_name}' " \
f"from template '{template_name}' " \
f"(revision {template_revision})"
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
changes = {
'entity.status.phase':
str(DefEntityPhase(DefEntityOperation.CREATE,
DefEntityOperationStatus.IN_PROGRESS)),
'entity.status.kubernetes': _create_k8s_software_string(
template[LocalTemplateKey.KUBERNETES],
template[LocalTemplateKey.KUBERNETES_VERSION]),
'entity.status.os': template[LocalTemplateKey.OS],
'entity.status.cloud_properties': cloud_properties,
'entity.status.uid': entity_id,
'entity.status.task_href': self.task_href,
'entity.status.site': vcd_site,
}
try:
curr_rde = self._update_cluster_entity(entity_id, changes=changes) # noqa: E501
except Exception:
msg = f"Error updating the cluster '{cluster_name}' with the status" # noqa: E501
LOGGER.error(msg)
raise
# trigger async operation
self.context.is_async = True
self._create_cluster_async(entity_id, input_native_entity)
return self.mqtt_publisher.construct_behavior_payload(
message=f"{CLUSTER_CREATE_OPERATION_MESSAGE} ({entity_id})",
status=BehaviorTaskStatus.RUNNING.value,
progress=5)
except Exception as err:
create_failed_msg = f"Failed to create cluster {cluster_name} in org {org_name} and VDC {ovdc_name}" # noqa: E501
LOGGER.error(create_failed_msg, exc_info=True)
# Since defined entity is already created by defined entity
# framework, we need to delete the defined entity if rollback
# is set to true
# NOTE: As per schema definition, default value for rollback is
# True
if input_native_entity.spec.settings.rollback_on_failure:
try:
# TODO can reduce try - catch by raising more specific
# exceptions
# Resolve entity state manually (PRE_CREATED --> RESOLVED/RESOLUTION_ERROR) # noqa: E501
# to allow delete operation
self.sysadmin_entity_svc.resolve_entity(entity_id=entity_id) # noqa: E501
# delete defined entity
self.sysadmin_entity_svc.delete_entity(
entity_id,
invoke_hooks=False)
except Exception:
msg = f"Failed to delete defined entity for cluster " \
f"{cluster_name} ({entity_id} with state " \
f"({curr_rde.state})"
LOGGER.error(msg, exc_info=True)
else:
# update status to CREATE:FAILED
try:
self._fail_operation(entity_id, DefEntityOperation.CREATE)
except Exception:
msg = f"Failed to update defined entity status for" \
f" cluster {cluster_name}({entity_id})"
LOGGER.error(f"{msg}", exc_info=True)
self._update_task(BehaviorTaskStatus.ERROR,
message=create_failed_msg,
error_message=str(err))
raise
def resize_cluster(self, cluster_id: str,
input_native_entity: rde_2_x.NativeEntity):
"""Start the resize cluster operation.
:param str cluster_id: Defined entity Id of the cluster
:param DefEntity input_native_entity: Input cluster spec
:return: DefEntity of the cluster with the updated operation status
and task_href.
:rtype: dict
"""
# TODO: Make use of current entity in the behavior payload
# NOTE: It is always better to do a get on the entity to make use of
# existing entity status. This guarantees that operations performed
# are relevant.
curr_rde: common_models.DefEntity = self.entity_svc.get_entity(cluster_id) # noqa: E501
curr_native_entity: rde_2_x.NativeEntity = curr_rde.entity
state: str = curr_rde.state
cluster_name: str = curr_rde.name
current_spec: rde_2_x.ClusterSpec = \
def_utils.construct_cluster_spec_from_entity_status(
curr_native_entity.status,
server_utils.get_rde_version_in_use())
curr_worker_count: int = current_spec.topology.workers.count
phase: DefEntityPhase = DefEntityPhase.from_phase(
curr_native_entity.status.phase)
# compute the values of workers to be added or removed by
# comparing the desired and the current state. "num_workers_to_add"
# can hold either +ve or -ve value.
desired_worker_count: int = input_native_entity.spec.topology.workers.count # noqa: E501
num_workers_to_add: int = desired_worker_count - curr_worker_count
if desired_worker_count < 0:
raise exceptions.CseServerError(
f"Worker count must be >= 0 (received {desired_worker_count})")
if num_workers_to_add < 0:
raise exceptions.CseServerError(
"Scaling down TKGm cluster is not supported")
# Check for unexposing the cluster
desired_expose_state: bool = \
input_native_entity.spec.settings.network.expose
is_exposed: bool = current_spec.settings.network.expose
unexpose: bool = is_exposed and not desired_expose_state
# Check if the desired worker count is valid and raise
# an exception if the cluster does not need to be unexposed
if not unexpose and num_workers_to_add == 0:
raise exceptions.CseServerError(
f"Cluster '{cluster_name}' already has {desired_worker_count} "
f"workers and is already not exposed.")
# check if cluster is in a valid state
if state != def_constants.DEF_RESOLVED_STATE or phase.is_entity_busy():
# TODO fix the exception type raised
raise exceptions.CseServerError(
f"Cluster {cluster_name} with id {cluster_id} is not in a "
f"valid state to be resized. Please contact the administrator")
# update the task and defined entity.
msg = f"Resizing the cluster '{cluster_name}' ({cluster_id}) to the " \
f"desired worker count {desired_worker_count}"
if unexpose:
msg += " and unexposing the cluster"
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
# set entity status to busy
changes = {
'entity.status.task_href': self.task_href,
'entity.status.phase': str(
DefEntityPhase(DefEntityOperation.UPDATE,
DefEntityOperationStatus.IN_PROGRESS))
}
try:
self._update_cluster_entity(cluster_id, changes=changes)
except Exception as err:
self._update_task(BehaviorTaskStatus.ERROR,
message=msg,
error_message=str(err))
LOGGER.error(str(err))
raise
# trigger async operation
self.context.is_async = True
self._monitor_resize(
cluster_id=cluster_id,
input_native_entity=input_native_entity
)
# TODO(test-resize): verify if multiple messages are not published
# in update_cluster()
return self.mqtt_publisher.construct_behavior_payload(
message=f"{CLUSTER_RESIZE_OPERATION_MESSAGE} ({cluster_id})",
status=BehaviorTaskStatus.RUNNING.value, progress=5)
def delete_cluster(self, cluster_id):
"""Start the delete cluster operation."""
# TODO: Make use of current entity in the behavior payload
# Get entity required here to get the org and vdc in which the cluster
# is present
curr_rde: common_models.DefEntity = self.entity_svc.get_entity(
cluster_id)
curr_native_entity: rde_2_x.NativeEntity = curr_rde.entity
cluster_name: str = curr_rde.name
org_name: str = curr_native_entity.metadata.org_name
ovdc_name: str = curr_native_entity.metadata.virtual_data_center_name
phase: DefEntityPhase = DefEntityPhase.from_phase(
curr_native_entity.status.phase)
# Check if cluster is busy
if phase.is_entity_busy():
raise exceptions.CseServerError(
f"Cluster {cluster_name} with id {cluster_id} is not in a "
f"valid state to be deleted. Please contact administrator.")
# must _update_task here or else self.task_resource is None
# do not logout of sys admin, or else in pyvcloud's session.request()
# call, session becomes None
msg = f"Deleting cluster '{cluster_name}' ({cluster_id})"
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
# Update defined entity of the cluster to delete in-progress state
changes = {
'entity.status.task_href': self.task_href,
'entity.status.phase': str(
DefEntityPhase(DefEntityOperation.DELETE,
DefEntityOperationStatus.IN_PROGRESS))
}
try:
self._update_cluster_entity(cluster_id, changes=changes)
except Exception:
msg = f"Error updating the cluster '{cluster_name}' with the status" # noqa: E501
LOGGER.error(msg)
raise
self.context.is_async = True
# NOTE: The async method will mark the task as succeeded which will
# allow the RDE framework to delete the cluster defined entity
self._delete_cluster_async(cluster_name=cluster_name,
org_name=org_name,
ovdc_name=ovdc_name,
curr_rde=curr_rde)
return self.mqtt_publisher.construct_behavior_payload(
message=f"{CLUSTER_DELETE_OPERATION_MESSAGE} ({cluster_id})",
status=BehaviorTaskStatus.RUNNING.value, progress=5)
def get_cluster_upgrade_plan(self, cluster_id: str) -> List[Dict]:
"""Get the template names/revisions that the cluster can upgrade to.
:param str cluster_id:
:return: A list of dictionaries with keys defined in LocalTemplateKey
:rtype: Null list since TKGm upgrades are not supported yet
"""
return []
def update_cluster(self, cluster_id: str, input_native_entity: rde_2_x.NativeEntity): # noqa: E501
"""Start the update cluster operation (resize or upgrade).
Updating cluster is an asynchronous task, so the returned
`result['task_href']` can be polled to get updates on task progress.
:param str cluster_id: id of the cluster to be updated
:param rde_2_x.NativeEntity input_native_entity: cluster spec with new
worker node count or new kubernetes distribution and revision
:return: dictionary representing mqtt response published
:rtype: dict
"""
# TODO: Make use of current entity in the behavior payload
curr_rde = self.entity_svc.get_entity(cluster_id)
curr_native_entity: rde_2_x.NativeEntity = curr_rde.entity
sysadmin_client_v36 = \
self.context.get_sysadmin_client(DEFAULT_API_VERSION)
vdc: VDC = vcd_utils.get_vdc(
sysadmin_client_v36,
vdc_name=curr_native_entity.status.cloud_properties.virtual_data_center_name, # noqa: E501
org_name=curr_native_entity.status.cloud_properties.org_name)
vdc_resource = vdc.get_resource_admin()
default_cp_name = vdc_resource.DefaultComputePolicy.get('name')
control_plane_sizing_class = curr_native_entity.status.nodes.control_plane.sizing_class # noqa: E501
is_tkgm_with_default_sizing_in_control_plane = \
(control_plane_sizing_class == default_cp_name)
is_tkgm_with_default_sizing_in_workers = \
(len(curr_native_entity.status.nodes.workers) > 0
and curr_native_entity.status.nodes.workers[0].sizing_class == default_cp_name) # noqa: E501
current_spec: rde_2_x.ClusterSpec = \
def_utils.construct_cluster_spec_from_entity_status(
curr_native_entity.status,
server_utils.get_rde_version_in_use(),
is_tkgm_with_default_sizing_in_control_plane=is_tkgm_with_default_sizing_in_control_plane, # noqa: E501
is_tkgm_with_default_sizing_in_workers=is_tkgm_with_default_sizing_in_workers) # noqa: E501
current_workers_count = current_spec.topology.workers.count
desired_workers_count = input_native_entity.spec.topology.workers.count
current_expose_flag = current_spec.settings.network.expose
desired_expose_flag = input_native_entity.spec.settings.network.expose
if (
current_workers_count != desired_workers_count
or current_expose_flag != desired_expose_flag
):
return self.resize_cluster(cluster_id, input_native_entity)
current_template_name = current_spec.distribution.template_name
desired_template_name = input_native_entity.spec.distribution.template_name # noqa: E501
if current_template_name != desired_template_name:
raise Exception(
"Upgrades not supported for TKGm in this version of CSE"
)
nothing_to_do_payload = {
"status": "success",
"result": {
"resultContent": "Nothing to Update"
},
}
return nothing_to_do_payload
def get_cluster_acl_info(self, cluster_id, page: int, page_size: int):
"""Get cluster ACL info based on the defined entity ACL."""
telemetry_params = {
shared_constants.RequestKey.CLUSTER_ID: cluster_id,
shared_constants.PaginationKey.PAGE_NUMBER: page,
shared_constants.PaginationKey.PAGE_SIZE: page_size,
telemetry_constants.PayloadKey.SOURCE_DESCRIPTION: thread_local_data.get_thread_local_data(ThreadLocalData.USER_AGENT) # noqa: E501
}
telemetry_handler.record_user_action_details(
telemetry_constants.CseOperation.V36_CLUSTER_ACL_LIST,
cse_params=telemetry_params)
client_v36 = self.context.get_client(api_version=DEFAULT_API_VERSION)
config = server_utils.get_server_runtime_config()
logger_wire = NULL_LOGGER
if utils.str_to_bool(config.get_value_at('service.log_wire')):
logger_wire = SERVER_CLOUDAPI_WIRE_LOGGER
acl_svc = acl_service.ClusterACLService(
cluster_id=cluster_id,
client=client_v36,
logger_debug=LOGGER,
logger_wire=logger_wire
)
curr_rde: common_models.DefEntity = acl_svc.get_cluster_entity()
user_id_names_dict = vcd_utils.create_org_user_id_to_name_dict(
client=client_v36,
org_name=curr_rde.org.name)
# If the user is from the system org, need to consider system users
if client_v36.is_sysadmin():
system_user_id_names_dict = vcd_utils.create_org_user_id_to_name_dict( # noqa: E501
client=client_v36,
org_name=SYSTEM_ORG_NAME)
user_id_names_dict.update(system_user_id_names_dict)
# Iterate all acl entries because not all results correspond to a user
acl_values = []
result_total = 0
for acl_entry in acl_svc.list_def_entity_acl_entries():
if acl_entry.memberId.startswith(shared_constants.USER_URN_PREFIX):
curr_page = result_total // page_size + 1
page_entry = result_total % page_size
# Check if entry is on desired page
if curr_page == page and page_entry < page_size:
# Add acl entry
# If there is no username found, the user must be a system
# user, so a generic name is shown
acl_entry.username = user_id_names_dict.get(
acl_entry.memberId, shared_constants.SYSTEM_USER_GENERIC_NAME) # noqa: E501
filter_acl_value: dict = acl_entry.construct_filtered_dict(
include=def_constants.CLUSTER_ACL_LIST_FIELDS)
acl_values.append(filter_acl_value)
result_total += 1
return {
shared_constants.PaginationKey.RESULT_TOTAL: result_total,
shared_constants.PaginationKey.VALUES: acl_values
}
def update_cluster_acl(self, cluster_id, update_acl_entry_dicts: list):
"""Update the cluster ACL by updating the defined entity and vApp ACL.""" # noqa: E501
update_acl_entries = [common_models.ClusterAclEntry(**entry_dict)
for entry_dict in update_acl_entry_dicts]
telemetry_params = {
shared_constants.RequestKey.CLUSTER_ID: cluster_id,
shared_constants.ClusterAclKey.UPDATE_ACL_ENTRIES:
update_acl_entries,
telemetry_constants.PayloadKey.SOURCE_DESCRIPTION: thread_local_data.get_thread_local_data(ThreadLocalData.USER_AGENT) # noqa: E501
}
telemetry_handler.record_user_action_details(
telemetry_constants.CseOperation.V36_CLUSTER_ACL_UPDATE,
cse_params=telemetry_params)
client_v36 = self.context.get_client(api_version=DEFAULT_API_VERSION)
config = server_utils.get_server_runtime_config()
logger_wire = NULL_LOGGER
if utils.str_to_bool(config.get_value_at('service.log_wire')):
logger_wire = SERVER_CLOUDAPI_WIRE_LOGGER
acl_svc = acl_service.ClusterACLService(
cluster_id=cluster_id,
client=client_v36,
logger_debug=LOGGER,
logger_wire=logger_wire
)
prev_user_id_to_acl_entry_dict: \
Dict[str, common_models.ClusterAclEntry] = \
acl_svc.create_user_id_to_acl_entry_dict()
try:
acl_svc.update_native_def_entity_acl(
update_acl_entries=update_acl_entries,
prev_user_id_to_acl_entry=prev_user_id_to_acl_entry_dict)
acl_svc.native_update_vapp_access_settings(
prev_user_id_to_acl_entry_dict, update_acl_entries)
except Exception as err:
LOGGER.error(str(err))
# Rollback defined entity
prev_acl_entries = [acl_entry for _, acl_entry in prev_user_id_to_acl_entry_dict.items()] # noqa: E501
curr_user_acl_info = acl_svc.create_user_id_to_acl_entry_dict()
acl_svc.update_native_def_entity_acl(
update_acl_entries=prev_acl_entries,
prev_user_id_to_acl_entry=curr_user_acl_info)
raise err
def delete_nodes(self, cluster_id: str, nodes_to_del=None):
"""Start the delete nodes operation."""
if nodes_to_del is None:
nodes_to_del = []
# TODO: Make use of current entity in the behavior payload
# get_entity() call needed here to get the cluster details
curr_rde: common_models.DefEntity = self.entity_svc.get_entity(
cluster_id)
curr_native_entity: rde_2_x.NativeEntity = curr_rde.entity
if len(nodes_to_del) == 0:
LOGGER.debug("No nodes specified to delete")
return curr_rde
# must _update_task here or else self.task_resource is None
# do not logout of sys admin, or else in pyvcloud's session.request()
# call, session becomes None
msg = f"Deleting {', '.join(nodes_to_del)} node(s) from cluster " \
f"'{curr_native_entity.metadata.name}' ({cluster_id})"
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
changes = {
'entity.status.task_href': self.task_href,
'entity.status.phase': str(
DefEntityPhase(DefEntityOperation.UPDATE,
DefEntityOperationStatus.IN_PROGRESS))
}
try:
self._update_cluster_entity(cluster_id, changes=changes)
except Exception as err:
self._update_task(BehaviorTaskStatus.ERROR,
message=msg,
error_message=str(err))
LOGGER.error(str(err))
raise
self.context.is_async = True
self._monitor_delete_nodes(cluster_id=cluster_id,
nodes_to_del=nodes_to_del)
return self.mqtt_publisher.construct_behavior_payload(
message=msg,
status=BehaviorTaskStatus.RUNNING.value, progress=5)
@thread_utils.run_async
def _create_cluster_async(self, cluster_id: str,
input_native_entity: rde_2_x.NativeEntity):
cluster_name = ''
rollback = False
org_name = ''
ovdc_name = ''
vapp = None
network_name = ''
client_v36 = self.context.get_client(api_version=DEFAULT_API_VERSION)
curr_rde: Optional[Union[common_models.DefEntity, Tuple[common_models.DefEntity, dict]]] = None # noqa: E501
is_refresh_token_created = False
# by default set to True to attempt DNAT rule deletion while rolling
# back
expose: bool = True
try:
cluster_name = input_native_entity.metadata.name
vcd_host = input_native_entity.metadata.site
org_name = input_native_entity.metadata.org_name
ovdc_name = input_native_entity.metadata.virtual_data_center_name
num_workers = input_native_entity.spec.topology.workers.count
control_plane_sizing_class = input_native_entity.spec.topology.control_plane.sizing_class # noqa: E501
control_plane_cpu_count = input_native_entity.spec.topology.control_plane.cpu # noqa: E501
control_plane_memory_mb = input_native_entity.spec.topology.control_plane.memory # noqa: E501
worker_sizing_class = input_native_entity.spec.topology.workers.sizing_class # noqa: E501
worker_cpu_count = input_native_entity.spec.topology.workers.cpu
worker_memory_mb = input_native_entity.spec.topology.workers.memory
control_plane_storage_profile = input_native_entity.spec.topology.control_plane.storage_profile # noqa: E501
worker_storage_profile = input_native_entity.spec.topology.workers.storage_profile # noqa: E501
network_name = input_native_entity.spec.settings.ovdc_network
template_name = input_native_entity.spec.distribution.template_name # noqa: E501
ssh_key = input_native_entity.spec.settings.ssh_key
rollback = input_native_entity.spec.settings.rollback_on_failure
expose = input_native_entity.spec.settings.network.expose
# The order of precedence for csi/cpi/cni defaults is:
# 1. RDE params 2. CSE config file 3. hard-coded constants
# Handle defaults for csi
extra_options_config: dict = _get_extra_options_config()
csi_list = input_native_entity.spec.settings.csi
if csi_list is not None and len(csi_list) > 0 and \
csi_list[0].version is not None:
csi_version = csi_list[0].version
else:
csi_version = extra_options_config.get("csi_version", CSI_DEFAULT_VERSION) # noqa: E501
# Handle defaults for cpi
if input_native_entity.spec.settings.cpi is not None and \
input_native_entity.spec.settings.cpi.version is not None:
cpi_version = input_native_entity.spec.settings.cpi.version
else:
cpi_version = extra_options_config.get("cpi_version", CPI_DEFAULT_VERSION) # noqa: E501
# Handle defaults for cni
if input_native_entity.spec.settings.cni is not None and \
input_native_entity.spec.settings.cni.version is not None:
cni_version = input_native_entity.spec.settings.cni.version
else:
# No default CNI version is provided so that the control plane
# script will see an empty version and use the tkr bom file
# to find the compatible CNI version. Only CNI and CPI have
# default versions since they are not currently in the tkr bom
cni_version = extra_options_config.get("antrea_version", "")
input_default_storage_class = None
create_default_storage_class = False
if csi_list is not None and len(csi_list) > 0 and \
csi_list[0].default_k8s_storage_class is not None:
input_default_storage_class = csi_list[0].default_k8s_storage_class # noqa: E501
create_default_storage_class = True
# dsc: default storage class
dsc_storage_profile_name = None
dsc_k8s_storage_class_name = None
dsc_filesystem = None
dsc_use_delete_reclaim_policy: bool = False
if create_default_storage_class:
dsc_storage_profile_name = input_default_storage_class.vcd_storage_profile_name # noqa: E501
dsc_k8s_storage_class_name = input_default_storage_class.k8s_storage_class_name # noqa: E501
dsc_filesystem = input_default_storage_class.filesystem
dsc_use_delete_reclaim_policy = input_default_storage_class.use_delete_reclaim_policy # noqa: E501
k8s_pod_cidr = TKGM_DEFAULT_POD_NETWORK_CIDR
if (
input_native_entity.spec.settings is not None
and input_native_entity.spec.settings.network is not None
and input_native_entity.spec.settings.network.pods is not None
and input_native_entity.spec.settings.network.pods.cidr_blocks is not None # noqa: E501
and len(input_native_entity.spec.settings.network.pods.cidr_blocks) > 0 # noqa: E501
):
k8s_pod_cidr = input_native_entity.spec.settings.network.pods.cidr_blocks[0] # noqa: E501
k8s_svc_cidr = TKGM_DEFAULT_SERVICE_CIDR
if (
input_native_entity.spec.settings is not None
and input_native_entity.spec.settings.network is not None
and input_native_entity.spec.settings.network.services is not None # noqa: E501
and input_native_entity.spec.settings.network.services.cidr_blocks is not None # noqa: E501
and len(input_native_entity.spec.settings.network.services.cidr_blocks) > 0 # noqa: E501
):
k8s_svc_cidr = input_native_entity.spec.settings.network.services.cidr_blocks[0] # noqa: E501
org = vcd_utils.get_org(client_v36, org_name=org_name)
vdc = vcd_utils.get_vdc(client_v36, vdc_name=ovdc_name, org=org)
LOGGER.debug(f"About to create cluster '{cluster_name}' on "
f"{ovdc_name} with {num_workers} worker nodes, "
f"storage profile={worker_storage_profile}")
msg = f"Creating cluster vApp {cluster_name} ({cluster_id})"
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
try:
vapp_resource = vdc.create_vapp(
cluster_name,
description=f"cluster '{cluster_name}'",
network=network_name,
fence_mode='bridged')
except Exception as err:
LOGGER.error(str(err), exc_info=True)
raise exceptions.ClusterOperationError(
f"Error while creating vApp: {err}")
client_v36.get_task_monitor().wait_for_status(vapp_resource.Tasks.Task[0]) # noqa: E501
template = _get_tkgm_template(template_name)
LOGGER.debug(f"Setting metadata on cluster vApp '{cluster_name}'")
tags = {
ClusterMetadataKey.CLUSTER_ID: cluster_id,
ClusterMetadataKey.CSE_VERSION: pkg_resources.require('container-service-extension')[0].version, # noqa: E501
ClusterMetadataKey.TEMPLATE_NAME: template[LocalTemplateKey.NAME], # noqa: E501
# templateRevision is hardcoded as 1 for TKGm
ClusterMetadataKey.TEMPLATE_REVISION: 1,
ClusterMetadataKey.OS: template[LocalTemplateKey.OS],
ClusterMetadataKey.KUBERNETES: template[LocalTemplateKey.KUBERNETES], # noqa: E501
ClusterMetadataKey.KUBERNETES_VERSION: template[LocalTemplateKey.KUBERNETES_VERSION], # noqa: E501
ClusterMetadataKey.CNI: CNI_NAME,
ClusterMetadataKey.CSI: CSI_NAME,
ClusterMetadataKey.CPI: CPI_NAME
}
sysadmin_client_v36 = self.context.get_sysadmin_client(
api_version=DEFAULT_API_VERSION)
# Extra config elements of VApp are visible only for admin client
vapp = vcd_vapp.VApp(client_v36,
href=vapp_resource.get('href'))
admin_vapp = vcd_vapp.VApp(sysadmin_client_v36, href=vapp_resource.get('href'))
task = vapp.set_multiple_metadata(tags)
client_v36.get_task_monitor().wait_for_status(task)
# Get refresh token
config = server_utils.get_server_runtime_config()
logger_wire = NULL_LOGGER
if utils.str_to_bool(config.get_value_at('service.log_wire')):
logger_wire = SERVER_CLOUDAPI_WIRE_LOGGER
oauth_client_name = _get_oauth_client_name_from_cluster_id(cluster_id) # noqa: E501
mts = oauth_service.MachineTokenService(
vcd_api_client=client_v36,
oauth_client_name=oauth_client_name,
logger_debug=LOGGER,
logger_wire=logger_wire)
mts.register_oauth_client()
mts.create_refresh_token()
refresh_token = mts.refresh_token
is_refresh_token_created = True
msg = f"Creating control plane node for cluster '{cluster_name}'" \
f" ({cluster_id})"
LOGGER.debug(msg)
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
vapp.reload()
server_config = server_utils.get_server_runtime_config()
catalog_name = server_config.get_value_at('broker.catalog')
msg = f"Adding control plane node for '{cluster_name}' ({cluster_id})" # noqa: E501
LOGGER.debug(msg)
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
vapp.reload()
try:
# antrea will be installed on the first control plane node.
# kapp controller and metrics server will be installed on
# the worker nodes.
expose_ip, _, core_pkg_versions = _add_control_plane_nodes(
sysadmin_client_v36,
user_client=self.context.client,
num_nodes=1,
vcd_host=vcd_host,
org=org,
vdc=vdc,
vapp=vapp,
admin_vapp=admin_vapp,
catalog_name=catalog_name,
template=template,
network_name=network_name,
k8s_pod_cidr=k8s_pod_cidr,
k8s_svc_cidr=k8s_svc_cidr,
storage_profile=control_plane_storage_profile,
ssh_key=ssh_key,
sizing_class_name=control_plane_sizing_class,
cpu_count=control_plane_cpu_count,
memory_mb=control_plane_memory_mb,
expose=expose,
cluster_name=cluster_name,
cluster_id=cluster_id,
refresh_token=refresh_token,
cni_version=cni_version,
cpi_version=cpi_version,
csi_version=csi_version,
create_default_storage_class=create_default_storage_class,
dsc_storage_profile_name=f"\"{dsc_storage_profile_name}\"",
dsc_k8s_storage_class_name=dsc_k8s_storage_class_name,
dsc_filesystem=dsc_filesystem,
dsc_use_delete_reclaim_policy=dsc_use_delete_reclaim_policy
)
except Exception as err:
LOGGER.error(err, exc_info=True)
raise exceptions.ControlPlaneNodeCreationError(
f"Error adding control plane node: {err}")
vapp.reload()
control_plane_join_cmd = _get_join_cmd(
sysadmin_client=sysadmin_client_v36,
vapp=admin_vapp
)
msg = f"Creating {num_workers} node(s) for cluster " \
f"'{cluster_name}' ({cluster_id})"
LOGGER.debug(msg)
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
cni_version = core_pkg_versions.get(CorePkgVersionKeys.ANTREA.value) # noqa: E501
# because antrea is already installed, remove it from the core pkg
# dictionary so that it is not installed
if cni_version:
del core_pkg_versions[CorePkgVersionKeys.ANTREA.value]
try:
_, installed_core_pkg_versions = _add_worker_nodes(
sysadmin_client_v36,
user_client=self.context.client,
num_nodes=num_workers,
org=org,
vdc=vdc,
vapp=vapp,
admin_vapp=admin_vapp,
catalog_name=catalog_name,
template=template,
network_name=network_name,
storage_profile=worker_storage_profile,
ssh_key=ssh_key,
sizing_class_name=worker_sizing_class,
cpu_count=worker_cpu_count,
memory_mb=worker_memory_mb,
control_plane_join_cmd=control_plane_join_cmd,
core_pkg_versions_to_install=core_pkg_versions
)
except Exception as err:
LOGGER.error(err, exc_info=True)
raise exceptions.WorkerNodeCreationError(
f"Error creating worker node: {err}")
msg = f"Added {num_workers} node(s) to cluster " \
f"'{cluster_name}' ({cluster_id})"
LOGGER.debug(msg)
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
vapp.reload()
# Update defined entity instance with new properties like vapp_id,
# control plane_ip and nodes.
msg = f"Updating cluster `{cluster_name}` ({cluster_id}) defined entity" # noqa: E501
LOGGER.debug(msg)
self._update_task(BehaviorTaskStatus.RUNNING, message=msg)
# Get changes needed for rde update
csi_elem_rde_status_value = rde_2_x.CsiElement()
# no deep copy is currently needed because the default
# storage class has no object fields
if create_default_storage_class:
csi_elem_rde_status_value.default_k8s_storage_class = \
copy.copy(input_default_storage_class)
csi_elem_rde_status_value.name = CSI_NAME
csi_elem_rde_status_value.version = csi_version
# When multiple CSI's are supported we cannot hardcode this
# csi `default` field; we will need to look into the spec and we
# may need to validate if there is only one default csi
csi_elem_rde_status_value.default = True
# get installed core pkg versions
installed_kapp_controller_version = installed_core_pkg_versions.get(CorePkgVersionKeys.KAPP_CONTROLLER.value, "") # noqa: E501
installed_metrics_server_version = installed_core_pkg_versions.get(CorePkgVersionKeys.METRICS_SERVER.value, "") # noqa: E501
changes = {