serverConfiguration.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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 datetime
  18. import glob
  19. import os
  20. import re
  21. import shutil
  22. import stat
  23. import string
  24. import sys
  25. import tempfile
  26. from ambari_commons.exceptions import FatalException
  27. from ambari_commons.os_check import OSCheck, OSConst
  28. from ambari_commons.os_family_impl import OsFamilyImpl
  29. from ambari_commons.os_utils import run_os_command, search_file, set_file_permissions
  30. from ambari_commons.logging_utils import get_debug_mode, print_info_msg, print_warning_msg, print_error_msg, \
  31. set_debug_mode
  32. from ambari_server.properties import Properties
  33. from ambari_server.userInput import get_validated_string_input
  34. from ambari_server.utils import compare_versions, locate_file
  35. OS_VERSION = OSCheck().get_os_major_version()
  36. OS_TYPE = OSCheck.get_os_type()
  37. OS_FAMILY = OSCheck.get_os_family()
  38. PID_NAME = "ambari-server.pid"
  39. # Non-root user setup commands
  40. NR_USER_PROPERTY = "ambari-server.user"
  41. BLIND_PASSWORD = "*****"
  42. # Common messages
  43. PRESS_ENTER_MSG = "Press <enter> to continue."
  44. OS_FAMILY_PROPERTY = "server.os_family"
  45. OS_TYPE_PROPERTY = "server.os_type"
  46. BOOTSTRAP_DIR_PROPERTY = "bootstrap.dir"
  47. AMBARI_CONF_VAR = "AMBARI_CONF_DIR"
  48. AMBARI_PROPERTIES_FILE = "ambari.properties"
  49. GET_FQDN_SERVICE_URL = "server.fqdn.service.url"
  50. SERVER_OUT_FILE_KEY = "ambari.output.file.path"
  51. VERBOSE_OUTPUT_KEY = "ambari.output.verbose"
  52. DEBUG_MODE_KEY = "ambari.server.debug"
  53. SUSPEND_START_MODE_KEY = "ambari.server.debug.suspend.start"
  54. # Environment variables
  55. AMBARI_SERVER_LIB = "AMBARI_SERVER_LIB"
  56. JAVA_HOME = "JAVA_HOME"
  57. AMBARI_VERSION_VAR = "AMBARI_VERSION_VAR"
  58. # JDK
  59. JAVA_HOME_PROPERTY = "java.home"
  60. JDK_NAME_PROPERTY = "jdk.name"
  61. JCE_NAME_PROPERTY = "jce.name"
  62. # JDBC
  63. JDBC_PATTERNS = {"oracle": "*ojdbc*.jar", "mysql": "*mysql*.jar", "mssql": "*sqljdbc*.jar"}
  64. #TODO property used incorrectly in local case, it was meant to be dbms name, not postgres database name,
  65. # has workaround for now, as we don't need dbms name if persistence_type=local
  66. JDBC_DATABASE_PROPERTY = "server.jdbc.database" # E.g., embedded|oracle|mysql|mssql|postgres
  67. JDBC_DATABASE_NAME_PROPERTY = "server.jdbc.database_name" # E.g., ambari. Not used on Windows.
  68. JDBC_HOSTNAME_PROPERTY = "server.jdbc.hostname"
  69. JDBC_PORT_PROPERTY = "server.jdbc.port"
  70. JDBC_POSTGRES_SCHEMA_PROPERTY = "server.jdbc.postgres.schema" # Only for postgres, defaults to same value as DB name
  71. JDBC_USER_NAME_PROPERTY = "server.jdbc.user.name"
  72. JDBC_PASSWORD_PROPERTY = "server.jdbc.user.passwd"
  73. JDBC_PASSWORD_FILENAME = "password.dat"
  74. JDBC_RCA_PASSWORD_FILENAME = "rca_password.dat"
  75. CLIENT_API_PORT_PROPERTY = "client.api.port"
  76. CLIENT_API_PORT = "8080"
  77. SERVER_VERSION_FILE_PATH = "server.version.file"
  78. PERSISTENCE_TYPE_PROPERTY = "server.persistence.type"
  79. JDBC_DRIVER_PROPERTY = "server.jdbc.driver"
  80. JDBC_DRIVER_PATH_PROPERTY = "server.jdbc.driver.path"
  81. JDBC_URL_PROPERTY = "server.jdbc.url"
  82. JDBC_RCA_DATABASE_PROPERTY = "server.jdbc.database"
  83. JDBC_RCA_HOSTNAME_PROPERTY = "server.jdbc.hostname"
  84. JDBC_RCA_PORT_PROPERTY = "server.jdbc.port"
  85. JDBC_RCA_SCHEMA_PROPERTY = "server.jdbc.schema"
  86. JDBC_RCA_DRIVER_PROPERTY = "server.jdbc.rca.driver"
  87. JDBC_RCA_URL_PROPERTY = "server.jdbc.rca.url"
  88. JDBC_RCA_USER_NAME_PROPERTY = "server.jdbc.rca.user.name"
  89. JDBC_RCA_PASSWORD_FILE_PROPERTY = "server.jdbc.rca.user.passwd"
  90. JDBC_RCA_PASSWORD_ALIAS = "ambari.db.password"
  91. ### # Windows-specific # ###
  92. JDBC_USE_INTEGRATED_AUTH_PROPERTY = "server.jdbc.use.integrated.auth"
  93. JDBC_RCA_USE_INTEGRATED_AUTH_PROPERTY = "server.jdbc.rca.use.integrated.auth"
  94. ### # End Windows-specific # ###
  95. # resources repo configuration
  96. RESOURCES_DIR_PROPERTY = "resources.dir"
  97. # stack repo upgrade
  98. STACK_LOCATION_KEY = 'metadata.path'
  99. # LDAP security
  100. IS_LDAP_CONFIGURED = "ambari.ldap.isConfigured"
  101. LDAP_MGR_PASSWORD_ALIAS = "ambari.ldap.manager.password"
  102. LDAP_MGR_PASSWORD_PROPERTY = "authentication.ldap.managerPassword"
  103. LDAP_MGR_PASSWORD_FILENAME = "ldap-password.dat"
  104. LDAP_MGR_USERNAME_PROPERTY = "authentication.ldap.managerDn"
  105. LDAP_PRIMARY_URL_PROPERTY = "authentication.ldap.primaryUrl"
  106. # SSL truststore
  107. SSL_TRUSTSTORE_PASSWORD_ALIAS = "ambari.ssl.trustStore.password"
  108. SSL_TRUSTSTORE_PATH_PROPERTY = "ssl.trustStore.path"
  109. SSL_TRUSTSTORE_PASSWORD_PROPERTY = "ssl.trustStore.password"
  110. SSL_TRUSTSTORE_TYPE_PROPERTY = "ssl.trustStore.type"
  111. # SSL common
  112. SSL_API = 'api.ssl'
  113. SSL_API_PORT = 'client.api.ssl.port'
  114. DEFAULT_SSL_API_PORT = 8443
  115. # JDK
  116. JDK_RELEASES="java.releases"
  117. VIEWS_DIR_PROPERTY = "views.dir"
  118. #Common setup or upgrade message
  119. SETUP_OR_UPGRADE_MSG = "- If this is a new setup, then run the \"ambari-server setup\" command to create the user\n" \
  120. "- If this is an upgrade of an existing setup, run the \"ambari-server upgrade\" command.\n" \
  121. "Refer to the Ambari documentation for more information on setup and upgrade."
  122. DEFAULT_DB_NAME = "ambari"
  123. class ServerConfigDefaults(object):
  124. def __init__(self):
  125. self.JAVA_SHARE_PATH = "/usr/share/java"
  126. self.OUT_DIR = os.sep + os.path.join("var", "log", "ambari-server")
  127. self.SERVER_OUT_FILE = os.path.join(self.OUT_DIR, "ambari-server.out")
  128. self.SERVER_LOG_FILE = os.path.join(self.OUT_DIR, "ambari-server.log")
  129. self.ROOT_FS_PATH = os.sep
  130. self.JDK_INSTALL_DIR = ""
  131. self.JDK_SEARCH_PATTERN = ""
  132. self.JAVA_EXE_SUBPATH = ""
  133. self.JDK_SECURITY_DIR = os.path.join("jre", "lib", "security")
  134. self.SERVER_RESOURCES_DIR = ""
  135. # Configuration defaults
  136. self.DEFAULT_CONF_DIR = ""
  137. self.PID_DIR = os.sep + os.path.join("var", "run", "ambari-server")
  138. self.DEFAULT_LIBS_DIR = ""
  139. self.AMBARI_PROPERTIES_BACKUP_FILE = ""
  140. # ownership/permissions mapping
  141. # path - permissions - user - group - recursive
  142. # Rules are executed in the same order as they are listed
  143. # {0} in user/group will be replaced by customized ambari-server username
  144. self.NR_ADJUST_OWNERSHIP_LIST = []
  145. self.NR_USERADD_CMD = ""
  146. self.MASTER_KEY_FILE_PERMISSIONS = "600"
  147. self.CREDENTIALS_STORE_FILE_PERMISSIONS = "600"
  148. self.TRUST_STORE_LOCATION_PERMISSIONS = "600"
  149. self.DEFAULT_DB_NAME = "ambari"
  150. self.STACK_LOCATION_DEFAULT = ""
  151. self.DEFAULT_VIEWS_DIR = ""
  152. #keytool commands
  153. self.keytool_bin_subpath = ""
  154. #Standard messages
  155. self.MESSAGE_SERVER_RUNNING_AS_ROOT = ""
  156. self.MESSAGE_ERROR_SETUP_NOT_ROOT = ""
  157. self.MESSAGE_ERROR_RESET_NOT_ROOT = ""
  158. self.MESSAGE_ERROR_UPGRADE_NOT_ROOT = ""
  159. self.MESSAGE_CHECK_FIREWALL = ""
  160. @OsFamilyImpl(os_family=OSConst.WINSRV_FAMILY)
  161. class ServerConfigDefaultsWindows(ServerConfigDefaults):
  162. def __init__(self):
  163. super(ServerConfigDefaultsWindows, self).__init__()
  164. self.JDK_INSTALL_DIR = "C:\\"
  165. self.JDK_SEARCH_PATTERN = "j[2se|dk|re]*"
  166. self.JAVA_EXE_SUBPATH = "bin\\java.exe"
  167. # Configuration defaults
  168. self.DEFAULT_CONF_DIR = "conf"
  169. self.DEFAULT_LIBS_DIR = "lib"
  170. self.AMBARI_PROPERTIES_BACKUP_FILE = "ambari.properties.backup"
  171. # ownership/permissions mapping
  172. # path - permissions - user - group - recursive
  173. # Rules are executed in the same order as they are listed
  174. # {0} in user/group will be replaced by customized ambari-server username
  175. # The permissions are icacls
  176. self.NR_ADJUST_OWNERSHIP_LIST = [
  177. (self.OUT_DIR, "M", "{0}", True), #0110-0100-0100 rw-r-r
  178. (self.OUT_DIR, "F", "{0}", False), #0111-0101-0101 rwx-rx-rx
  179. (self.PID_DIR, "M", "{0}", True),
  180. (self.PID_DIR, "F", "{0}", False),
  181. ("bootstrap", "F", "{0}", False),
  182. ("ambari-env.cmd", "F", "{0}", False),
  183. ("keystore", "M", "{0}", True),
  184. ("keystore", "F", "{0}", False),
  185. ("keystore\\db", "700", "{0}", False),
  186. ("keystore\\db\\newcerts", "700", "{0}", False),
  187. ("resources\\stacks", "755", "{0}", True),
  188. ("resources\\custom_actions", "755", "{0}", True),
  189. ("conf", "644", "{0}", True),
  190. ("conf", "755", "{0}", False),
  191. ("conf\\password.dat", "640", "{0}", False),
  192. # Also, /etc/ambari-server/conf/password.dat
  193. # is generated later at store_password_file
  194. ]
  195. self.NR_USERADD_CMD = "cmd /C net user {0} {1} /ADD"
  196. self.SERVER_RESOURCES_DIR = "resources"
  197. self.STACK_LOCATION_DEFAULT = "resources\\stacks"
  198. self.DEFAULT_VIEWS_DIR = "resources\\views"
  199. #keytool commands
  200. self.keytool_bin_subpath = "bin\\keytool.exe"
  201. #Standard messages
  202. self.MESSAGE_SERVER_RUNNING_AS_ROOT = "Ambari Server running with 'root' privileges."
  203. self.MESSAGE_ERROR_SETUP_NOT_ROOT = "Ambari-server setup must be run with administrator-level privileges"
  204. self.MESSAGE_ERROR_RESET_NOT_ROOT = "Ambari-server reset must be run with administrator-level privileges"
  205. self.MESSAGE_ERROR_UPGRADE_NOT_ROOT = "Ambari-server upgrade must be run with administrator-level privileges"
  206. self.MESSAGE_CHECK_FIREWALL = "Checking firewall status..."
  207. @OsFamilyImpl(os_family=OsFamilyImpl.DEFAULT)
  208. class ServerConfigDefaultsLinux(ServerConfigDefaults):
  209. def __init__(self):
  210. super(ServerConfigDefaultsLinux, self).__init__()
  211. # JDK
  212. self.JDK_INSTALL_DIR = "/usr/jdk64"
  213. self.JDK_SEARCH_PATTERN = "jdk*"
  214. self.JAVA_EXE_SUBPATH = "bin/java"
  215. # Configuration defaults
  216. self.DEFAULT_CONF_DIR = "/etc/ambari-server/conf"
  217. self.DEFAULT_LIBS_DIR = "/usr/lib/ambari-server"
  218. self.AMBARI_PROPERTIES_BACKUP_FILE = "ambari.properties.rpmsave"
  219. # ownership/permissions mapping
  220. # path - permissions - user - group - recursive
  221. # Rules are executed in the same order as they are listed
  222. # {0} in user/group will be replaced by customized ambari-server username
  223. self.NR_ADJUST_OWNERSHIP_LIST = [
  224. ("/var/log/ambari-server", "644", "{0}", True),
  225. ("/var/log/ambari-server", "755", "{0}", False),
  226. ("/var/run/ambari-server", "644", "{0}", True),
  227. ("/var/run/ambari-server", "755", "{0}", False),
  228. ("/var/run/ambari-server/bootstrap", "755", "{0}", False),
  229. ("/var/lib/ambari-server/ambari-env.sh", "700", "{0}", False),
  230. ("/var/lib/ambari-server/keys", "600", "{0}", True),
  231. ("/var/lib/ambari-server/keys", "700", "{0}", False),
  232. ("/var/lib/ambari-server/keys/db", "700", "{0}", False),
  233. ("/var/lib/ambari-server/keys/db/newcerts", "700", "{0}", False),
  234. ("/var/lib/ambari-server/keys/.ssh", "700", "{0}", False),
  235. ("/var/lib/ambari-server/resources/stacks/", "755", "{0}", True),
  236. ("/var/lib/ambari-server/resources/custom_actions/", "755", "{0}", True),
  237. ("/var/lib/ambari-server/resources/host_scripts/", "755", "{0}", True),
  238. ("/var/lib/ambari-server/resources/views", "644", "{0}", True),
  239. ("/var/lib/ambari-server/resources/views", "755", "{0}", False),
  240. ("/var/lib/ambari-server/resources/views/work", "755", "{0}", True),
  241. ("/etc/ambari-server/conf", "644", "{0}", True),
  242. ("/etc/ambari-server/conf", "755", "{0}", False),
  243. ("/etc/ambari-server/conf/password.dat", "640", "{0}", False),
  244. ("/var/lib/ambari-server/keys/pass.txt", "600", "{0}", False),
  245. ("/etc/ambari-server/conf/ldap-password.dat", "640", "{0}", False),
  246. ("/var/run/ambari-server/stack-recommendations/", "744", "{0}", True),
  247. ("/var/run/ambari-server/stack-recommendations/", "755", "{0}", False),
  248. ("/var/lib/ambari-server/data/tmp/", "644", "{0}", True),
  249. ("/var/lib/ambari-server/data/tmp/", "755", "{0}", False),
  250. ("/var/lib/ambari-server/data/cache/", "600", "{0}", True),
  251. ("/var/lib/ambari-server/data/cache/", "700", "{0}", False),
  252. # Also, /etc/ambari-server/conf/password.dat
  253. # is generated later at store_password_file
  254. ]
  255. self.NR_USERADD_CMD = 'useradd -M --comment "{1}" ' \
  256. '--shell %s -d /var/lib/ambari-server/keys/ {0}' % locate_file('nologin', '/sbin')
  257. self.SERVER_RESOURCES_DIR = "/var/lib/ambari-server/resources"
  258. self.STACK_LOCATION_DEFAULT = "/var/lib/ambari-server/resources/stacks"
  259. self.DEFAULT_VIEWS_DIR = "/var/lib/ambari-server/resources/views"
  260. #keytool commands
  261. self.keytool_bin_subpath = "bin/keytool"
  262. #Standard messages
  263. self.MESSAGE_SERVER_RUNNING_AS_ROOT = "Ambari Server running with administrator privileges."
  264. self.MESSAGE_ERROR_SETUP_NOT_ROOT = "Ambari-server setup should be run with root-level privileges"
  265. self.MESSAGE_ERROR_RESET_NOT_ROOT = "Ambari-server reset should be run with root-level privileges"
  266. self.MESSAGE_ERROR_UPGRADE_NOT_ROOT = "Ambari-server upgrade must be run with root-level privileges"
  267. self.MESSAGE_CHECK_FIREWALL = "Checking firewall status..."
  268. configDefaults = ServerConfigDefaults()
  269. # Security
  270. SECURITY_KEYS_DIR = "security.server.keys_dir"
  271. SECURITY_MASTER_KEY_LOCATION = "security.master.key.location"
  272. SECURITY_KEY_IS_PERSISTED = "security.master.key.ispersisted"
  273. SECURITY_KEY_ENV_VAR_NAME = "AMBARI_SECURITY_MASTER_KEY"
  274. SECURITY_MASTER_KEY_FILENAME = "master"
  275. SECURITY_IS_ENCRYPTION_ENABLED = "security.passwords.encryption.enabled"
  276. SECURITY_KERBEROS_JASS_FILENAME = "krb5JAASLogin.conf"
  277. SECURITY_PROVIDER_GET_CMD = "{0} -cp {1} " + \
  278. "org.apache.ambari.server.security.encryption" + \
  279. ".CredentialProvider GET {2} {3} {4} " + \
  280. "> " + configDefaults.SERVER_OUT_FILE + " 2>&1"
  281. SECURITY_PROVIDER_PUT_CMD = "{0} -cp {1} " + \
  282. "org.apache.ambari.server.security.encryption" + \
  283. ".CredentialProvider PUT {2} {3} {4} " + \
  284. "> " + configDefaults.SERVER_OUT_FILE + " 2>&1"
  285. SECURITY_PROVIDER_KEY_CMD = "{0} -cp {1} " + \
  286. "org.apache.ambari.server.security.encryption" + \
  287. ".MasterKeyServiceImpl {2} {3} {4} " + \
  288. "> " + configDefaults.SERVER_OUT_FILE + " 2>&1"
  289. def get_conf_dir():
  290. try:
  291. conf_dir = os.environ[AMBARI_CONF_VAR]
  292. return conf_dir
  293. except KeyError:
  294. default_conf_dir = configDefaults.DEFAULT_CONF_DIR
  295. print_info_msg(AMBARI_CONF_VAR + " is not set, using default " + default_conf_dir)
  296. return default_conf_dir
  297. def find_properties_file():
  298. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  299. if conf_file is None:
  300. err = 'File %s not found in search path $%s: %s' % (AMBARI_PROPERTIES_FILE,
  301. AMBARI_CONF_VAR, get_conf_dir())
  302. print err
  303. raise FatalException(1, err)
  304. else:
  305. print_info_msg('Loading properties from ' + conf_file)
  306. return conf_file
  307. # Load ambari properties and return dict with values
  308. def get_ambari_properties():
  309. conf_file = find_properties_file()
  310. properties = None
  311. try:
  312. properties = Properties()
  313. properties.load(open(conf_file))
  314. except (Exception), e:
  315. print 'Could not read "%s": %s' % (conf_file, e)
  316. return -1
  317. return properties
  318. def read_ambari_user():
  319. '''
  320. Reads ambari user from properties file
  321. '''
  322. properties = get_ambari_properties()
  323. if properties != -1:
  324. user = properties[NR_USER_PROPERTY]
  325. if user:
  326. return user
  327. return None
  328. def get_value_from_properties(properties, key, default=""):
  329. try:
  330. value = properties.get_property(key)
  331. if not value:
  332. value = default
  333. except:
  334. return default
  335. return value
  336. def get_admin_views_dir(properties):
  337. views_dir = properties.get_property(VIEWS_DIR_PROPERTY)
  338. if views_dir is None or views_dir == "":
  339. views_dirs = glob.glob("/var/lib/ambari-server/resources/views/work/ADMIN_VIEW*")
  340. else:
  341. views_dirs = glob.glob(views_dir + "/work/ADMIN_VIEW*")
  342. return views_dirs
  343. def get_is_secure(properties):
  344. isSecure = properties.get_property(SECURITY_IS_ENCRYPTION_ENABLED)
  345. isSecure = True if isSecure and isSecure.lower() == 'true' else False
  346. return isSecure
  347. def get_is_persisted(properties):
  348. keyLocation = get_master_key_location(properties)
  349. masterKeyFile = search_file(SECURITY_MASTER_KEY_FILENAME, keyLocation)
  350. isPersisted = True if masterKeyFile else False
  351. return (isPersisted, masterKeyFile)
  352. def get_credential_store_location(properties):
  353. store_loc = properties[SECURITY_KEYS_DIR]
  354. if store_loc is None or store_loc == "":
  355. store_loc = "/var/lib/ambari-server/keys/credentials.jceks"
  356. else:
  357. store_loc += os.sep + "credentials.jceks"
  358. return store_loc
  359. def get_master_key_location(properties):
  360. keyLocation = properties[SECURITY_MASTER_KEY_LOCATION]
  361. if keyLocation is None or keyLocation == "":
  362. keyLocation = properties[SECURITY_KEYS_DIR]
  363. return keyLocation
  364. # Copy file to /tmp and save with file.# (largest # is latest file)
  365. def backup_file_in_temp(filePath):
  366. if filePath is not None:
  367. tmpDir = tempfile.gettempdir()
  368. back_up_file_count = len(glob.glob1(tmpDir, AMBARI_PROPERTIES_FILE + "*"))
  369. try:
  370. shutil.copyfile(filePath, tmpDir + os.sep +
  371. AMBARI_PROPERTIES_FILE + "." + str(back_up_file_count + 1))
  372. except (Exception), e:
  373. print_error_msg('Could not backup file in temp "%s": %s' % (
  374. back_up_file_count, str(e)))
  375. return 0
  376. def get_ambari_version(properties):
  377. """
  378. :param properties: Ambari properties
  379. :return: Return a string of the ambari version. When comparing versions, please use "compare_versions" function.
  380. """
  381. version = None
  382. try:
  383. server_version_file_path = properties[SERVER_VERSION_FILE_PATH]
  384. if server_version_file_path and os.path.exists(server_version_file_path):
  385. with open(server_version_file_path, 'r') as file:
  386. version = file.read().strip()
  387. except:
  388. print_error_msg("Error getting ambari version")
  389. return version
  390. def get_db_type(properties):
  391. db_type = None
  392. if properties[JDBC_URL_PROPERTY]:
  393. jdbc_url = properties[JDBC_URL_PROPERTY].lower()
  394. if "postgres" in jdbc_url:
  395. db_type = "postgres"
  396. elif "oracle" in jdbc_url:
  397. db_type = "oracle"
  398. elif "mysql" in jdbc_url:
  399. db_type = "mysql"
  400. elif "sqlserver" in jdbc_url:
  401. db_type = "mssql"
  402. elif "derby" in jdbc_url:
  403. db_type = "derby"
  404. return db_type
  405. def check_database_name_property(upgrade=False):
  406. """
  407. :param upgrade: If Ambari is being upgraded.
  408. :return:
  409. """
  410. properties = get_ambari_properties()
  411. if properties == -1:
  412. print_error_msg("Error getting ambari properties")
  413. return -1
  414. version = get_ambari_version(properties)
  415. if upgrade and (properties[JDBC_DATABASE_PROPERTY] not in ["postgres", "oracle", "mysql", "mssql", "derby"]
  416. or properties.has_key(JDBC_RCA_SCHEMA_PROPERTY)):
  417. # This code exists for historic reasons in which property names changed from Ambari 1.6.1 to 1.7.0
  418. persistence_type = properties[PERSISTENCE_TYPE_PROPERTY]
  419. if persistence_type == "remote":
  420. db_name = properties["server.jdbc.schema"] # this was a property in Ambari 1.6.1, but not after 1.7.0
  421. if db_name:
  422. write_property(JDBC_DATABASE_NAME_PROPERTY, db_name)
  423. # If DB type is missing, attempt to reconstruct it from the JDBC URL
  424. db_type = properties[JDBC_DATABASE_PROPERTY]
  425. if db_type is None or db_type.strip().lower() not in ["postgres", "oracle", "mysql", "mssql", "derby"]:
  426. db_type = get_db_type(properties)
  427. if db_type:
  428. write_property(JDBC_DATABASE_PROPERTY, db_type)
  429. properties = get_ambari_properties()
  430. elif persistence_type == "local":
  431. # Ambari 1.6.1, had "server.jdbc.database" as the DB name, and the
  432. # DB type was assumed to be "postgres" if was embedded ("local")
  433. db_name = properties[JDBC_DATABASE_PROPERTY]
  434. if db_name:
  435. write_property(JDBC_DATABASE_NAME_PROPERTY, db_name)
  436. write_property(JDBC_DATABASE_PROPERTY, "postgres")
  437. properties = get_ambari_properties()
  438. dbname = properties[JDBC_DATABASE_NAME_PROPERTY]
  439. if dbname is None or dbname == "":
  440. err = "DB Name property not set in config file.\n" + SETUP_OR_UPGRADE_MSG
  441. raise FatalException(-1, err)
  442. def update_database_name_property(upgrade=False):
  443. try:
  444. check_database_name_property(upgrade)
  445. except FatalException:
  446. properties = get_ambari_properties()
  447. if properties == -1:
  448. err = "Error getting ambari properties"
  449. raise FatalException(-1, err)
  450. print_warning_msg(JDBC_DATABASE_NAME_PROPERTY + " property isn't set in " +
  451. AMBARI_PROPERTIES_FILE + ". Setting it to default value - " + configDefaults.DEFAULT_DB_NAME)
  452. properties.process_pair(JDBC_DATABASE_NAME_PROPERTY, configDefaults.DEFAULT_DB_NAME)
  453. conf_file = find_properties_file()
  454. try:
  455. properties.store(open(conf_file, "w"))
  456. except Exception, e:
  457. err = 'Could not write ambari config file "%s": %s' % (conf_file, e)
  458. raise FatalException(-1, err)
  459. def encrypt_password(alias, password):
  460. properties = get_ambari_properties()
  461. if properties == -1:
  462. raise FatalException(1, None)
  463. return get_encrypted_password(alias, password, properties)
  464. def get_encrypted_password(alias, password, properties):
  465. isSecure = get_is_secure(properties)
  466. (isPersisted, masterKeyFile) = get_is_persisted(properties)
  467. if isSecure:
  468. masterKey = None
  469. if not masterKeyFile:
  470. # Encryption enabled but no master key file found
  471. masterKey = get_original_master_key(properties)
  472. retCode = save_passwd_for_alias(alias, password, masterKey)
  473. if retCode != 0:
  474. print 'Failed to save secure password!'
  475. return password
  476. else:
  477. return get_alias_string(alias)
  478. return password
  479. def is_alias_string(passwdStr):
  480. regex = re.compile("\$\{alias=[\w\.]+\}")
  481. # Match implies string at beginning of word
  482. r = regex.match(passwdStr)
  483. if r is not None:
  484. return True
  485. else:
  486. return False
  487. def get_alias_string(alias):
  488. return "${alias=" + alias + "}"
  489. def get_alias_from_alias_string(aliasStr):
  490. return aliasStr[8:-1]
  491. def read_passwd_for_alias(alias, masterKey=""):
  492. if alias:
  493. jdk_path = find_jdk()
  494. if jdk_path is None:
  495. print_error_msg("No JDK found, please run the \"setup\" "
  496. "command to install a JDK automatically or install any "
  497. "JDK manually to " + configDefaults.JDK_INSTALL_DIR)
  498. return 1
  499. tempFileName = "ambari.passwd"
  500. passwd = ""
  501. tempDir = tempfile.gettempdir()
  502. #create temporary file for writing
  503. tempFilePath = tempDir + os.sep + tempFileName
  504. file = open(tempFilePath, 'w+')
  505. os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)
  506. file.close()
  507. if masterKey is None or masterKey == "":
  508. masterKey = "None"
  509. command = SECURITY_PROVIDER_GET_CMD.format(get_java_exe_path(),
  510. get_full_ambari_classpath(), alias, tempFilePath, masterKey)
  511. (retcode, stdout, stderr) = run_os_command(command)
  512. print_info_msg("Return code from credential provider get passwd: " +
  513. str(retcode))
  514. if retcode != 0:
  515. print 'ERROR: Unable to read password from store. alias = ' + alias
  516. else:
  517. passwd = open(tempFilePath, 'r').read()
  518. # Remove temporary file
  519. os.remove(tempFilePath)
  520. return passwd
  521. else:
  522. print_error_msg("Alias is unreadable.")
  523. def decrypt_password_for_alias(properties, alias):
  524. isSecure = get_is_secure(properties)
  525. if isSecure:
  526. masterKey = None
  527. (isPersisted, masterKeyFile) = get_is_persisted(properties)
  528. if not masterKeyFile:
  529. # Encryption enabled but no master key file found
  530. masterKey = get_original_master_key(properties)
  531. return read_passwd_for_alias(alias, masterKey)
  532. else:
  533. return alias
  534. def save_passwd_for_alias(alias, passwd, masterKey=""):
  535. if alias and passwd:
  536. jdk_path = find_jdk()
  537. if jdk_path is None:
  538. print_error_msg("No JDK found, please run the \"setup\" "
  539. "command to install a JDK automatically or install any "
  540. "JDK manually to " + configDefaults.JDK_INSTALL_DIR)
  541. return 1
  542. if masterKey is None or masterKey == "":
  543. masterKey = "None"
  544. command = SECURITY_PROVIDER_PUT_CMD.format(get_java_exe_path(),
  545. get_full_ambari_classpath(), alias, passwd, masterKey)
  546. (retcode, stdout, stderr) = run_os_command(command)
  547. print_info_msg("Return code from credential provider save passwd: " +
  548. str(retcode))
  549. return retcode
  550. else:
  551. print_error_msg("Alias or password is unreadable.")
  552. def get_pass_file_path(conf_file, filename):
  553. return os.path.join(os.path.dirname(conf_file), filename)
  554. def store_password_file(password, filename):
  555. conf_file = find_properties_file()
  556. passFilePath = get_pass_file_path(conf_file, filename)
  557. with open(passFilePath, 'w+') as passFile:
  558. passFile.write(password)
  559. print_info_msg("Adjusting filesystem permissions")
  560. ambari_user = read_ambari_user()
  561. set_file_permissions(passFilePath, "660", ambari_user, False)
  562. #Windows paths need double backslashes, otherwise the Ambari server deserializer will think the single \ are escape markers
  563. return passFilePath.replace('\\', '\\\\')
  564. def remove_password_file(filename):
  565. conf_file = find_properties_file()
  566. passFilePath = os.path.join(os.path.dirname(conf_file),
  567. filename)
  568. if os.path.exists(passFilePath):
  569. try:
  570. os.remove(passFilePath)
  571. except Exception, e:
  572. print_warning_msg('Unable to remove password file: ' + str(e))
  573. return 1
  574. pass
  575. return 0
  576. def get_original_master_key(properties):
  577. input = True
  578. while(input):
  579. try:
  580. masterKey = get_validated_string_input('Enter current Master Key: ',
  581. "", ".*", "", True, False)
  582. except KeyboardInterrupt:
  583. print 'Exiting...'
  584. sys.exit(1)
  585. # Find an alias that exists
  586. alias = None
  587. property = properties.get_property(JDBC_PASSWORD_PROPERTY)
  588. if property and is_alias_string(property):
  589. alias = JDBC_RCA_PASSWORD_ALIAS
  590. if not alias:
  591. property = properties.get_property(LDAP_MGR_PASSWORD_PROPERTY)
  592. if property and is_alias_string(property):
  593. alias = LDAP_MGR_PASSWORD_ALIAS
  594. if not alias:
  595. property = properties.get_property(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
  596. if property and is_alias_string(property):
  597. alias = SSL_TRUSTSTORE_PASSWORD_ALIAS
  598. # Decrypt alias with master to validate it, if no master return
  599. if alias and masterKey:
  600. password = read_passwd_for_alias(alias, masterKey)
  601. if not password:
  602. print "ERROR: Master key does not match."
  603. continue
  604. input = False
  605. return masterKey
  606. # Load database connection properties from conf file
  607. def parse_properties_file(args):
  608. properties = get_ambari_properties()
  609. if properties == -1:
  610. print_error_msg("Error getting ambari properties")
  611. return -1
  612. args.server_version_file_path = properties[SERVER_VERSION_FILE_PATH]
  613. args.persistence_type = properties[PERSISTENCE_TYPE_PROPERTY]
  614. args.jdbc_url = properties[JDBC_URL_PROPERTY]
  615. args.dbms = properties[JDBC_DATABASE_PROPERTY]
  616. if not args.persistence_type:
  617. args.persistence_type = "local"
  618. if args.persistence_type == 'remote':
  619. args.database_host = properties[JDBC_HOSTNAME_PROPERTY]
  620. args.database_port = properties[JDBC_PORT_PROPERTY]
  621. args.database_name = properties[JDBC_DATABASE_NAME_PROPERTY]
  622. args.database_username = properties[JDBC_USER_NAME_PROPERTY]
  623. args.postgres_schema = properties[JDBC_POSTGRES_SCHEMA_PROPERTY] \
  624. if JDBC_POSTGRES_SCHEMA_PROPERTY in properties.propertyNames() else None
  625. args.database_password_file = properties[JDBC_PASSWORD_PROPERTY]
  626. if args.database_password_file:
  627. if not is_alias_string(args.database_password_file):
  628. args.database_password = open(properties[JDBC_PASSWORD_PROPERTY]).read()
  629. else:
  630. args.database_password = args.database_password_file
  631. return 0
  632. def update_ambari_properties():
  633. prev_conf_file = search_file(configDefaults.AMBARI_PROPERTIES_BACKUP_FILE, get_conf_dir())
  634. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  635. # Previous config file does not exist
  636. if (not prev_conf_file) or (prev_conf_file is None):
  637. print_warning_msg("Can not find %s file from previous version, skipping import of settings" % configDefaults.AMBARI_PROPERTIES_BACKUP_FILE)
  638. return 0
  639. # ambari.properties file does not exists
  640. if conf_file is None:
  641. print_error_msg("Can't find %s file" % AMBARI_PROPERTIES_FILE)
  642. return -1
  643. try:
  644. old_properties = Properties()
  645. old_properties.load(open(prev_conf_file))
  646. except Exception, e:
  647. print 'Could not read "%s": %s' % (prev_conf_file, e)
  648. return -1
  649. try:
  650. new_properties = Properties()
  651. new_properties.load(open(conf_file))
  652. for prop_key, prop_value in old_properties.getPropertyDict().items():
  653. if "agent.fqdn.service.url" == prop_key:
  654. # BUG-7179 what is agent.fqdn property in ambari.props?
  655. new_properties.process_pair(GET_FQDN_SERVICE_URL, prop_value)
  656. elif "server.os_type" == prop_key:
  657. new_properties.process_pair(OS_TYPE_PROPERTY, OS_FAMILY + OS_VERSION)
  658. else:
  659. new_properties.process_pair(prop_key, prop_value)
  660. # Adding custom user name property if it is absent
  661. # In previous versions without custom user support server was started as
  662. # "root" anyway so it's a reasonable default
  663. if NR_USER_PROPERTY not in new_properties.keys():
  664. new_properties.process_pair(NR_USER_PROPERTY, "root")
  665. if OS_FAMILY_PROPERTY not in new_properties.keys():
  666. new_properties.process_pair(OS_FAMILY_PROPERTY, OS_FAMILY + OS_VERSION)
  667. new_properties.store(open(conf_file, 'w'))
  668. except Exception, e:
  669. print 'Could not write "%s": %s' % (conf_file, e)
  670. return -1
  671. timestamp = datetime.datetime.now()
  672. fmt = '%Y%m%d%H%M%S'
  673. os.rename(prev_conf_file, prev_conf_file + '.' + timestamp.strftime(fmt))
  674. return 0
  675. # update properties in a section-less properties file
  676. # Cannot use ConfigParser due to bugs in version 2.6
  677. def update_properties(propertyMap):
  678. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  679. backup_file_in_temp(conf_file)
  680. if propertyMap is not None and conf_file is not None:
  681. properties = Properties()
  682. try:
  683. with open(conf_file, 'r') as file:
  684. properties.load(file)
  685. except (Exception), e:
  686. print_error_msg('Could not read "%s": %s' % (conf_file, e))
  687. return -1
  688. for key in propertyMap.keys():
  689. properties.removeOldProp(key)
  690. properties.process_pair(key, str(propertyMap[key]))
  691. for key in properties.keys():
  692. if not propertyMap.has_key(key):
  693. properties.removeOldProp(key)
  694. with open(conf_file, 'w') as file:
  695. properties.store_ordered(file)
  696. return 0
  697. def update_properties_2(properties, propertyMap):
  698. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  699. backup_file_in_temp(conf_file)
  700. if conf_file is not None:
  701. if propertyMap is not None:
  702. for key in propertyMap.keys():
  703. properties.removeOldProp(key)
  704. properties.process_pair(key, str(propertyMap[key]))
  705. pass
  706. with open(conf_file, 'w') as file:
  707. properties.store_ordered(file)
  708. pass
  709. pass
  710. def write_property(key, value):
  711. conf_file = find_properties_file()
  712. properties = Properties()
  713. try:
  714. properties.load(open(conf_file))
  715. except Exception, e:
  716. print_error_msg('Could not read ambari config file "%s": %s' % (conf_file, e))
  717. return -1
  718. properties.process_pair(key, value)
  719. try:
  720. properties.store(open(conf_file, "w"))
  721. except Exception, e:
  722. print_error_msg('Could not write ambari config file "%s": %s' % (conf_file, e))
  723. return -1
  724. return 0
  725. #
  726. # Checks if options determine local DB configuration
  727. #
  728. def is_local_database(args):
  729. try:
  730. return args.persistence_type == 'local'
  731. except AttributeError:
  732. return False
  733. def update_debug_mode():
  734. debug_mode = get_debug_mode()
  735. # The command-line settings supersede the ones in ambari.properties
  736. if not debug_mode & 1:
  737. properties = get_ambari_properties()
  738. if properties == -1:
  739. print_error_msg("Error getting ambari properties")
  740. return -1
  741. if get_value_from_properties(properties, DEBUG_MODE_KEY, False):
  742. debug_mode = debug_mode | 1
  743. if get_value_from_properties(properties, SUSPEND_START_MODE_KEY, False):
  744. debug_mode = debug_mode | 2
  745. set_debug_mode(debug_mode)
  746. #
  747. ### JDK ###
  748. #
  749. #
  750. # Describes the JDK configuration data, necessary for download and installation
  751. #
  752. class JDKRelease:
  753. name = ""
  754. desc = ""
  755. url = ""
  756. dest_file = ""
  757. jcpol_url = "http://public-repo-1.hortonworks.com/ARTIFACTS/UnlimitedJCEPolicyJDK7.zip"
  758. dest_jcpol_file = ""
  759. inst_dir = ""
  760. def __init__(self, i_name, i_desc, i_url, i_dest_file, i_jcpol_url, i_dest_jcpol_file, i_inst_dir, i_reg_exp):
  761. if i_name is None or i_name is "":
  762. raise FatalException(-1, "Invalid JDK name: " + (i_desc or ""))
  763. self.name = i_name
  764. if i_desc is None or i_desc is "":
  765. self.desc = self.name
  766. else:
  767. self.desc = i_desc
  768. if i_url is None or i_url is "":
  769. raise FatalException(-1, "Invalid URL for JDK " + i_name)
  770. self.url = i_url
  771. if i_dest_file is None or i_dest_file is "":
  772. self.dest_file = i_name + ".exe"
  773. else:
  774. self.dest_file = i_dest_file
  775. if not (i_jcpol_url is None or i_jcpol_url is ""):
  776. self.jcpol_url = i_jcpol_url
  777. if i_dest_jcpol_file is None or i_dest_jcpol_file is "":
  778. self.dest_jcpol_file = "jcpol-" + i_name + ".zip"
  779. else:
  780. self.dest_jcpol_file = i_dest_jcpol_file
  781. if i_inst_dir is None or i_inst_dir is "":
  782. self.inst_dir = os.path.join(configDefaults.JDK_INSTALL_DIR, i_desc)
  783. else:
  784. self.inst_dir = i_inst_dir
  785. if i_reg_exp is None or i_reg_exp is "":
  786. raise FatalException(-1, "Invalid output parsing regular expression for JDK " + i_name)
  787. self.reg_exp = i_reg_exp
  788. @classmethod
  789. def from_properties(cls, properties, section_name):
  790. (desc, url, dest_file, jcpol_url, jcpol_file, inst_dir, reg_exp) = JDKRelease.__load_properties(properties, section_name)
  791. cls = JDKRelease(section_name, desc, url, dest_file, jcpol_url, jcpol_file, inst_dir, reg_exp)
  792. return cls
  793. @staticmethod
  794. def __load_properties(properties, section_name):
  795. if section_name is None or section_name is "":
  796. raise FatalException(-1, "Invalid properties section: " + ("(empty)" if section_name is None else ""))
  797. if(properties.has_key(section_name + ".desc")): #Not critical
  798. desc = properties[section_name + ".desc"]
  799. else:
  800. desc = section_name
  801. if not properties.has_key(section_name + ".url"):
  802. raise FatalException(-1, "Invalid JDK URL in the properties section: " + section_name)
  803. url = properties[section_name + ".url"] #Required
  804. if not properties.has_key(section_name + ".re"):
  805. raise FatalException(-1, "Invalid JDK output parsing regular expression in the properties section: " + section_name)
  806. reg_exp = properties[section_name + ".re"] #Required
  807. if(properties.has_key(section_name + ".dest-file")): #Not critical
  808. dest_file = properties[section_name + ".dest-file"]
  809. else:
  810. dest_file = section_name + ".exe"
  811. if(properties.has_key(section_name + ".jcpol-url")): #Not critical
  812. jcpol_url = properties[section_name + ".jcpol-url"]
  813. else:
  814. jcpol_url = None
  815. if(properties.has_key(section_name + ".jcpol-file")): #Not critical
  816. jcpol_file = properties[section_name + ".jcpol-file"]
  817. else:
  818. jcpol_file = None
  819. if(properties.has_key(section_name + ".home")): #Not critical
  820. inst_dir = properties[section_name + ".home"]
  821. else:
  822. inst_dir = "C:\\" + section_name
  823. return (desc, url, dest_file, jcpol_url, jcpol_file, inst_dir, reg_exp)
  824. pass
  825. def get_ambari_jars():
  826. try:
  827. conf_dir = os.environ[AMBARI_SERVER_LIB]
  828. return conf_dir
  829. except KeyError:
  830. default_jar_location = configDefaults.DEFAULT_LIBS_DIR
  831. print_info_msg(AMBARI_SERVER_LIB + " is not set, using default "
  832. + default_jar_location)
  833. return default_jar_location
  834. def get_share_jars():
  835. share_jars = ""
  836. file_list = []
  837. file_list.extend(glob.glob(configDefaults.JAVA_SHARE_PATH + os.sep + "*mysql*"))
  838. file_list.extend(glob.glob(configDefaults.JAVA_SHARE_PATH + os.sep + "*sqljdbc*"))
  839. file_list.extend(glob.glob(configDefaults.JAVA_SHARE_PATH + os.sep + "*ojdbc*"))
  840. if len(file_list) > 0:
  841. share_jars = string.join(file_list, os.pathsep)
  842. return share_jars
  843. def get_jdbc_cp():
  844. jdbc_jar_path = ""
  845. properties = get_ambari_properties()
  846. if properties != -1:
  847. jdbc_jar_path = properties[JDBC_DRIVER_PATH_PROPERTY]
  848. return jdbc_jar_path
  849. def get_ambari_classpath():
  850. ambari_cp = os.path.abspath(get_ambari_jars() + os.sep + "*")
  851. jdbc_cp = get_jdbc_cp()
  852. if len(jdbc_cp) > 0:
  853. ambari_cp = ambari_cp + os.pathsep + jdbc_cp
  854. share_cp = get_share_jars()
  855. if len(share_cp) > 0:
  856. ambari_cp = ambari_cp + os.pathsep + share_cp
  857. return ambari_cp
  858. def get_full_ambari_classpath(conf_dir = None):
  859. if conf_dir is None:
  860. conf_dir = get_conf_dir()
  861. cp = conf_dir + os.pathsep + get_ambari_classpath()
  862. if cp.find(' ') != -1:
  863. cp = '"' + cp + '"'
  864. return cp
  865. def get_JAVA_HOME():
  866. properties = get_ambari_properties()
  867. if properties == -1:
  868. print_error_msg("Error getting ambari properties")
  869. return None
  870. java_home = properties[JAVA_HOME_PROPERTY]
  871. if (not 0 == len(java_home)) and (os.path.exists(java_home)):
  872. return java_home
  873. return None
  874. #
  875. # Checks jdk path for correctness
  876. #
  877. def validate_jdk(jdk_path):
  878. if jdk_path:
  879. if os.path.exists(jdk_path):
  880. java_exe_path = os.path.join(jdk_path, configDefaults.JAVA_EXE_SUBPATH)
  881. if os.path.exists(java_exe_path) and os.path.isfile(java_exe_path):
  882. return True
  883. return False
  884. #
  885. # Finds the available JDKs.
  886. #
  887. def find_jdk():
  888. jdkPath = get_JAVA_HOME()
  889. if jdkPath:
  890. if validate_jdk(jdkPath):
  891. return jdkPath
  892. print "Looking for available JDKs at " + configDefaults.JDK_INSTALL_DIR
  893. jdks = glob.glob(os.path.join(configDefaults.JDK_INSTALL_DIR, configDefaults.JDK_SEARCH_PATTERN))
  894. #[fbarca] Use the newest JDK
  895. jdks.sort(None, None, True)
  896. print "Found: " + str(jdks)
  897. if len(jdks) == 0:
  898. return
  899. for jdkPath in jdks:
  900. print "Trying to use JDK {0}".format(jdkPath)
  901. if validate_jdk(jdkPath):
  902. print "Selected JDK {0}".format(jdkPath)
  903. return jdkPath
  904. else:
  905. print "JDK {0} is invalid".format(jdkPath)
  906. return
  907. def get_java_exe_path():
  908. jdkPath = find_jdk()
  909. if jdkPath:
  910. java_exe = os.path.join(jdkPath, configDefaults.JAVA_EXE_SUBPATH)
  911. return java_exe
  912. return
  913. #
  914. # Server resource files location
  915. #
  916. def get_resources_location(properties):
  917. err = 'Invalid directory'
  918. try:
  919. resources_dir = properties[RESOURCES_DIR_PROPERTY]
  920. if not resources_dir:
  921. resources_dir = configDefaults.SERVER_RESOURCES_DIR
  922. except (KeyError), e:
  923. err = 'Property ' + str(e) + ' is not defined at ' + properties.fileName
  924. resources_dir = configDefaults.SERVER_RESOURCES_DIR
  925. if not os.path.exists(os.path.abspath(resources_dir)):
  926. msg = 'Resources dir ' + resources_dir + ' is incorrectly configured: ' + err
  927. raise FatalException(1, msg)
  928. return resources_dir
  929. #
  930. # Stack upgrade
  931. #
  932. def get_stack_location(properties):
  933. stack_location = properties[STACK_LOCATION_KEY]
  934. if stack_location is None:
  935. stack_location = configDefaults.STACK_LOCATION_DEFAULT
  936. return stack_location