-
Notifications
You must be signed in to change notification settings - Fork 5
/
start.py
1299 lines (1101 loc) · 68.2 KB
/
start.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
# -*- coding: utf-8 -*-
# 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 io
import logging
import os
import re
import socket
from configobj import ConfigObj
from clusterdock.models import Cluster, client, Node
from clusterdock.utils import nested_get, wait_for_condition
from .cm import ClouderaManagerDeployment
DEFAULT_NAMESPACE = 'cloudera'
CM_PORT = 7180
HUE_PORT = 8888
CM_AGENT_CONFIG_FILE_PATH = '/etc/cloudera-scm-agent/config.ini'
CM_PRINCIPAL_PASSWORD = 'cldadmin'
CM_PRINCIPAL_USER = 'cloudera-scm/admin'
CM_SERVER_ETC_DEFAULT = '/etc/default/cloudera-scm-server'
CSD_DIRECTORY = '/opt/cloudera/csd'
PARCEL_REPO_DIRECTORY = '/opt/cloudera/parcel-repo'
# In the following two locations, clusterdock volume mounts the csds and parcels for cloudera services.
CLUSTERDOCK_CSD_DIRECTORY = '/opt/clusterdock/csd'
CLUSTERDOCK_PARCEL_REPO_DIRECTORY = '/opt/clusterdock/parcel-repo'
DEFAULT_CLUSTER_NAME = 'cluster'
SECONDARY_NODE_TEMPLATE_NAME = 'Secondary'
KERBEROS_CONFIG_CONTAINER_DIR = '/etc/clusterdock/client/kerberos'
KDC_HOSTNAME = 'kdc'
KDC_IMAGE = 'clusterdock/topology_nodebase_kerberos:centos6.6'
KDC_ACL_FILENAME = '/var/kerberos/krb5kdc/kadm5.acl'
KDC_CONF_FILENAME = '/var/kerberos/krb5kdc/kdc.conf'
KDC_KEYTAB_FILENAME = '{}/clusterdock.keytab'.format(KERBEROS_CONFIG_CONTAINER_DIR)
KDC_KRB5_CONF_FILENAME = '/etc/krb5.conf'
LINUX_USER_ID_START = 1000
EARLIEST_CDH_VERSION_WITH_KAFKA = (6, 0, 0)
EARLIEST_CDH_VERSION_WITH_KUDU = (5, 13, 0)
EARLIEST_CDH_VERSION_WITH_SPARK2 = (6, 0, 0)
EARLIEST_CDH_VERSION_WITH_CENTOS6_8 = (6, 1, 1)
KUDU_PARCEL_VERSION_REGEX = r'(.*)-.*\.cdh(.*)\.p'
KAFKA_PARCEL_REPO_URL = 'https://archive.cloudera.com/kafka/parcels'
KUDU_PARCEL_REPO_URL = 'https://archive.cloudera.com/kudu/parcels'
KUDU_PARCEL_VERSIONS = {'1.2.0': '5.10.0',
'1.3.0': '5.11.0',
'1.4.0': '5.12.0'}
SERVICE_PARCEL_REPO_URLS = {'KAFKA': KAFKA_PARCEL_REPO_URL,
'KUDU': KUDU_PARCEL_REPO_URL}
# Files placed in this directory on primary_node are available
# in clusterdock_config_directory after cluster is started.
# Also, this gets volume mounted to all secondary nodes and hence available there too.
CLUSTERDOCK_CLIENT_CONTAINER_DIR = '/etc/clusterdock/client'
SSL_SERVER_CONTAINER_DIR = '/etc/clusterdock/server/ssl'
SSL_CLIENT_CONTAINER_DIR = '/etc/clusterdock/client/ssl'
SSL_SERVER_KEYSTORE = 'server.keystore.jks'
SSL_SERVER_TRUSTSTORE = 'server.truststore.jks'
SSL_CLIENT_KEYSTORE = 'client.keystore.jks'
SSL_CLIENT_TRUSTSTORE = 'client.truststore.jks'
SSL_SERVER_PASSWORD = 'serverpass'
SSL_CLIENT_PASSWORD = 'clientpass'
# Navigator related constants.
DB_MGMT_PROPERTIES_FILENAME = '/etc/cloudera-scm-server/db.mgmt.properties'
# CDH versions < 5.14.0 need to have Reports Manager role created when license is applied
# which is required for Navigator.
EARLIEST_CDH_VERSION_WITH_NO_REPORTS_MANAGER_NEEDED = (5, 14, 0)
NAVIGATOR_POSTGRESQL_PORT = 7432
logger = logging.getLogger('clusterdock.{}'.format(__name__))
def main(args):
if args.include_services and args.exclude_services:
raise ValueError('Cannot pass both --include-services and --exclude-services.')
image_prefix = '{}/{}/clusterdock:cdh{}_cm{}'.format(args.registry,
args.namespace or DEFAULT_NAMESPACE,
args.cdh_version,
args.cm_version)
primary_node_image = '{}_{}'.format(image_prefix, 'primary-node')
secondary_node_image = '{}_{}'.format(image_prefix, 'secondary-node')
single_node_image = '{}_{}'.format(image_prefix, 'single-node')
# Docker's API for healthcheck uses units of nanoseconds. Define a constant
# to make this more readable.
SECONDS = 1000000000
cm_server_healthcheck = {
'test': 'curl --silent --output /dev/null 127.0.0.1:{}'.format(CM_PORT),
'interval': 1 * SECONDS,
'timeout': 1 * SECONDS,
'retries': 1,
'start_period': 30 * SECONDS
}
ports = [{CM_PORT: CM_PORT} if args.predictable else CM_PORT,
{HUE_PORT: HUE_PORT} if args.predictable else HUE_PORT]
clusterdock_config_host_dir = os.path.realpath(os.path.expanduser(args.clusterdock_config_directory))
volumes = [{clusterdock_config_host_dir: CLUSTERDOCK_CLIENT_CONTAINER_DIR}]
primary_node = Node(hostname=args.primary_node[0], group='primary',
image=primary_node_image if not args.single_node else single_node_image,
ports=ports,
healthcheck=cm_server_healthcheck,
volumes=volumes)
secondary_nodes = [Node(hostname=hostname, group='secondary', image=secondary_node_image, volumes=volumes)
for hostname in args.secondary_nodes]
nodes = [primary_node] + secondary_nodes if not args.single_node else [primary_node]
if args.java:
java_image = '{}/{}/clusterdock:cdh_{}'.format(args.registry,
args.namespace,
args.java)
for node in nodes:
node.volumes.append(java_image)
cdh_version_tuple = tuple(int(i) if i.isdigit() else i for i in args.cdh_version.split('.'))
# Gather services to add depending on values of --include-services and --exclude-services.
# These services accept version as arguments e.g. kafka_version, kudu_version.
services_to_add = set()
if args.spark2_version and cdh_version_tuple < EARLIEST_CDH_VERSION_WITH_SPARK2:
if _is_service_to_add('SPARK2_ON_YARN', args.include_services, args.exclude_services):
services_to_add.add('SPARK2_ON_YARN')
image_name = '{}/{}/clusterdock:topology_cdh-spark-{}'
spark2_parcel_image = image_name.format(args.registry,
args.namespace or DEFAULT_NAMESPACE,
args.spark2_version)
logger.debug('Adding Spark2 parcel image %s to CM nodes ...', spark2_parcel_image)
for node in nodes:
node.volumes.append(spark2_parcel_image)
if args.kerberos:
dir = '{}/kerberos'.format(args.clusterdock_config_directory)
kerberos_config_host_dir = os.path.realpath(os.path.expanduser(dir))
volumes = [{kerberos_config_host_dir: KERBEROS_CONFIG_CONTAINER_DIR}]
for node in nodes:
node.volumes.extend(volumes)
kdc_node = Node(hostname=KDC_HOSTNAME, group='kdc', image=KDC_IMAGE,
volumes=volumes)
cluster = Cluster(*nodes + ([kdc_node] if args.kerberos else []))
cluster.primary_node = primary_node
cluster.start(args.network, pull_images=args.always_pull)
# Keep track of whether to suppress DEBUG-level output in commands.
quiet = not args.verbose
if args.spark2_version and 'SPARK2_ON_YARN' in services_to_add:
# Install is needed only when Spark2 is not integrated.
logger.info('Installing Spark2 from local repo ...')
_install_service_from_local_repo(cluster, product='SPARK2')
if args.kerberos:
cluster.kdc_node = kdc_node
_configure_kdc(cluster, args.kerberos_principals, args.kerberos_ticket_lifetime, quiet=quiet)
_install_kerberos_clients(nodes, quiet=quiet)
if args.kerberos_principals:
_create_kerberos_cluster_users(nodes, args.kerberos_principals, quiet=quiet)
if args.java:
_set_cm_server_java_home(primary_node, '/usr/java/{}'.format(args.java))
if args.java or (args.spark2_version and 'SPARK2_ON_YARN' in services_to_add):
# In case change was made to Java version or parcel/s were installed from local repo,
# then cloudera-scm-server needs to be restarted to take changes in effect.
# Avoid CM database issues by waiting for CM to not be dead before restarting it.
def cm_server_not_dead(primary_node):
cm_server_status = primary_node.execute('service cloudera-scm-server status', quiet=True)
logger.debug('CM server status command has output (%s) with exit code %s.',
cm_server_status.output,
cm_server_status.exit_code)
return cm_server_status.exit_code != 1
try:
wait_for_condition(cm_server_not_dead,
[primary_node],
failure=lambda timeout: None)
except TimeoutError:
logger.warning('Timed out while waiting for the CM server to not be dead. '
'Will try to continue ...')
primary_node.execute('service cloudera-scm-server restart')
filesystem_fix_commands = ['cp {0} {0}.1; umount {0}; mv -f {0}.1 {0}'.format(file_)
for file_ in ['/etc/hosts',
'/etc/resolv.conf',
'/etc/hostname',
'/etc/localtime']]
for node in nodes:
node.execute('; '.join(filesystem_fix_commands), quiet=quiet)
_configure_cm_agents(nodes)
# The CDH topology uses two pre-built images ('primary' and 'secondary'). If a cluster
# larger than 2 nodes is started, some modifications need to be done to the nodes to
# prevent duplicate heartbeats and things like that.
if len(secondary_nodes) > 1:
_remove_files(nodes=secondary_nodes[1:],
files=['/var/lib/cloudera-scm-agent/uuid',
'/dfs*/dn/current/*'])
logger.info('Restarting Cloudera Manager agents ...')
_restart_cm_agents(nodes, cdh_version_tuple)
logger.info('Waiting for Cloudera Manager server to come online ...')
_wait_for_cm_server(primary_node)
# Docker for Mac exposes ports that can be accessed only with ``localhost:<port>`` so
# use that instead of the hostname if the host name is ``moby``.
if any(docker_for_mac_name in client.info().get('Name', '') for docker_for_mac_name in ['moby', 'linuxkit']):
hostname = 'localhost'
else:
hostname = socket.gethostbyname(socket.gethostname())
port = primary_node.host_ports.get(CM_PORT)
server_url = 'http://{}:{}'.format(hostname, port)
logger.info('Cloudera Manager server is now reachable at %s', server_url)
# The work we need to do through CM itself begins here...
deployment = ClouderaManagerDeployment(server_url)
cm_cluster = deployment.cluster(DEFAULT_CLUSTER_NAME)
# For CDH 6, it takes a bit of time for CDH parcel to reach ACTIVATED stage.
# Hence wait for that stage to reach, otherwise the next statement to find cdh_parcel in that stage fails.
cm_cluster.wait_for_parcel_stage(product='CDH', version=args.cdh_version, stage='ACTIVATED')
cdh_parcel = next(parcel for parcel in cm_cluster.parcels
if parcel.product == 'CDH' and parcel.stage == 'ACTIVATED')
# Wait on all slave nodes to get back to CM
wait_for_condition(lambda: len(deployment.get_all_hosts()) == len(nodes))
# Add all CM hosts to the cluster (i.e. only new hosts that weren't part of the original
# images).
all_host_ids = {}
for host in deployment.get_all_hosts():
all_host_ids[host['hostId']] = host['hostname']
for node in nodes:
if node.fqdn == host['hostname']:
node.host_id = host['hostId']
break
else:
raise Exception('Could not find CM host with hostname {}.'.format(node.fqdn))
cluster_host_ids = {host['hostId']
for host in deployment.get_cluster_hosts(cluster_name=DEFAULT_CLUSTER_NAME)}
host_ids_to_add = set(all_host_ids.keys()) - cluster_host_ids
if host_ids_to_add:
logger.debug('Adding %s to cluster %s ...',
'host{} ({})'.format('s' if len(host_ids_to_add) > 1 else '',
', '.join(all_host_ids[host_id]
for host_id in host_ids_to_add)),
DEFAULT_CLUSTER_NAME)
deployment.add_cluster_hosts(cluster_name=DEFAULT_CLUSTER_NAME, host_ids=host_ids_to_add)
cdh_parcel.wait_for_stage('ACTIVATED', timeout=600, time_to_success=10)
# Create and apply a host template to ensure that all the secondary nodes have the same
# CM roles running on them.
logger.info('Creating secondary node host template ...')
_create_secondary_node_template(deployment=deployment,
cluster_name=DEFAULT_CLUSTER_NAME,
secondary_node=secondary_nodes[0])
deployment.apply_host_template(cluster_name=DEFAULT_CLUSTER_NAME,
host_template_name=SECONDARY_NODE_TEMPLATE_NAME,
start_roles=False,
host_ids=host_ids_to_add)
else:
cdh_parcel.wait_for_stage('ACTIVATED', timeout=600, time_to_success=10)
if args.java:
java_home = '/usr/java/{}'.format(args.java)
logger.info('Updating JAVA_HOME config on all hosts to %s ...', java_home)
deployment.update_all_hosts_config(configs={'java_home': java_home})
logger.info('Updating CM server configurations ...')
deployment.update_cm_config(configs={'manages_parcels': True})
# Services that are not added by default by CDH core parcel are added. e.g. KAFKA, KUDU, SPARK2_ON_YARN.
# Validate passed service versions and add them to set of services_to_add.
# SPARK2_ON_YARN is already validated by now.
services_to_add.update(_validate_services_to_add(cdh_version_tuple, cm_cluster, args.exclude_services,
args.include_services, args.kafka_version, args.kudu_version))
if args.include_services:
service_types_to_leave = args.include_services.upper().split(',')
for service in deployment.get_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME):
if service['type'] not in service_types_to_leave:
logger.info('Removing cluster service (name = %s) ...',
service['name'])
deployment.api_client.delete_cluster_service(cluster_name=DEFAULT_CLUSTER_NAME,
service_name=service['name'])
elif args.exclude_services:
service_types_to_remove = args.exclude_services.upper().split(',')
for service in deployment.get_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME):
if service['type'] in service_types_to_remove:
logger.info('Removing cluster service (name = %s) ...',
service['name'])
deployment.api_client.delete_cluster_service(cluster_name=DEFAULT_CLUSTER_NAME,
service_name=service['name'])
cluster_service_types = {service['type']
for service
in deployment.get_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME)}
logger.info('Updating database configurations ...')
_update_database_configs(deployment=deployment,
cluster_name=DEFAULT_CLUSTER_NAME,
primary_node=primary_node)
if 'HIVE' in cluster_service_types and 'HDFS' in cluster_service_types:
logger.info('Updating Hive Metastore Namenodes ...')
_update_hive_metastore_namenodes(deployment=deployment,
cluster_name=DEFAULT_CLUSTER_NAME)
# Whether a user requests a service version or not, we always begin by removing it from the
# cluster services list (if present) so that configurations can always be generated anew.
for service in deployment.get_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME):
if service['type'] == 'KUDU':
logger.debug('Removing cluster service (name = %s) ...',
service['name'])
deployment.api_client.delete_cluster_service(cluster_name=DEFAULT_CLUSTER_NAME,
service_name=service['name'])
logger.debug('Clearing /data/kudu/master on primary node ...')
cluster.primary_node.execute('rm -rf /data/kudu/master')
elif service['type'] == 'KAFKA':
logger.debug('Removing cluster service (name = %s) ...',
service['name'])
deployment.api_client.delete_cluster_service(cluster_name=DEFAULT_CLUSTER_NAME,
service_name=service['name'])
if args.navigator:
logger.info('Configuring Navigator ...')
_configure_navigator(deployment, cluster, cdh_version_tuple)
if 'SPARK2_ON_YARN' in services_to_add:
logger.info('Configuring Spark2 ...')
_configure_spark2(deployment, cluster, secondary_nodes[0] if not args.single_node else primary_node)
if args.kerberos:
# Stopping of services after first_run, is needed for kerberos to work correctly.
logger.info('Stopping cluster services after adding Spark2 as some were started during first_run ...')
cm_cluster.stop()
if 'KAFKA' in services_to_add:
if args.ssl:
_setup_ssl(cluster, ['KAFKA'])
logger.info('Configuring Kafka ...')
_configure_kafka(deployment, cluster, args.kafka_version, cdh_version_tuple, args.ssl)
if 'KUDU' in services_to_add:
logger.info('Configuring Kudu ...')
_configure_kudu(deployment, cluster, args.kudu_version, args.cdh_version, args.single_node)
if args.kerberos:
logger.info('Configure Cloudera Manager for Kerberos ...')
_configure_cm_for_kerberos(deployment, cluster, args.kerberos_ticket_lifetime)
logger.info('Deploying client config ...')
cm_cluster.deploy_client_config()
# This is needed due to the fact some service might have run first_run_service command while configuring.
# first_run_service command in turn starts the service along with its dependent services.
# In case of dont_start_cluster, the cluster services need to be stopped.
# Otherwise, some of these started services end up with stale configurations at this point
# - which asks for their stop and later run start.
logger.info('Stopping cluster services ...')
cm_cluster.stop()
if not args.dont_start_cluster:
logger.info('Starting cluster services ...')
cm_cluster.start()
logger.info('Starting CM services ...')
_start_cm_service(deployment=deployment)
logger.info('Validating service health ...')
_validate_service_health(deployment=deployment, cluster_name=DEFAULT_CLUSTER_NAME)
logger.info('Configuring after start of cluster ...')
_configure_after_start(deployment=deployment,
cluster_name=DEFAULT_CLUSTER_NAME,
cluster=cluster, quiet=not args.verbose,
kerberos_principals=args.kerberos_principals)
def _is_service_to_add(service_type, include_services, exclude_services):
if include_services:
return service_type in include_services.upper().split(',')
elif exclude_services:
return service_type not in exclude_services.upper().split(',')
else:
return True
def _configure_kdc(cluster, kerberos_principals, kerberos_ticket_lifetime, quiet):
kdc_node = cluster.kdc_node
logger.info('Updating KDC configurations ...')
realm = cluster.network.upper()
logger.debug('Updating krb5.conf ...')
krb5_conf = cluster.kdc_node.get_file(KDC_KRB5_CONF_FILENAME)
# Here '\g<1>' represents group matched in regex which is the original default value of ticket_lifetime.
ticket_lifetime_replacement = kerberos_ticket_lifetime if kerberos_ticket_lifetime else '\g<1>'
krb5_conf_contents = re.sub(r'EXAMPLE.COM', realm,
re.sub(r'example.com', cluster.network,
re.sub(r'ticket_lifetime = ((.)*)',
r'ticket_lifetime = {}'.format(ticket_lifetime_replacement),
re.sub(r'kerberos.example.com',
kdc_node.fqdn,
krb5_conf))))
kdc_node.put_file(KDC_KRB5_CONF_FILENAME, krb5_conf_contents)
logger.debug('Updating kdc.conf ...')
kdc_conf = kdc_node.get_file(KDC_CONF_FILENAME)
max_time_replacement = kerberos_ticket_lifetime if kerberos_ticket_lifetime else '1d'
kdc_node.put_file(KDC_CONF_FILENAME,
re.sub(r'EXAMPLE.COM', realm,
re.sub(r'\[kdcdefaults\]',
r'[kdcdefaults]\n max_renewablelife = 7d\n max_life = {}'.format(max_time_replacement),
kdc_conf)))
logger.debug('Updating kadm5.acl ...')
kadm5_acl = kdc_node.get_file(KDC_ACL_FILENAME)
kdc_node.put_file(KDC_ACL_FILENAME,
re.sub(r'EXAMPLE.COM', realm, kadm5_acl))
logger.info('Starting KDC ...')
kdc_commands = [
'kdb5_util create -s -r {} -P kdcadmin'.format(realm),
'kadmin.local -q "addprinc -pw {} admin/admin@{}"'.format('acladmin', realm),
'kadmin.local -q "addprinc -pw {} {}@{}"'.format(CM_PRINCIPAL_PASSWORD,
CM_PRINCIPAL_USER,
realm)
]
if kerberos_principals:
principals = ['{}@{}'.format(primary, realm)
for primary in kerberos_principals.split(',')]
if kerberos_ticket_lifetime:
kdc_commands.extend([('kadmin.local -q "addprinc -maxlife {}sec '
'-maxrenewlife 5day -randkey {}"'.format(kerberos_ticket_lifetime, principal))
for principal in principals])
else:
kdc_commands.extend(['kadmin.local -q "addprinc -randkey {}"'.format(principal)
for principal in principals])
kdc_commands.append('kadmin.local -q '
'"xst -norandkey -k {} {}"'.format(KDC_KEYTAB_FILENAME,
' '.join(principals)))
kdc_commands.extend(['service krb5kdc start',
'service kadmin start',
'authconfig --enablekrb5 --update',
'cp -f {} {}'.format(KDC_KRB5_CONF_FILENAME,
KERBEROS_CONFIG_CONTAINER_DIR)])
if kerberos_principals:
kdc_commands.append('chmod 644 {}'.format(KDC_KEYTAB_FILENAME))
kdc_node.execute(' && '.join(kdc_commands),
quiet=quiet)
logger.info('Validating health of Kerberos services ...')
def condition(node, services, quiet):
services_with_poor_health = [service
for service in services
if node.execute(command='service {} status'.format(service),
quiet=quiet).exit_code != 0]
if services_with_poor_health:
logger.debug('Services with poor health: %s',
', '.join(services_with_poor_health))
# Return True if the list of services with poor health is empty.
return not bool(services_with_poor_health)
wait_for_condition(condition=condition, condition_args=[kdc_node,
['krb5kdc', 'kadmin'],
quiet])
def _install_kerberos_clients(nodes, quiet):
logger.info('Installing Kerberos libraries on Cloudera Manager nodes ...')
for node in nodes:
if node.execute('yum list installed yum-plugin-ovl', quiet=quiet).exit_code != 0:
logger.debug('Installing yum-plugin-ovl to workaround https://git.io/vFvPW ...')
node.execute('yum -y -q install yum-plugin-ovl', quiet=quiet)
command = ('yum -y -q install openldap-clients krb5-libs krb5-workstation'
if node.group == 'primary'
else 'yum -y -q install krb5-libs krb5-workstation')
node.execute(command=command, quiet=quiet)
def _create_kerberos_cluster_users(nodes, kerberos_principals, quiet):
commands = ['useradd -u {} -g hadoop {}'.format(uid, primary)
for uid, primary in enumerate(kerberos_principals.split(','),
start=LINUX_USER_ID_START)]
for node in nodes:
node.execute('; '.join(commands), quiet=quiet)
def _configure_cm_for_kerberos(deployment, cluster, kerberos_ticket_lifetime):
realm = cluster.network.upper()
kerberos_config = dict(SECURITY_REALM=realm,
KDC_HOST=cluster.kdc_node.fqdn,
KRB_MANAGE_KRB5_CONF=True,
KRB_ENC_TYPES='aes256-cts-hmac-sha1-96')
# Suppress CM's warnings for built-in parameter validation for Kerberos ticket lifetime and renewable lifetime.
# This will allow ticket lifetime and renewable lifetime to be less than an hour.
if kerberos_ticket_lifetime:
kerberos_config.update(dict(scm_config_suppression_krb_renew_lifetime=True,
scm_config_suppression_krb_ticket_lifetime=True,
krb_ticket_lifetime=kerberos_ticket_lifetime))
logger.debug('Updating CM server configurations ...')
deployment.update_cm_config(kerberos_config)
logger.debug('Importing Kerberos admin credentials ...')
command_id = deployment.api_client.import_admin_credentials('{}@{}'.format(CM_PRINCIPAL_USER,
realm),
CM_PRINCIPAL_PASSWORD)['id']
def success(time):
logger.debug('Imported admin credentials in %s seconds.', time)
def failure(timeout):
raise TimeoutError('Timed out after {} seconds waiting '
'to import admin credentials.'.format(timeout))
wait_for_condition(condition=_command_condition,
condition_args=[deployment, command_id, 'Import admin credentials'],
success=success, failure=failure)
logger.debug('Configuring cluster for Kerberos ...')
command_id = deployment.api_client.configure_cluster_for_kerberos(DEFAULT_CLUSTER_NAME)['id']
def success(time):
logger.debug('Configured cluster for Kerberos in %s seconds.', time)
def failure(timeout):
raise TimeoutError('Timed out after {} seconds waiting '
'to configure cluster for Kerberos.'.format(timeout))
wait_for_condition(condition=_command_condition,
condition_args=[deployment, command_id, 'Configure cluster for Kerberos'],
success=success, failure=failure)
logger.debug('Deploying Kerberos client config ...')
command_id = deployment.deploy_cluster_kerberos_client_config(DEFAULT_CLUSTER_NAME)['id']
def success(time):
logger.debug('Deployed Kerberos client config in %s seconds.', time)
def failure(timeout):
raise TimeoutError('Timed out after {} seconds waiting '
'to deploy Kerberos client config.'.format(timeout))
wait_for_condition(condition=_command_condition,
condition_args=[deployment, command_id, 'Deploy Kerberos client config'],
timeout=180,
success=success, failure=failure)
if kerberos_ticket_lifetime:
cm_kerberos_principals = deployment.get_cm_kerberos_principals()
logger.debug('cm_kerberos_principals = %s', cm_kerberos_principals)
_apply_kerberos_ticket_expiration_for_cm_principals(cluster, cm_kerberos_principals, kerberos_ticket_lifetime)
for service in deployment.get_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME):
if service['type'] == 'HUE':
_apply_kerberos_fix_for_hue(cluster)
break
def _apply_kerberos_fix_for_hue(cluster):
""" Fix for Hue service as explained at:
http://www.cloudera.com/documentation/manager/5-1-x/Configuring-Hadoop-Security-with-Cloudera-Manager/cm5chs_enable_hue_sec_s10.html
"""
logger.info('Applying Kerberos fix for hue...')
kdc_node = cluster.kdc_node
primary_node = cluster.primary_node
realm = cluster.network.upper()
kdc_hue_commands = [
'kadmin.local -q "modprinc -maxrenewlife 90day krbtgt/{realm}"'.format(realm=realm),
'kadmin.local -q "modprinc -maxrenewlife 90day +allow_renewable hue/{hue_node_name}@{realm}"'.format(
realm=realm,
hue_node_name=primary_node.fqdn),
'service krb5kdc restart',
'service kadmin restart'
]
kdc_node.execute('&& '.join(kdc_hue_commands))
def _apply_kerberos_ticket_expiration_for_cm_principals(cluster, cm_kerberos_principals, kerberos_ticket_lifetime):
"""Apply Kerberos ticket expiration for Kerberos principals needed by the services being managed by
Cloudera Manager.
"""
logger.info('Applying kerberos ticket expiration...')
change_ticket_expiration_cmd = 'kadmin.local -q "modprinc -maxrenewlife 5day -maxlife {maxlife}sec {principal}"'
commands = [
change_ticket_expiration_cmd.format(maxlife=kerberos_ticket_lifetime, principal=principal)
for principal in cm_kerberos_principals
]
commands.extend(['service krb5kdc restart', 'service kadmin restart'])
cluster.kdc_node.execute('&& '.join(commands))
def _command_condition(deployment, command_id, command_description):
command_information = deployment.api_client.get_command_information(command_id)
active = command_information.get('active')
success = command_information.get('success')
logger.debug('%s command: (active: %s, success: %s)', command_description, active, success)
if not active and not success:
raise Exception('Failed to import admin credentials')
return not active and success
def _deactivate_service_parcel(deployment, cluster, product, version):
for parcel in deployment.cluster(DEFAULT_CLUSTER_NAME).parcels:
if parcel.product == product and parcel.stage in 'ACTIVATED':
parcel_version = parcel.version.split('-')[0]
if parcel_version == version:
logger.info('Detected parcel version matches specified version. Continuing ...')
else:
parcel.deactivate()
# Only one parcel can be activated at a time, so once one is found, our work is done.
break
def _install_parcel_from_remote_repo(deployment, product, version, parcel_repo_version=None):
for config in deployment.get_cm_config():
if config['name'] == 'REMOTE_PARCEL_REPO_URLS':
break
else:
raise Exception('Failed to find remote parcel repo URLs configuration.')
parcel_repo_urls = config['value']
service_parcel_repo_url = '{}/{}'.format(SERVICE_PARCEL_REPO_URLS[product],
parcel_repo_version if parcel_repo_version is not None else version)
logger.debug('Adding parcel repo URL (%s) ...', service_parcel_repo_url)
deployment.update_cm_config(
{'REMOTE_PARCEL_REPO_URLS': '{},{}'.format(parcel_repo_urls,
service_parcel_repo_url)}
)
logger.debug('Refreshing parcel repos ...')
deployment.refresh_parcel_repos()
deployment.cluster(DEFAULT_CLUSTER_NAME).wait_for_parcel_stage(product=product, version=version)
service_parcel = deployment.cluster(DEFAULT_CLUSTER_NAME).parcel(product=product, version=version)
service_parcel.download().distribute().activate()
def _configure_kafka(deployment, cluster, kafka_version, cdh_version_tuple, ssl):
if cdh_version_tuple < EARLIEST_CDH_VERSION_WITH_KAFKA:
_deactivate_service_parcel(deployment, cluster, 'KAFKA', kafka_version)
for parcel in deployment.cluster(DEFAULT_CLUSTER_NAME).parcels:
if parcel.product == 'KAFKA' and parcel.stage in 'ACTIVATED':
break
else:
_install_parcel_from_remote_repo(deployment, 'KAFKA', kafka_version)
logger.info('Adding Kafka service to cluster (%s) ...', DEFAULT_CLUSTER_NAME)
broker_role = {'type': 'KAFKA_BROKER',
'hostRef': {'hostId': cluster.primary_node.host_id}}
for service in deployment.get_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME):
if service['type'] == 'ZOOKEEPER':
break
else:
raise Exception('Could not find ZooKeeper service on cluster %s.', DEFAULT_CLUSTER_NAME)
# Replication factor needs to be set to 1 for CDH Kafka 3.0.0 onwards
# when Default Number of partitions = 1 (which is default).
# Also changing replication factor to 1 works with CDH Kafka < 3.0.0.
deployment.create_cluster_services(
cluster_name=DEFAULT_CLUSTER_NAME,
services=[{'name': 'kafka',
'type': 'KAFKA',
'displayName': 'Kafka',
'roles': [broker_role],
'config': {'items': [{'name': 'zookeeper_service', 'value': service['name']},
{'name': 'offsets.topic.replication.factor', 'value': 1}]}}]
)
for role_config_group in deployment.get_service_role_config_groups(DEFAULT_CLUSTER_NAME,
'kafka'):
if role_config_group['roleType'] == 'KAFKA_BROKER':
logger.debug('Setting Kafka Broker max heap size to 1024 MB ...')
configs = {'broker_max_heap_size': '1024'}
if ssl:
configs.update({'ssl_enabled': 'true',
'ssl_server_keystore_location': '{}/{}.{}'.format(SSL_SERVER_CONTAINER_DIR,
'kafka',
SSL_SERVER_KEYSTORE),
'ssl_server_keystore_password': SSL_SERVER_PASSWORD,
'ssl_server_keystore_keypassword': SSL_SERVER_PASSWORD,
'ssl_client_truststore_location': '{}/{}.{}'.format(SSL_SERVER_CONTAINER_DIR,
'kafka',
SSL_SERVER_TRUSTSTORE),
'ssl_client_truststore_password': SSL_SERVER_PASSWORD})
if ssl == 'authentication':
configs.update({'ssl.client.auth': 'required'})
deployment.update_service_role_config_group_config(DEFAULT_CLUSTER_NAME,
'kafka',
role_config_group['name'],
configs)
data_directories = ' '.join(deployment.get_service_role_config_group_config(
cluster_name=DEFAULT_CLUSTER_NAME,
service_name='kafka',
role_config_group_name=role_config_group['name'],
view='full'
)['log.dirs'].split(','))
cluster.primary_node.execute('rm -rf {}'.format(data_directories))
def _install_service_from_local_repo(cluster, product):
# We install service using local repo /opt/cloudera/parcel-repo.
# Set file and folder permissions correctly.
commands = ['chown -R cloudera-scm:cloudera-scm {} {}'.format(CLUSTERDOCK_CSD_DIRECTORY,
CLUSTERDOCK_PARCEL_REPO_DIRECTORY),
'chmod 644 {}/{}/*.jar'.format(CLUSTERDOCK_CSD_DIRECTORY, product),
'ln -s {}/{}/*.jar {}'.format(CLUSTERDOCK_CSD_DIRECTORY, product, CSD_DIRECTORY),
'chmod 644 {}/*.jar'.format(CSD_DIRECTORY),
'chown cloudera-scm:cloudera-scm {}/*.jar'.format(CSD_DIRECTORY),
'ln -s {}/{}/* {}/'.format(CLUSTERDOCK_PARCEL_REPO_DIRECTORY, product, PARCEL_REPO_DIRECTORY)]
cluster.primary_node.execute(' && '.join(commands))
def _configure_spark2(deployment, cluster, history_server_node):
# The parcel is already present. Hence just distribute and activate it after refresing parcel repos.
deployment.refresh_parcel_repos()
deployment.cluster(DEFAULT_CLUSTER_NAME).wait_for_parcel_stage(product='SPARK2', stage='DOWNLOADED')
parcel = deployment.cluster(DEFAULT_CLUSTER_NAME).parcel(product='SPARK2', stage='DOWNLOADED')
parcel.distribute().activate()
logger.info('Adding Spark2 service to cluster (%s) ...', DEFAULT_CLUSTER_NAME)
service_name = 'spark2_on_yarn'
history_server_role = {'type': 'SPARK2_YARN_HISTORY_SERVER',
'hostRef': {'hostId': history_server_node.host_id}}
gateway_roles = [{'type': 'GATEWAY', 'hostRef': node.host_id}
for node in cluster if node.group in ['primary', 'secondary']]
service_config = {'items': [{'name': 'hive_service', 'value': 'hive', 'sensitive': False},
{'name': 'yarn_service', 'value': 'yarn', 'sensitive': False}]}
deployment.create_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME,
services=[{'name': service_name,
'type': 'SPARK2_ON_YARN',
'displayName': 'Spark2',
'roles': [history_server_role] + gateway_roles,
'config': service_config}])
# first_run_service is needed as it creates HDFS dir. /user/spark/spark2ApplicationHistory that is needed by
# Spark2 History Server. Without that, starting of Spark2 service fails.
deployment.first_run_service(DEFAULT_CLUSTER_NAME, service_name, 300)
def _configure_navigator(deployment, cluster, cdh_version_tuple):
logger.info('Begin trial license for cluster (%s) ...', DEFAULT_CLUSTER_NAME)
deployment.begin_trial()
primary_node = cluster.primary_node
navigator_roles = []
# Fetch the embedded database management properties.
db_mgmt_prop_data = primary_node.get_file(DB_MGMT_PROPERTIES_FILENAME)
if cdh_version_tuple < EARLIEST_CDH_VERSION_WITH_NO_REPORTS_MANAGER_NEEDED:
# These CDH versions need to have Reports Manager role created when license is applied.
logger.info('Updating Reports Manager base role configs ...')
configs = {'headlamp_database_name': 'rman',
'headlamp_database_user': 'rman'}
deployment.update_cm_service_role_config_group_config('mgmt-REPORTSMANAGER-BASE', configs)
logger.info('Configuring Reports Manager role ...')
reports_manager_dbpassword = re.search('com.cloudera.cmf.REPORTSMANAGER.db.password=(.*)', db_mgmt_prop_data)
reports_manager_role = {'type': 'REPORTSMANAGER',
'config': {'items': [
{'name': 'headlamp_database_host',
'value': '{}:{}'.format(primary_node.fqdn, NAVIGATOR_POSTGRESQL_PORT)},
{'name': 'headlamp_database_password',
'value': reports_manager_dbpassword.group(1)},
{'name': 'headlamp_database_type',
'value': 'postgresql'}
]},
'hostRef': {'hostId': cluster.primary_node.host_id}}
navigator_roles.append(reports_manager_role)
logger.info('Configuring Navigator Metaserver role ...')
navigator_metaserver_dbpassword = re.search('cloudera.cmf.NAVIGATORMETASERVER.db.password=(.*)', db_mgmt_prop_data)
navigator_metadata_server_role = {'type': 'NAVIGATORMETASERVER',
'config': {'items': [
{'name': 'nav_metaserver_database_host',
'value': '{}:{}'.format(primary_node.fqdn, NAVIGATOR_POSTGRESQL_PORT)},
{'name': 'nav_metaserver_database_password',
'value': navigator_metaserver_dbpassword.group(1)},
{'name': 'nav_metaserver_database_type',
'value': 'postgresql'}
]},
'hostRef': {'hostId': cluster.primary_node.host_id}}
navigator_roles.append(navigator_metadata_server_role)
logger.info('Configuring Audit Server role ...')
navigator_dbpassword = re.search('com.cloudera.cmf.NAVIGATOR.db.password=(.*)', db_mgmt_prop_data)
navigator_audit_server_role = {'type': 'NAVIGATOR',
'config': {'items': [
{'name': 'navigator_database_host',
'value': '{}:{}'.format(primary_node.fqdn, NAVIGATOR_POSTGRESQL_PORT)},
{'name': 'navigator_database_password',
'value': navigator_dbpassword.group(1)},
{'name': 'navigator_database_type',
'value': 'postgresql'}
]},
'hostRef': {'hostId': primary_node.host_id}}
navigator_roles.append(navigator_audit_server_role)
logger.info('Adding Navigator roles to cluster (%s) ...', DEFAULT_CLUSTER_NAME)
deployment.create_cm_roles(navigator_roles)
def _install_kudu(deployment, kudu_version):
for parcel in deployment.cluster(DEFAULT_CLUSTER_NAME).parcels:
if parcel.product == 'KUDU' and parcel.stage in 'ACTIVATED':
parcel_kudu_version = re.match(KUDU_PARCEL_VERSION_REGEX, parcel.version).group(1)
if parcel_kudu_version == kudu_version:
logger.info('Detected Kudu version matches specified version. Continuing ...')
else:
parcel.deactivate()
for config in deployment.get_cm_config():
if config['name'] == 'REMOTE_PARCEL_REPO_URLS':
break
else:
raise Exception('Failed to find remote parcel repo URLs configuration.')
parcel_repo_urls = config['value']
kudu_parcel_repo_url = '{}/{}'.format(KUDU_PARCEL_REPO_URL,
KUDU_PARCEL_VERSIONS[kudu_version])
logger.debug('Adding Kudu parcel repo URL (%s) ...', kudu_parcel_repo_url)
deployment.update_cm_config(
{'REMOTE_PARCEL_REPO_URLS': '{},{}'.format(parcel_repo_urls,
kudu_parcel_repo_url)}
)
logger.debug('Refreshing parcel repos ...')
deployment.refresh_parcel_repos()
kudu_parcel = next(parcel
for parcel in deployment.cluster(DEFAULT_CLUSTER_NAME).parcels
if parcel.product == 'KUDU'
and parcel.version.split('-')[0] == kudu_version)
kudu_parcel.download().distribute().activate()
# Only one parcel can be activated at a time, so once one is found, our work is done.
break
# Check if service needs to be added and if yes, validate the service version passed.
# Returns services to add if valid.
def _validate_services_to_add(cdh_version_tuple, cm_cluster, exclude_services,
include_services, kafka_version, kudu_version):
services_to_validate = set()
if kafka_version and _is_service_to_add('KAFKA', include_services, exclude_services):
services_to_validate.add('KAFKA')
if kudu_version and _is_service_to_add('KUDU', include_services, exclude_services):
services_to_validate.add('KUDU')
if services_to_validate:
logger.info('Validating passed service versions ...')
cluster_info = cm_cluster.get_cluster_info()
if cluster_info is not None:
cluster_display_name = cluster_info['displayName']
inspect_hosts_contents = cm_cluster.download_command_output(cm_cluster.inspect_hosts())
for service in services_to_validate:
if service == 'KUDU':
if cdh_version_tuple < EARLIEST_CDH_VERSION_WITH_KUDU:
cdh_version_from_map = KUDU_PARCEL_VERSIONS.get(kudu_version)
if cdh_version_from_map is None:
cdh_version = '.'.join(str(i) for i in cdh_version_tuple)
raise Exception('Kudu version {} is not available for '
'CDH {} Aborting ...'.format(kudu_version, cdh_version))
else:
_validate_integrated_service_version(cdh_version_tuple, cluster_display_name,
EARLIEST_CDH_VERSION_WITH_KUDU,
inspect_hosts_contents, 'kudu', kudu_version)
elif service == 'KAFKA':
_validate_integrated_service_version(cdh_version_tuple, cluster_display_name,
EARLIEST_CDH_VERSION_WITH_KAFKA,
inspect_hosts_contents, 'kafka', kafka_version)
return services_to_validate
def _validate_integrated_service_version(cdh_version_tuple, cluster_display_name, earliest_cdh_version_with_service,
inspect_hosts_contents, service_name, service_version):
if cdh_version_tuple >= earliest_cdh_version_with_service:
# Check if the parameter service_version matches integrated service version for the specific CDH version.
for item in inspect_hosts_contents['componentSetByCluster'][cluster_display_name][0]['componentInfo']:
if item['name'] == service_name:
break
else:
cdh_version = '.'.join(str(i) for i in cdh_version_tuple)
raise Exception('Integrated {} version for CDH {} not found.'.format(service_name, cdh_version))
cluster_service_version = item['componentVersion'].split('+')[0]
if service_version != cluster_service_version:
cdh_version = '.'.join(str(i) for i in cdh_version_tuple)
raise Exception('{} version {} does not match integrated version {} for '
'CDH {} Aborting ...'.format(service_name, service_version,
cluster_service_version, cdh_version))
def _configure_kudu(deployment, cluster, kudu_version, cdh_version, single_node):
cdh_version_tuple = tuple(int(i) if i.isdigit() else i for i in cdh_version.split('.'))
if cdh_version_tuple < EARLIEST_CDH_VERSION_WITH_KUDU:
_deactivate_service_parcel(deployment, cluster, 'KUDU', kudu_version)
for parcel in deployment.cluster(DEFAULT_CLUSTER_NAME).parcels:
if parcel.product == 'KUDU' and parcel.stage in 'ACTIVATED':
break
else:
_install_parcel_from_remote_repo(deployment, 'KUDU', kudu_version, KUDU_PARCEL_VERSIONS[kudu_version])
logger.info('Adding Kudu service to cluster (%s) ...', DEFAULT_CLUSTER_NAME)
master_role = {'type': 'KUDU_MASTER',
'hostRef': {'hostId': cluster.primary_node.host_id},
'config': {'items': [{'name': 'fs_wal_dir', 'value': '/data/kudu/master'},
{'name': 'fs_data_dirs', 'value': '/data/kudu/master'}]}}
tserver_node_group = 'secondary' if not single_node else 'primary'
tserver_roles = [{'type': 'KUDU_TSERVER',
'config': {'items': [
{'name': 'fs_wal_dir', 'value': '/data/kudu/tserver'},
{'name': 'fs_data_dirs', 'value': '/data/kudu/tserver'}
]},
'hostRef': node.host_id}
for node in cluster if node.group == tserver_node_group]
service_config = {'items': [{'name': 'gflagfile_service_safety_valve',
'value': '--use_hybrid_clock=false'}]}
deployment.create_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME,
services=[{'name': 'kudu',
'type': 'KUDU',
'displayName': 'Kudu',
'roles': [master_role] + tserver_roles,
'config': service_config}])
for service in deployment.get_cluster_services(cluster_name=DEFAULT_CLUSTER_NAME):
if service['type'] == 'KUDU':
break
else:
raise Exception('Could not find Kudu service.')
for role_config_group in deployment.get_service_role_config_groups(DEFAULT_CLUSTER_NAME,
service['name']):
if role_config_group['roleType'] == 'KUDU_MASTER':
configs = {'fs_wal_dir': '/data/kudu/master',
'fs_data_dirs': '/data/kudu/master'}
deployment.update_service_role_config_group_config(DEFAULT_CLUSTER_NAME,
service['name'],
role_config_group['name'],
configs)
elif role_config_group['roleType'] == 'KUDU_TSERVER':
configs = {'fs_wal_dir': '/data/kudu/tserver',
'fs_data_dirs': '/data/kudu/tserver'}
deployment.update_service_role_config_group_config(DEFAULT_CLUSTER_NAME,
service['name'],
role_config_group['name'],
configs)
def _setup_ssl(cluster, service_list):
_setup_ssl_ca_authority(cluster)
for service in service_list:
# Python kerberos client for Kafka needs files to be generated using kafka.client.keystore.jks
# This is generated in authentication setup. Hence call it always.
_setup_ssl_encryption_authentication(cluster, service)
def _setup_ssl_ca_authority(cluster):
ssl_ca_authority_commands = [
'mkdir -p {}'.format(SSL_SERVER_CONTAINER_DIR),
'mkdir -p {}'.format(SSL_CLIENT_CONTAINER_DIR),
'cd {}'.format(SSL_SERVER_CONTAINER_DIR),
('openssl req -new -newkey rsa:4096 -days 365 -x509 -subj "/CN=Kafka-Security-CA"'
' -keyout ca-private-key -out ca-public-key -nodes'),
]
cluster.primary_node.execute(' && '.join(ssl_ca_authority_commands))
def _setup_ssl_encryption(cluster, service):
cur_service = service.lower()
service_server_keystore = '{}.{}'.format(cur_service, SSL_SERVER_KEYSTORE)
service_server_truststore = '{}.{}'.format(cur_service, SSL_SERVER_TRUSTSTORE)
# Configuration of server side e.g. for Kafka broker.
ssl_server_commands = [
'export SRVPASS={}'.format(SSL_SERVER_PASSWORD),
# Add JAVA_HOME to PATH to make keytool available.
# awk needs single quotes to get the correct value.
"export JAVA_HOME=`echo $(awk -F = '/JAVA_HOME/{print $NF}' /etc/default/cloudera-scm-server)`",
'export PATH=$PATH:$JAVA_HOME/bin',
# Create a broker certificate.