serverConfiguration.py 39 KB

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