serverSetup.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. #!/usr/bin/env python
  2. '''
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. '''
  17. import optparse
  18. import os
  19. import re
  20. import shutil
  21. import sys
  22. import subprocess
  23. from ambari_commons.exceptions import FatalException
  24. from ambari_commons.firewall import Firewall
  25. from ambari_commons.inet_utils import force_download_file, download_progress
  26. from ambari_commons.logging_utils import get_silent, print_info_msg, print_warning_msg, print_error_msg, get_verbose
  27. from ambari_commons.os_check import OSConst
  28. from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl
  29. from ambari_commons.os_utils import copy_files, run_os_command, is_root
  30. from ambari_commons.str_utils import compress_backslashes
  31. from ambari_server.dbConfiguration import DBMSConfigFactory, check_jdbc_drivers
  32. from ambari_server.serverConfiguration import configDefaults, JDKRelease, \
  33. get_ambari_properties, get_is_secure, get_is_persisted, get_java_exe_path, get_JAVA_HOME, \
  34. get_resources_location, get_value_from_properties, read_ambari_user, update_properties, validate_jdk, write_property, \
  35. JAVA_HOME, JAVA_HOME_PROPERTY, JCE_NAME_PROPERTY, JDBC_RCA_URL_PROPERTY, JDBC_URL_PROPERTY, \
  36. JDK_NAME_PROPERTY, JDK_RELEASES, NR_USER_PROPERTY, OS_FAMILY, OS_FAMILY_PROPERTY, OS_TYPE, OS_TYPE_PROPERTY, OS_VERSION, \
  37. VIEWS_DIR_PROPERTY, JDBC_DATABASE_PROPERTY, JDK_DOWNLOAD_SUPPORTED_PROPERTY, JCE_DOWNLOAD_SUPPORTED_PROPERTY
  38. from ambari_server.serverUtils import is_server_runing
  39. from ambari_server.setupSecurity import adjust_directory_permissions
  40. from ambari_server.userInput import get_YN_input, get_validated_string_input
  41. from ambari_server.utils import locate_file
  42. from ambari_server.serverClassPath import ServerClassPath
  43. # selinux commands
  44. GET_SE_LINUX_ST_CMD = locate_file('sestatus', '/usr/sbin')
  45. SE_SETENFORCE_CMD = "setenforce 0"
  46. SE_STATUS_DISABLED = "disabled"
  47. SE_STATUS_ENABLED = "enabled"
  48. SE_MODE_ENFORCING = "enforcing"
  49. SE_MODE_PERMISSIVE = "permissive"
  50. PERSISTENCE_TYPE_PROPERTY = "server.persistence.type"
  51. TAR_GZ_ARCHIVE_TYPE = ".tar.gz"
  52. # Non-root user setup commands
  53. NR_USER_COMMENT = "Ambari user"
  54. VIEW_EXTRACT_CMD = "{0} -cp {1} " + \
  55. "org.apache.ambari.server.view.ViewRegistry extract {2} " + \
  56. "> " + configDefaults.SERVER_OUT_FILE + " 2>&1"
  57. MAKE_FILE_EXECUTABLE_CMD = "chmod a+x {0}"
  58. # use --no-same-owner when running as root to prevent uucp as the user (AMBARI-6478)
  59. UNTAR_JDK_ARCHIVE = "tar --no-same-owner -xvf {0}"
  60. JDK_PROMPT = "[{0}] {1}\n"
  61. JDK_VALID_CHOICES = "^[{0}{1:d}]$"
  62. def get_supported_jdbc_drivers():
  63. factory = DBMSConfigFactory()
  64. return factory.get_supported_jdbc_drivers()
  65. JDBC_DB_OPTION_VALUES = get_supported_jdbc_drivers()
  66. #
  67. # Setup security prerequisites
  68. #
  69. def verify_setup_allowed(options):
  70. if get_silent():
  71. properties = get_ambari_properties()
  72. if properties == -1:
  73. print_error_msg("Error getting ambari properties")
  74. return -1
  75. isSecure = get_is_secure(properties)
  76. if isSecure:
  77. (isPersisted, masterKeyFile) = get_is_persisted(properties)
  78. if not isPersisted:
  79. print "ERROR: Cannot run silent 'setup' with password encryption enabled " \
  80. "and Master Key not persisted."
  81. print "Ambari Server 'setup' exiting."
  82. return 1
  83. factory = DBMSConfigFactory()
  84. default_dbms = factory.get_default_dbms_name()
  85. if default_dbms:
  86. valid = True
  87. if options.dbms is not None \
  88. and options.database_host is not None \
  89. and options.database_port is not None \
  90. and options.database_name is not None \
  91. and options.database_username is not None \
  92. and options.database_password is not None:
  93. if default_dbms == "sqlanywhere" and options.sqla_server_name is None:
  94. valid = False
  95. else:
  96. valid = False
  97. if not valid:
  98. print "ERROR: Cannot run silent setup without database connection properties provided."
  99. print "Ambari Server 'setup' exiting."
  100. return 2
  101. return 0
  102. #
  103. # Security enhancements (Linux only)
  104. #
  105. #
  106. # Checks SELinux
  107. #
  108. def check_selinux():
  109. try:
  110. retcode, out, err = run_os_command(GET_SE_LINUX_ST_CMD)
  111. se_status = re.search('(disabled|enabled)', out).group(0)
  112. print "SELinux status is '" + se_status + "'"
  113. if se_status == SE_STATUS_DISABLED:
  114. return 0
  115. else:
  116. try:
  117. se_mode = re.search('(enforcing|permissive)', out).group(0)
  118. except AttributeError:
  119. err = "Error determining SELinux mode. Exiting."
  120. raise FatalException(1, err)
  121. print "SELinux mode is '" + se_mode + "'"
  122. if se_mode == SE_MODE_ENFORCING:
  123. print "Temporarily disabling SELinux"
  124. run_os_command(SE_SETENFORCE_CMD)
  125. print_warning_msg(
  126. "SELinux is set to 'permissive' mode and temporarily disabled.")
  127. ok = get_YN_input("OK to continue [y/n] (y)? ", True)
  128. if not ok:
  129. raise FatalException(1, None)
  130. return 0
  131. except OSError:
  132. print_warning_msg("Could not run {0}: OK".format(GET_SE_LINUX_ST_CMD))
  133. return 0
  134. # No security enhancements in Windows
  135. @OsFamilyFuncImpl(OSConst.WINSRV_FAMILY)
  136. def disable_security_enhancements():
  137. retcode = 0
  138. err = ''
  139. return (retcode, err)
  140. @OsFamilyFuncImpl(OsFamilyImpl.DEFAULT)
  141. def disable_security_enhancements():
  142. print 'Checking SELinux...'
  143. err = ''
  144. retcode = check_selinux()
  145. if not retcode == 0:
  146. err = 'Failed to disable SELinux. Exiting.'
  147. return (retcode, err)
  148. #
  149. # User account creation
  150. #
  151. class AmbariUserChecks(object):
  152. def __init__(self):
  153. self.NR_USER_CHANGE_PROMPT = ""
  154. self.NR_USER_CUSTOMIZE_PROMPT = ""
  155. self.NR_DEFAULT_USER = ""
  156. self.NR_USER_COMMENT = "Ambari user"
  157. self.register_service = False
  158. self.user = None
  159. self.password = None
  160. def do_checks(self):
  161. try:
  162. user = read_ambari_user()
  163. if not user:
  164. user = self.NR_DEFAULT_USER
  165. if self.user is not None: #Command-line parameter is the default
  166. update_user_setting = True
  167. prompt_msg = self.NR_USER_CUSTOMIZE_PROMPT.format('y')
  168. else:
  169. update_user_setting = False
  170. if user != self.NR_DEFAULT_USER:
  171. prompt_msg = self.NR_USER_CHANGE_PROMPT.format(user, 'n')
  172. else:
  173. prompt_msg = self.NR_USER_CUSTOMIZE_PROMPT.format('n')
  174. self.user = user if user else self.NR_DEFAULT_USER
  175. self.register_service = get_YN_input(prompt_msg, update_user_setting)
  176. if self.register_service:
  177. retcode = self._create_custom_user()
  178. if retcode != 0:
  179. return retcode
  180. adjust_directory_permissions(self.user)
  181. except OSError as e:
  182. print_error_msg("Failed: %s" % str(e))
  183. return 4
  184. except Exception as e:
  185. print_error_msg("Unexpected error %s" % str(e))
  186. return 1
  187. return 0
  188. def _create_custom_user(self):
  189. pass
  190. @OsFamilyImpl(os_family=OSConst.WINSRV_FAMILY)
  191. class AmbariUserChecksWindows(AmbariUserChecks):
  192. def __init__(self, options):
  193. super(AmbariUserChecksWindows, self).__init__()
  194. self.NR_USER_CHANGE_PROMPT = "Ambari-server service is configured to run under user '{0}'. Change this setting [y/n] ({1})? "
  195. self.NR_USER_CUSTOMIZE_PROMPT = "Customize user account for ambari-server service [y/n] ({0})? "
  196. self.NR_DEFAULT_USER = "NT AUTHORITY\\SYSTEM"
  197. self.NR_SYSTEM_USERS = ["NT AUTHORITY\\SYSTEM", "NT AUTHORITY\\NetworkService", "NT AUTHORITY\\LocalService"]
  198. self.user = options.svc_user
  199. self.password = options.svc_password
  200. def _create_custom_user(self):
  201. user = get_validated_string_input(
  202. "Enter user account for ambari-server service ({0}):".format(self.user),
  203. self.user, None,
  204. "Invalid username.",
  205. False
  206. )
  207. if user in self.NR_SYSTEM_USERS:
  208. self.user = user
  209. return 0
  210. if get_silent():
  211. password = self.password
  212. else:
  213. password = get_validated_string_input("Enter password for user {0}:".format(user), "", None, "Password", True, False)
  214. from ambari_commons.os_windows import UserHelper
  215. uh = UserHelper(user)
  216. if uh.find_user():
  217. print_info_msg("User {0} already exists, make sure that you typed correct password for user, "
  218. "skipping user creation".format(user))
  219. else:
  220. status, message = uh.create_user(password)
  221. if status == UserHelper.USER_EXISTS:
  222. print_info_msg("User {0} already exists, make sure that you typed correct password for user, "
  223. "skipping user creation".format(user))
  224. elif status == UserHelper.ACTION_FAILED: # fail
  225. print_warning_msg("Can't create user {0}. Failed with message {1}".format(user, message))
  226. return UserHelper.ACTION_FAILED
  227. self.password = password
  228. # setting SeServiceLogonRight and SeBatchLogonRight to user
  229. #This is unconditional
  230. status, message = uh.add_user_privilege('SeServiceLogonRight')
  231. if status == UserHelper.ACTION_FAILED:
  232. print_warning_msg("Can't add SeServiceLogonRight to user {0}. Failed with message {1}".format(user, message))
  233. return UserHelper.ACTION_FAILED
  234. status, message = uh.add_user_privilege('SeBatchLogonRight')
  235. if status == UserHelper.ACTION_FAILED:
  236. print_warning_msg("Can't add SeBatchLogonRight to user {0}. Failed with message {1}".format(user, message))
  237. return UserHelper.ACTION_FAILED
  238. print_info_msg("User configuration is done.")
  239. print_warning_msg("When using non SYSTEM user make sure that your user has read\write access to log directories and "
  240. "all server directories. In case of integrated authentication for SQL Server make sure that your "
  241. "user is properly configured to access the ambari database.")
  242. if user.find('\\') == -1:
  243. user = '.\\' + user
  244. self.user = user
  245. return 0
  246. @OsFamilyImpl(os_family=OsFamilyImpl.DEFAULT)
  247. class AmbariUserChecksLinux(AmbariUserChecks):
  248. def __init__(self, options):
  249. super(AmbariUserChecksLinux, self).__init__()
  250. self.NR_USER_CHANGE_PROMPT = "Ambari-server daemon is configured to run under user '{0}'. Change this setting [y/n] ({1})? "
  251. self.NR_USER_CUSTOMIZE_PROMPT = "Customize user account for ambari-server daemon [y/n] ({0})? "
  252. self.NR_DEFAULT_USER = "root"
  253. self.NR_USERADD_CMD = 'useradd -M --comment "{1}" ' \
  254. '--shell %s -d /var/lib/ambari-server/keys/ {0}' % locate_file('nologin', '/sbin')
  255. def _create_custom_user(self):
  256. user = get_validated_string_input(
  257. "Enter user account for ambari-server daemon (root):",
  258. self.user,
  259. "^[a-z_][a-z0-9_-]{1,31}$",
  260. "Invalid username.",
  261. False
  262. )
  263. print_info_msg("Trying to create user {0}".format(user))
  264. command = self.NR_USERADD_CMD.format(user, self.NR_USER_COMMENT)
  265. retcode, out, err = run_os_command(command)
  266. if retcode == 9: # 9 = username already in use
  267. print_info_msg("User {0} already exists, "
  268. "skipping user creation".format(user))
  269. elif retcode != 0: # fail
  270. print_warning_msg("Can't create user {0}. Command {1} "
  271. "finished with {2}: \n{3}".format(user, command, retcode, err))
  272. return retcode
  273. print_info_msg("User configuration is done.")
  274. self.user = user
  275. return 0
  276. def check_ambari_user(options):
  277. uc = AmbariUserChecks(options)
  278. retcode = uc.do_checks()
  279. return retcode, uc.register_service, uc.user, uc.password
  280. #
  281. # Windows service setup
  282. #
  283. @OsFamilyFuncImpl(os_family=OSConst.WINSRV_FAMILY)
  284. def service_setup(register_service, svc_user, svc_password):
  285. from ambari_windows_service import svcsetup
  286. svc_user_setup = svc_user if svc_user.upper() != "NT AUTHORITY\\SYSTEM" else None
  287. result = svcsetup(register_service, svc_user_setup, svc_password)
  288. if result == 0:
  289. write_property(NR_USER_PROPERTY, svc_user)
  290. @OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT)
  291. def service_setup(register_service, svc_user, svc_password):
  292. #Nothing else to do in Linux
  293. write_property(NR_USER_PROPERTY, svc_user)
  294. #
  295. # Firewall
  296. #
  297. def check_firewall():
  298. firewall_obj = Firewall().getFirewallObject()
  299. firewall_on = firewall_obj.check_firewall()
  300. if firewall_obj.stderrdata and len(firewall_obj.stderrdata) > 0:
  301. print firewall_obj.stderrdata
  302. if firewall_on:
  303. print_warning_msg("%s is running. Confirm the necessary Ambari ports are accessible. " %
  304. firewall_obj.FIREWALL_SERVICE_NAME +
  305. "Refer to the Ambari documentation for more details on ports.")
  306. ok = get_YN_input("OK to continue [y/n] (y)? ", True)
  307. if not ok:
  308. raise FatalException(1, None)
  309. #
  310. # ## JDK ###
  311. #
  312. class JDKSetup(object):
  313. def __init__(self):
  314. self.JDK_DEFAULT_CONFIGS = []
  315. self.JDK_PROMPT = "[{0}] {1}\n"
  316. self.JDK_CUSTOM_CHOICE_PROMPT = "[{0}] Custom JDK\n==============================================================================\nEnter choice ({1}): "
  317. self.JDK_VALID_CHOICES = "^[{0}{1:d}]$"
  318. self.JDK_MIN_FILESIZE = 5000
  319. self.JAVA_BIN = ""
  320. self.jdk_index = 0
  321. #
  322. # Downloads and installs the JDK and the JCE policy archive
  323. #
  324. def download_and_install_jdk(self, args, properties):
  325. conf_file = properties.fileName
  326. jcePolicyWarn = "JCE Policy files are required for configuring Kerberos security. If you plan to use Kerberos," \
  327. "please make sure JCE Unlimited Strength Jurisdiction Policy Files are valid on all hosts."
  328. if args.java_home:
  329. #java_home was specified among the command-line arguments. Use it as custom JDK location.
  330. if not validate_jdk(args.java_home):
  331. err = "Path to java home " + args.java_home + " or java binary file does not exists"
  332. raise FatalException(1, err)
  333. print_warning_msg("JAVA_HOME " + args.java_home + " must be valid on ALL hosts")
  334. print_warning_msg(jcePolicyWarn)
  335. IS_CUSTOM_JDK = True
  336. properties.process_pair(JAVA_HOME_PROPERTY, args.java_home)
  337. properties.removeOldProp(JDK_NAME_PROPERTY)
  338. properties.removeOldProp(JCE_NAME_PROPERTY)
  339. self._ensure_java_home_env_var_is_set(args.java_home)
  340. self.jdk_index = self.custom_jdk_number
  341. return
  342. java_home_var = get_JAVA_HOME()
  343. if OS_FAMILY == OSConst.WINSRV_FAMILY:
  344. progress_func = None
  345. else:
  346. progress_func = download_progress
  347. if get_silent():
  348. if not java_home_var:
  349. #No java_home_var set, detect if java is already installed
  350. if os.environ.has_key(JAVA_HOME):
  351. args.java_home = os.environ[JAVA_HOME]
  352. properties.process_pair(JAVA_HOME_PROPERTY, args.java_home)
  353. properties.removeOldProp(JDK_NAME_PROPERTY)
  354. properties.removeOldProp(JCE_NAME_PROPERTY)
  355. self._ensure_java_home_env_var_is_set(args.java_home)
  356. self.jdk_index = self.custom_jdk_number
  357. return
  358. else:
  359. # For now, changing the existing JDK to make sure we use a supported one
  360. pass
  361. if java_home_var:
  362. change_jdk = get_YN_input("Do you want to change Oracle JDK [y/n] (n)? ", False)
  363. if not change_jdk:
  364. self._ensure_java_home_env_var_is_set(java_home_var)
  365. self.jdk_index = self.custom_jdk_number
  366. return
  367. #Continue with the normal setup, taking the first listed JDK version as the default option
  368. jdk_num = str(self.jdk_index + 1)
  369. (self.jdks, jdk_choice_prompt, jdk_valid_choices, self.custom_jdk_number) = self._populate_jdk_configs(properties, jdk_num)
  370. jdk_num = get_validated_string_input(
  371. jdk_choice_prompt,
  372. jdk_num,
  373. jdk_valid_choices,
  374. "Invalid number.",
  375. False
  376. )
  377. self.jdk_index = int(jdk_num) - 1
  378. if self.jdk_index == self.custom_jdk_number:
  379. print_warning_msg("JDK must be installed on all hosts and JAVA_HOME must be valid on all hosts.")
  380. print_warning_msg(jcePolicyWarn)
  381. args.java_home = get_validated_string_input("Path to JAVA_HOME: ", None, None, None, False, False)
  382. if not os.path.exists(args.java_home) or not os.path.isfile(os.path.join(args.java_home, "bin", self.JAVA_BIN)):
  383. err = "Java home path or java binary file is unavailable. Please put correct path to java home."
  384. raise FatalException(1, err)
  385. print "Validating JDK on Ambari Server...done."
  386. properties.process_pair(JAVA_HOME_PROPERTY, args.java_home)
  387. properties.removeOldProp(JDK_NAME_PROPERTY)
  388. properties.removeOldProp(JCE_NAME_PROPERTY)
  389. # Make sure any previously existing JDK and JCE name properties are removed. These will
  390. # confuse things in a Custom JDK scenario
  391. properties.removeProp(JDK_NAME_PROPERTY)
  392. properties.removeProp(JCE_NAME_PROPERTY)
  393. self._ensure_java_home_env_var_is_set(args.java_home)
  394. return
  395. jdk_cfg = self.jdks[self.jdk_index]
  396. resources_dir = get_resources_location(properties)
  397. dest_file = os.path.abspath(os.path.join(resources_dir, jdk_cfg.dest_file))
  398. if os.path.exists(dest_file):
  399. print "JDK already exists, using " + dest_file
  400. elif properties[JDK_DOWNLOAD_SUPPORTED_PROPERTY].upper() == "FALSE":
  401. print "ERROR: Oracle JDK is not found in {1}. JDK download is not supported in this distribution. Please download Oracle JDK " \
  402. "archive ({0}) manually from Oracle site, place it into {1} and re-run this script.".format(jdk_cfg.dest_file, dest_file)
  403. print "NOTE: If you have already downloaded the file, please verify if the name is exactly same as {0}.".format(jdk_cfg.dest_file)
  404. print 'Exiting...'
  405. sys.exit(1)
  406. else:
  407. ok = get_YN_input("To download the Oracle JDK and the Java Cryptography Extension (JCE) "
  408. "Policy Files you must accept the "
  409. "license terms found at "
  410. "http://www.oracle.com/technetwork/java/javase/"
  411. "terms/license/index.html and not accepting will "
  412. "cancel the Ambari Server setup and you must install the JDK and JCE "
  413. "files manually.\nDo you accept the "
  414. "Oracle Binary Code License Agreement [y/n] (y)? ", True)
  415. if not ok:
  416. print 'Exiting...'
  417. sys.exit(1)
  418. jdk_url = jdk_cfg.url
  419. print 'Downloading JDK from ' + jdk_url + ' to ' + dest_file
  420. self._download_jdk(jdk_url, dest_file, progress_func)
  421. try:
  422. (retcode, out, java_home_dir) = self._install_jdk(dest_file, jdk_cfg)
  423. except Exception, e:
  424. print "Installation of JDK has failed: %s\n" % str(e)
  425. file_exists = os.path.isfile(dest_file)
  426. if file_exists:
  427. ok = get_YN_input("JDK found at " + dest_file + ". "
  428. "Would you like to re-download the JDK [y/n] (y)? ", not get_silent())
  429. if not ok:
  430. err = "Unable to install JDK. Please remove JDK file found at " + \
  431. dest_file + " and re-run Ambari Server setup"
  432. raise FatalException(1, err)
  433. else:
  434. jdk_url = jdk_cfg.url
  435. print 'Re-downloading JDK from ' + jdk_url + ' to ' + dest_file
  436. self._download_jdk(jdk_url, dest_file, progress_func)
  437. print 'Successfully re-downloaded JDK distribution to ' + dest_file
  438. try:
  439. (retcode, out) = self._install_jdk(dest_file, jdk_cfg)
  440. except Exception, e:
  441. print "Installation of JDK was failed: %s\n" % str(e)
  442. err = "Unable to install JDK. Please remove JDK, file found at " + \
  443. dest_file + " and re-run Ambari Server setup"
  444. raise FatalException(1, err)
  445. else:
  446. err = "Unable to install JDK. File " + dest_file + " does not exist, " \
  447. "please re-run Ambari Server setup"
  448. raise FatalException(1, err)
  449. properties.process_pair(JDK_NAME_PROPERTY, jdk_cfg.dest_file)
  450. properties.process_pair(JAVA_HOME_PROPERTY, java_home_dir)
  451. self._ensure_java_home_env_var_is_set(java_home_dir)
  452. def download_and_unpack_jce_policy(self, properties):
  453. err_msg_stdout = "JCE Policy files are required for secure HDP setup. Please ensure " \
  454. " all hosts have the JCE unlimited strength policy 6, files."
  455. resources_dir = get_resources_location(properties)
  456. jdk_cfg = self.jdks[self.jdk_index]
  457. try:
  458. JDKSetup._download_jce_policy(jdk_cfg.jcpol_url, jdk_cfg.dest_jcpol_file, resources_dir, properties)
  459. except FatalException, e:
  460. print err_msg_stdout
  461. print_error_msg("Failed to download JCE policy files:")
  462. if e.reason is not None:
  463. print_error_msg("\nREASON: {0}".format(e.reason))
  464. # TODO: We don't fail installation if _download_jce_policy fails. Is it OK?
  465. print 'Installing JCE policy...'
  466. try:
  467. jdk_path = properties.get_property(JAVA_HOME_PROPERTY)
  468. JDKSetup.unpack_jce_policy(jdk_path, resources_dir, jdk_cfg.dest_jcpol_file)
  469. self.adjust_jce_permissions(jdk_path)
  470. except FatalException, e:
  471. print err_msg_stdout
  472. print_error_msg("Failed to install JCE policy files:")
  473. if e.reason is not None:
  474. print_error_msg("\nREASON: {0}".format(e.reason))
  475. # TODO: We don't fail installation if _download_jce_policy fails. Is it OK?
  476. @staticmethod
  477. def unpack_jce_policy(jdk_path, resources_dir, jce_packed_file):
  478. jdk_security_path = os.path.abspath(os.path.join(jdk_path, configDefaults.JDK_SECURITY_DIR))
  479. jce_zip_path = os.path.abspath(os.path.join(resources_dir, jce_packed_file))
  480. expand_jce_zip_file(jce_zip_path, jdk_security_path)
  481. def _populate_jdk_configs(self, properties, jdk_num):
  482. if properties.has_key(JDK_RELEASES):
  483. jdk_names = properties[JDK_RELEASES].split(',')
  484. jdks = []
  485. for jdk_name in jdk_names:
  486. jdkR = JDKRelease.from_properties(properties, jdk_name)
  487. jdks.append(jdkR)
  488. else:
  489. jdks = self.JDK_DEFAULT_CONFIGS
  490. n_config = 1
  491. jdk_choice_prompt = ''
  492. jdk_choices = ''
  493. for jdk in jdks:
  494. jdk_choice_prompt += self.JDK_PROMPT.format(n_config, jdk.desc)
  495. jdk_choices += str(n_config)
  496. n_config += 1
  497. jdk_choice_prompt += self.JDK_CUSTOM_CHOICE_PROMPT.format(n_config, jdk_num)
  498. jdk_valid_choices = self.JDK_VALID_CHOICES.format(jdk_choices, n_config)
  499. return jdks, jdk_choice_prompt, jdk_valid_choices, n_config - 1
  500. def _download_jdk(self, jdk_url, dest_file, progress_func = None):
  501. jdk_download_fail_msg = " Failed to download JDK: {0}. Please check that the " \
  502. "JDK is available at {1}. Also you may specify JDK file " \
  503. "location in local filesystem using --jdk-location command " \
  504. "line argument.".format("{0}", jdk_url)
  505. try:
  506. force_download_file(jdk_url, dest_file, progress_func = progress_func)
  507. print 'Successfully downloaded JDK distribution to ' + dest_file
  508. except FatalException:
  509. raise
  510. except Exception, e:
  511. err = jdk_download_fail_msg.format(str(e))
  512. raise FatalException(1, err)
  513. @staticmethod
  514. def _download_jce_policy(jcpol_url, dest_jcpol_file, resources_dir, properties):
  515. dest_file = os.path.abspath(os.path.join(resources_dir, dest_jcpol_file))
  516. if not os.path.exists(dest_file):
  517. if properties[JCE_DOWNLOAD_SUPPORTED_PROPERTY].upper() == "FALSE":
  518. print "ERROR: JCE Policy archive is not found in {1}. JCE Policy archive download is not supported in this distribution. " \
  519. "Please download JCE Policy archive ({0}) from Oracle site, place it into {1} and re-run this script.".format(dest_jcpol_file, dest_file)
  520. print 'Exiting...'
  521. sys.exit(1)
  522. print 'Downloading JCE Policy archive from ' + jcpol_url + ' to ' + dest_file
  523. try:
  524. force_download_file(jcpol_url, dest_file)
  525. print 'Successfully downloaded JCE Policy archive to ' + dest_file
  526. except FatalException:
  527. raise
  528. except Exception, e:
  529. err = 'Failed to download JCE Policy archive: ' + str(e)
  530. raise FatalException(1, err)
  531. else:
  532. print "JCE Policy archive already exists, using " + dest_file
  533. properties.process_pair(JCE_NAME_PROPERTY, dest_jcpol_file)
  534. # Base implementation, overriden in the subclasses
  535. def _install_jdk(self, java_inst_file, java_home_dir):
  536. pass
  537. def adjust_jce_permissions(self, jdk_path):
  538. pass
  539. # Base implementation, overriden in the subclasses
  540. def _ensure_java_home_env_var_is_set(self, java_home_dir):
  541. pass
  542. @OsFamilyImpl(os_family=OSConst.WINSRV_FAMILY)
  543. class JDKSetupWindows(JDKSetup):
  544. def __init__(self):
  545. super(JDKSetupWindows, self).__init__()
  546. self.JDK_DEFAULT_CONFIGS = [
  547. JDKRelease("jdk7.67", "Oracle JDK 1.7.67",
  548. "http://public-repo-1.hortonworks.com/ARTIFACTS/jdk-7u67-windows-x64.exe", "jdk-7u67-windows-x64.exe",
  549. "http://public-repo-1.hortonworks.com/ARTIFACTS/UnlimitedJCEPolicyJDK7.zip", "UnlimitedJCEPolicyJDK7.zip",
  550. "C:\\jdk1.7.0_67",
  551. "Creating (jdk.*)/jre")
  552. ]
  553. self.jdks = self.JDK_DEFAULT_CONFIGS
  554. self.custom_jdk_number = len(self.jdks)
  555. self.JAVA_BIN = "java.exe"
  556. def _install_jdk(self, java_inst_file, jdk_cfg):
  557. jdk_inst_dir = jdk_cfg.inst_dir
  558. print "Installing JDK to {0}".format(jdk_inst_dir)
  559. if not os.path.exists(jdk_inst_dir):
  560. os.makedirs(jdk_inst_dir)
  561. if java_inst_file.endswith(".exe"):
  562. (dirname, filename) = os.path.split(java_inst_file)
  563. installLogFilePath = os.path.join(configDefaults.OUT_DIR, filename + "-install.log")
  564. #jre7u67.exe /s INSTALLDIR=<dir> STATIC=1 WEB_JAVA=0 /L \\var\\log\\ambari-server\\jre7u67.exe-install.log
  565. installCmd = [
  566. java_inst_file,
  567. "/s",
  568. "INSTALLDIR=" + jdk_inst_dir,
  569. "STATIC=1",
  570. "WEB_JAVA=0",
  571. "/L",
  572. installLogFilePath
  573. ]
  574. retcode, out, err = run_os_command(installCmd)
  575. #TODO: support .msi file installations
  576. #msiexec.exe jre.msi /s INSTALLDIR=<dir> STATIC=1 WEB_JAVA=0 /L \\var\\log\\ambari-server\\jre7u67-install.log ?
  577. else:
  578. err = "JDK installation failed.Unknown file mask."
  579. raise FatalException(1, err)
  580. if retcode == 1603:
  581. # JDK already installed
  582. print "JDK already installed in {0}".format(jdk_inst_dir)
  583. retcode = 0
  584. else:
  585. if retcode != 0:
  586. err = "Installation of JDK returned exit code %s" % retcode
  587. raise FatalException(retcode, err)
  588. print "Successfully installed JDK to {0}".format(jdk_inst_dir)
  589. # Don't forget to adjust the JAVA_HOME env var
  590. return (retcode, out, jdk_inst_dir)
  591. def _ensure_java_home_env_var_is_set(self, java_home_dir):
  592. if not os.environ.has_key(JAVA_HOME) or os.environ[JAVA_HOME] != java_home_dir:
  593. java_home_dir_unesc = compress_backslashes(java_home_dir)
  594. retcode, out, err = run_os_command("SETX {0} {1} /M".format(JAVA_HOME, java_home_dir_unesc))
  595. if retcode != 0:
  596. print_warning_msg("SETX output: " + out)
  597. print_warning_msg("SETX error output: " + err)
  598. err = "Setting JAVA_HOME failed. Exit code={0}".format(retcode)
  599. raise FatalException(1, err)
  600. os.environ[JAVA_HOME] = java_home_dir
  601. @OsFamilyImpl(os_family=OsFamilyImpl.DEFAULT)
  602. class JDKSetupLinux(JDKSetup):
  603. def __init__(self):
  604. super(JDKSetupLinux, self).__init__()
  605. self.JDK_DEFAULT_CONFIGS = [
  606. JDKRelease("jdk1.8", "Oracle JDK 1.8 + Java Cryptography Extension (JCE) Policy Files 8",
  607. "http://public-repo-1.hortonworks.com/ARTIFACTS/jdk-8u60-linux-x64.tar.gz", "jdk-8u60-linux-x64.tar.gz",
  608. "http://public-repo-1.hortonworks.com/ARTIFACTS/jce_policy-8.zip", "jce_policy-8.zip",
  609. "/usr/jdk64/jdk1.8.0_40",
  610. "(jdk.*)/jre")
  611. ]
  612. self.jdks = self.JDK_DEFAULT_CONFIGS
  613. self.custom_jdk_number = len(self.jdks)
  614. self.JAVA_BIN = "java"
  615. self.CREATE_JDK_DIR_CMD = "/bin/mkdir -p {0}"
  616. self.CHMOD_JDK_DIR_CMD = "chmod a+x {0}"
  617. self.SET_JCE_PERMISSIONS = "chown {0} {1}/{2}/*"
  618. # use --no-same-owner when running as root to prevent uucp as the user (AMBARI-6478)
  619. self.UNTAR_JDK_ARCHIVE = "tar --no-same-owner -xvf {0}"
  620. def _install_jdk(self, java_inst_file, jdk_cfg):
  621. jdk_inst_dir = jdk_cfg.inst_dir
  622. print "Installing JDK to {0}".format(jdk_inst_dir)
  623. retcode, out, err = run_os_command(self.CREATE_JDK_DIR_CMD.format(jdk_inst_dir))
  624. retcode, out, err = run_os_command(self.CHMOD_JDK_DIR_CMD.format(jdk_inst_dir))
  625. savedPath = os.getcwd()
  626. os.chdir(jdk_inst_dir)
  627. try:
  628. if java_inst_file.endswith(".gz"):
  629. retcode, out, err = run_os_command(self.UNTAR_JDK_ARCHIVE.format(java_inst_file))
  630. else:
  631. err = "JDK installation failed.Unknown file extension."
  632. raise FatalException(1, err)
  633. finally:
  634. os.chdir(savedPath)
  635. if retcode != 0:
  636. err = "Installation of JDK returned exit code %s" % retcode
  637. raise FatalException(retcode, err)
  638. jdk_version = re.search(jdk_cfg.reg_exp, out).group(1)
  639. java_home_dir = os.path.join(jdk_inst_dir, jdk_version)
  640. print "Successfully installed JDK to {0}".format(jdk_inst_dir)
  641. return (retcode, out, java_home_dir)
  642. def _ensure_java_home_env_var_is_set(self, java_home_dir):
  643. #No way to do this in Linux. Best we can is to set the process environment variable.
  644. os.environ[JAVA_HOME] = java_home_dir
  645. def adjust_jce_permissions(self, jdk_path):
  646. ambari_user = read_ambari_user()
  647. cmd = self.SET_JCE_PERMISSIONS.format(ambari_user, jdk_path,configDefaults.JDK_SECURITY_DIR)
  648. process = subprocess.Popen(cmd,
  649. stdout=subprocess.PIPE,
  650. stdin=subprocess.PIPE,
  651. stderr=subprocess.PIPE,
  652. shell=True
  653. )
  654. (stdoutdata, stderrdata) = process.communicate()
  655. def download_and_install_jdk(options):
  656. properties = get_ambari_properties()
  657. if properties == -1:
  658. err = "Error getting ambari properties"
  659. raise FatalException(-1, err)
  660. jdkSetup = JDKSetup()
  661. jdkSetup.download_and_install_jdk(options, properties)
  662. if jdkSetup.jdk_index != jdkSetup.custom_jdk_number:
  663. jdkSetup.download_and_unpack_jce_policy(properties)
  664. update_properties(properties)
  665. return 0
  666. #
  667. # Configures the OS settings in ambari properties.
  668. #
  669. def configure_os_settings():
  670. properties = get_ambari_properties()
  671. if properties == -1:
  672. print_error_msg("Error getting ambari properties")
  673. return -1
  674. try:
  675. conf_os_type = properties[OS_TYPE_PROPERTY]
  676. if conf_os_type != '':
  677. print_info_msg("os_type already set in the properties file")
  678. return 0
  679. except (KeyError):
  680. print_error_msg("os_type is not set in the properties file. Setting it now.")
  681. # to check server/agent compatibility
  682. master_os_family = OS_FAMILY + OS_VERSION
  683. # to check supported os_types
  684. master_os_type = OS_TYPE + OS_VERSION
  685. write_property(OS_FAMILY_PROPERTY, master_os_family)
  686. write_property(OS_TYPE_PROPERTY, master_os_type)
  687. return 0
  688. #
  689. # JDBC
  690. #
  691. def _check_jdbc_options(options):
  692. return (options.jdbc_driver is not None and options.jdbc_db is not None)
  693. def proceedJDBCProperties(args):
  694. if not os.path.isfile(args.jdbc_driver):
  695. err = "File {0} does not exist!".format(args.jdbc_driver)
  696. raise FatalException(1, err)
  697. if args.jdbc_db not in JDBC_DB_OPTION_VALUES:
  698. err = "Unsupported database name {0}. Please see help for more information.".format(args.jdbc_db)
  699. raise FatalException(1, err)
  700. _cache_jdbc_driver(args)
  701. # No JDBC driver caching in Windows at this point. Will cache it along with the integrated authentication dll into a
  702. # zip archive at a later moment.
  703. @OsFamilyFuncImpl(os_family=OSConst.WINSRV_FAMILY)
  704. def _cache_jdbc_driver(args):
  705. pass
  706. #TODO JDBC driver caching almost duplicates the LinuxDBMSConfig._install_jdbc_driver() functionality
  707. @OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT)
  708. def _cache_jdbc_driver(args):
  709. properties = get_ambari_properties()
  710. if properties == -1:
  711. err = "Error getting ambari properties"
  712. raise FatalException(-1, err)
  713. resources_dir = get_resources_location(properties)
  714. if args.jdbc_driver.endswith(TAR_GZ_ARCHIVE_TYPE):
  715. symlink_name = args.jdbc_db + "-jdbc-driver" + TAR_GZ_ARCHIVE_TYPE
  716. else:
  717. symlink_name = args.jdbc_db + "-jdbc-driver.jar"
  718. jdbc_symlink = os.path.join(resources_dir, symlink_name)
  719. path, jdbc_name = os.path.split(args.jdbc_driver)
  720. if os.path.lexists(jdbc_symlink):
  721. os.remove(jdbc_symlink)
  722. if os.path.isfile(os.path.join(resources_dir, jdbc_name)):
  723. os.remove(os.path.join(resources_dir, jdbc_name))
  724. try:
  725. shutil.copy(args.jdbc_driver, resources_dir)
  726. print "Copying {0} to {1}".format(args.jdbc_driver, resources_dir)
  727. except Exception, e:
  728. err = "Can not copy file {0} to {1} due to: {2} . Please check file " \
  729. "permissions and free disk space.".format(args.jdbc_driver, resources_dir, str(e))
  730. raise FatalException(1, err)
  731. os.symlink(os.path.join(resources_dir, jdbc_name), jdbc_symlink)
  732. print "JDBC driver was successfully initialized."
  733. #
  734. # Database
  735. #
  736. # Ask user for database connection properties
  737. def prompt_db_properties(options):
  738. factory = DBMSConfigFactory()
  739. if not factory.force_dbms_setup():
  740. ok = False
  741. if options.must_set_database_options:
  742. ok = get_YN_input("Enter advanced database configuration [y/n] (n)? ", False)
  743. else:
  744. ok = True
  745. print 'Configuring database...'
  746. options.must_set_database_options = ok
  747. options.database_index = factory.select_dbms(options)
  748. def _setup_database(options):
  749. properties = get_ambari_properties()
  750. if properties == -1:
  751. raise FatalException(-1, "Error getting ambari properties")
  752. factory = DBMSConfigFactory()
  753. dbmsAmbari = factory.create(options, properties, "Ambari")
  754. resultA = dbmsAmbari.configure_database(properties)
  755. # Now save the properties file
  756. if resultA:
  757. update_properties(properties)
  758. dbmsAmbari.setup_database()
  759. def _createDefDbFactory(options):
  760. properties = get_ambari_properties()
  761. if properties == -1:
  762. raise FatalException(-1, "Error getting ambari properties")
  763. if not (properties.getPropertyDict().has_key(JDBC_URL_PROPERTY) and
  764. properties.getPropertyDict().has_key(JDBC_RCA_URL_PROPERTY)):
  765. raise FatalException(-1, "Ambari Server not set up yet. Nothing to reset.")
  766. empty_options = optparse.Values()
  767. empty_options.must_set_database_options = options.must_set_database_options
  768. empty_options.database_index = options.database_index
  769. empty_options.database_host = ""
  770. empty_options.database_port = ""
  771. empty_options.database_name = ""
  772. empty_options.database_windows_auth = False
  773. empty_options.database_username = ""
  774. empty_options.database_password = ""
  775. empty_options.init_db_script_file = ""
  776. empty_options.cleanup_db_script_file = ""
  777. factory = DBMSConfigFactory()
  778. return empty_options, factory, properties
  779. def _reset_database(options):
  780. properties = get_ambari_properties()
  781. if properties == -1:
  782. print_error_msg("Error getting ambari properties")
  783. return -1
  784. persistence_type = properties[PERSISTENCE_TYPE_PROPERTY]
  785. if persistence_type == "remote":
  786. err = 'Ambari doesn\'t support resetting exernal DB automatically. ' \
  787. 'To reset Ambari Server schema you must first drop and then create it ' \
  788. 'using DDL scripts from "/var/lib/ambari-server/resources/"'
  789. raise FatalException(1, err)
  790. else:
  791. factory = DBMSConfigFactory()
  792. dbmsAmbari = factory.create(options, properties)
  793. dbmsAmbari.reset_database()
  794. #
  795. # Extract the system views
  796. #
  797. def extract_views(options):
  798. java_exe_path = get_java_exe_path()
  799. if java_exe_path is None:
  800. print_error_msg("No JDK found, please run the \"setup\" "
  801. "command to install a JDK automatically or install any "
  802. "JDK manually to " + configDefaults.JDK_INSTALL_DIR)
  803. return 1
  804. properties = get_ambari_properties()
  805. if properties == -1:
  806. print_error_msg("Error getting ambari properties")
  807. return -1
  808. vdir = get_value_from_properties(properties, VIEWS_DIR_PROPERTY, configDefaults.DEFAULT_VIEWS_DIR)
  809. files = [f for f in os.listdir(vdir) if os.path.isfile(os.path.join(vdir,f))]
  810. serverClassPath = ServerClassPath(get_ambari_properties(), options)
  811. for f in files:
  812. command = VIEW_EXTRACT_CMD.format(java_exe_path,
  813. serverClassPath.get_full_ambari_classpath_escaped_for_shell(), os.path.join(vdir,f))
  814. retcode, stdout, stderr = run_os_command(command)
  815. if retcode == 0:
  816. sys.stdout.write(f + "\n")
  817. elif retcode == 2:
  818. sys.stdout.write("Error extracting " + f + "\n")
  819. else:
  820. sys.stdout.write(".")
  821. sys.stdout.flush()
  822. print_info_msg("Return code from extraction of view archive " + f + ": " +
  823. str(retcode))
  824. sys.stdout.write("\n")
  825. return 0
  826. def expand_jce_zip_file(jce_zip_path, jdk_security_path):
  827. f = None
  828. import zipfile
  829. if os.path.exists(jdk_security_path) and os.path.exists(jce_zip_path):
  830. try:
  831. f = zipfile.ZipFile(jce_zip_path, "r")
  832. zip_members = f.namelist()
  833. for member in zip_members:
  834. if member.endswith(os.sep):
  835. os.makedirs(os.path.join(jdk_security_path, member))
  836. else:
  837. f.extract(member, jdk_security_path)
  838. unziped_jce_path = os.path.split(zip_members[len(zip_members) - 1])[0]
  839. finally:
  840. try:
  841. f.close()
  842. except Exception as e:
  843. err = "Fail during the extraction of {0}.".format(jce_zip_path)
  844. raise FatalException(1, err)
  845. else:
  846. err = "The path {0} or {1} is invalid.".format(jdk_security_path, jce_zip_path)
  847. raise FatalException(1, err)
  848. if unziped_jce_path:
  849. from_path = os.path.join(jdk_security_path, unziped_jce_path)
  850. jce_files = os.listdir(from_path)
  851. for i in range(len(jce_files)):
  852. jce_files[i] = os.path.join(from_path, jce_files[i])
  853. copy_files(jce_files, jdk_security_path)
  854. dir_to_delete = os.path.join(jdk_security_path, unziped_jce_path.split(os.sep)[0])
  855. shutil.rmtree(dir_to_delete)
  856. def check_setup_already_done():
  857. properties = get_ambari_properties()
  858. if properties == -1:
  859. print_error_msg("Error getting ambari properties")
  860. return -1
  861. return properties.get_property(JDK_NAME_PROPERTY) and properties.get_property(JDBC_DATABASE_PROPERTY)
  862. #
  863. # Setup the Ambari Server.
  864. #
  865. def setup(options):
  866. if options.only_silent:
  867. if check_setup_already_done():
  868. print "Nothing was done. Ambari Setup already performed and cannot re-run setup in silent mode. Use \"ambari-server setup\" command without -s option to change Ambari setup."
  869. sys.exit(0)
  870. retcode = verify_setup_allowed(options)
  871. if not retcode == 0:
  872. raise FatalException(1, None)
  873. if not is_root():
  874. err = configDefaults.MESSAGE_ERROR_SETUP_NOT_ROOT
  875. raise FatalException(4, err)
  876. # proceed jdbc properties if they were set
  877. if _check_jdbc_options(options):
  878. proceedJDBCProperties(options)
  879. return
  880. (retcode, err) = disable_security_enhancements()
  881. if not retcode == 0:
  882. raise FatalException(retcode, err)
  883. #Create ambari user, if needed
  884. (retcode, register_service, svc_user, svc_password) = check_ambari_user(options)
  885. if not retcode == 0:
  886. err = 'Failed to create user. Exiting.'
  887. raise FatalException(retcode, err)
  888. print configDefaults.MESSAGE_CHECK_FIREWALL
  889. check_firewall()
  890. # proceed jdbc properties if they were set
  891. if _check_jdbc_options(options):
  892. proceedJDBCProperties(options)
  893. print 'Checking JDK...'
  894. try:
  895. download_and_install_jdk(options)
  896. except FatalException as e:
  897. err = 'Downloading or installing JDK failed: {0}. Exiting.'.format(e)
  898. raise FatalException(e.code, err)
  899. print 'Completing setup...'
  900. retcode = configure_os_settings()
  901. if not retcode == 0:
  902. err = 'Configure of OS settings in ambari.properties failed. Exiting.'
  903. raise FatalException(retcode, err)
  904. print 'Configuring database...'
  905. prompt_db_properties(options)
  906. #DB setup should be done last after doing any setup.
  907. _setup_database(options)
  908. check_jdbc_drivers(options)
  909. print 'Extracting system views...'
  910. retcode = extract_views(options)
  911. if not retcode == 0:
  912. err = 'Error while extracting system views. Exiting'
  913. raise FatalException(retcode, err)
  914. # we've already done this, but new files were created so run it one time.
  915. adjust_directory_permissions(svc_user)
  916. service_setup(register_service, svc_user, svc_password)
  917. #
  918. # Setup the JCE policy for Ambari Server.
  919. #
  920. def setup_jce_policy(args):
  921. if not os.path.exists(args[1]):
  922. err = "Can not run 'setup-jce'. Invalid path {0}.".format(args[1])
  923. raise FatalException(1, err)
  924. properties = get_ambari_properties()
  925. resources_dir = get_resources_location(properties)
  926. zip_path = os.path.split(args[1])
  927. zip_dir = zip_path[0]
  928. if not zip_dir == resources_dir:
  929. try:
  930. shutil.copy(args[1], resources_dir)
  931. except Exception as e:
  932. err = "Fail while trying to copy {0} to {1}. {2}".format(args[1], resources_dir, e)
  933. raise FatalException(1, err)
  934. jdk_path = properties.get_property(JAVA_HOME_PROPERTY)
  935. if not jdk_path or not os.path.exists(jdk_path):
  936. err = "JDK not installed, you need to run 'ambari-server setup' before attempting to install the JCE policy."
  937. raise FatalException(1, err)
  938. zip_name = zip_path[1]
  939. properties.process_pair(JCE_NAME_PROPERTY, zip_name)
  940. print 'Installing JCE policy...'
  941. try:
  942. JDKSetup.unpack_jce_policy(jdk_path, resources_dir, zip_name)
  943. except FatalException as e:
  944. err = 'Installing JCE failed: {0}. Exiting.'.format(e)
  945. raise FatalException(e.code, err)
  946. update_properties(properties)
  947. print 'NOTE: Restart Ambari Server to apply changes' + \
  948. ' ("ambari-server restart|stop|start")'
  949. #
  950. # Resets the Ambari Server.
  951. #
  952. def reset(options):
  953. if not is_root():
  954. err = configDefaults.MESSAGE_ERROR_RESET_NOT_ROOT
  955. raise FatalException(4, err)
  956. status, stateDesc = is_server_runing()
  957. if status:
  958. err = 'Ambari-server must be stopped to reset'
  959. raise FatalException(1, err)
  960. #force reset if silent option provided
  961. if get_silent():
  962. default = "yes"
  963. else:
  964. default = "no"
  965. choice = get_YN_input("**** WARNING **** You are about to reset and clear the "
  966. "Ambari Server database. This will remove all cluster "
  967. "host and configuration information from the database. "
  968. "You will be required to re-configure the Ambari server "
  969. "and re-run the cluster wizard. \n"
  970. "Are you SURE you want to perform the reset "
  971. "[yes/no] ({0})? ".format(default), get_silent())
  972. okToRun = choice
  973. if not okToRun:
  974. err = "Ambari Server 'reset' cancelled"
  975. raise FatalException(1, err)
  976. _reset_database(options)
  977. pass