ambari-server.py 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917
  1. #!/usr/bin/env python2.6
  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. from pprint import pprint
  19. import shlex
  20. import sys
  21. import os
  22. import signal
  23. import subprocess
  24. import re
  25. import string
  26. import glob
  27. import platform
  28. import shutil
  29. import stat
  30. import fileinput
  31. import urllib2
  32. import time
  33. import getpass
  34. import socket
  35. import datetime
  36. import socket
  37. import tempfile
  38. # debug settings
  39. VERBOSE = False
  40. SILENT = False
  41. SERVER_START_DEBUG = False
  42. # action commands
  43. SETUP_ACTION = "setup"
  44. START_ACTION = "start"
  45. STOP_ACTION = "stop"
  46. RESET_ACTION = "reset"
  47. UPGRADE_ACTION = "upgrade"
  48. UPGRADE_STACK_ACTION = "upgradestack"
  49. UPDATE_METAINFO_ACTION = "update-metainfo"
  50. STATUS_ACTION = "status"
  51. SETUP_HTTPS_ACTION = "setup-https"
  52. LDAP_SETUP_ACTION = "setupldap"
  53. RESET_MASTER_KEY_ACTION = "resetmasterkey"
  54. # selinux commands
  55. GET_SE_LINUX_ST_CMD = "/usr/sbin/sestatus"
  56. SE_SETENFORCE_CMD = "setenforce 0"
  57. SE_STATUS_DISABLED = "disabled"
  58. SE_STATUS_ENABLED = "enabled"
  59. SE_MODE_ENFORCING = "enforcing"
  60. SE_MODE_PERMISSIVE = "permissive"
  61. # iptables commands
  62. IP_TBLS_ST_CMD = "/sbin/service iptables status"
  63. IP_TBLS_STOP_CMD = "/sbin/service iptables stop"
  64. IP_TBLS_ENABLED = "Firewall is running"
  65. IP_TBLS_DISABLED = "Firewall is stopped.\n"
  66. IP_TBLS_SRVC_NT_FND = "iptables: unrecognized service"
  67. # server commands
  68. ambari_provider_module_option = ""
  69. ambari_provider_module = os.environ.get('AMBARI_PROVIDER_MODULE')
  70. # Non-root user setup commands
  71. NR_USER_PROPERTY = "ambari.user"
  72. NR_USER_COMMENT = "Ambari user"
  73. NR_GET_OWNER_CMD = 'stat -c "%U" {0}'
  74. NR_USERADD_CMD = 'useradd -M -g {0} --comment "{1}" ' \
  75. '--shell /sbin/nologin -d /var/lib/ambari-server/keys/ {0}'
  76. NR_SET_USER_COMMENT_CMD = 'usermod -c "{0}" {1}'
  77. NR_GROUPADD_CMD = 'groupadd {0}'
  78. NR_ADD_USER_TO_GROUP = 'usermod -G {0} {0}'
  79. NR_CHMOD_CMD = 'chmod {0} {1}'
  80. NR_CHOWN_CMD = 'chown {0}:{1} {2}'
  81. # openssl command
  82. EXPRT_KSTR_CMD = "openssl pkcs12 -export -in {0} -inkey {1} -certfile {0} -out {3} -password pass:{2} -passin pass:{2}"
  83. # constants
  84. STACK_NAME_VER_SEP = "-"
  85. JAVA_SHARE_PATH="/usr/share/java"
  86. # terminal styles
  87. BOLD_ON='\033[1m'
  88. BOLD_OFF='\033[0m'
  89. #Common messages
  90. PRESS_ENTER_MSG="Press <enter> to continue."
  91. if ambari_provider_module is not None:
  92. ambari_provider_module_option = "-Dprovider.module.class=" +\
  93. ambari_provider_module + " "
  94. SERVER_START_CMD="{0}" + os.sep + "bin" + os.sep +\
  95. "java -server -XX:NewRatio=3 "\
  96. "-XX:+UseConcMarkSweepGC " +\
  97. "-XX:-UseGCOverheadLimit -XX:CMSInitiatingOccupancyFraction=60 " +\
  98. ambari_provider_module_option +\
  99. os.getenv('AMBARI_JVM_ARGS','-Xms512m -Xmx2048m') +\
  100. " -cp {1}"+ os.pathsep + "{2}" +\
  101. " org.apache.ambari.server.controller.AmbariServer "\
  102. ">/var/log/ambari-server/ambari-server.out 2>&1 &" \
  103. " echo $! > {3}" # Writing pidfile
  104. SERVER_START_CMD_DEBUG="{0}" + os.sep + "bin" + os.sep +\
  105. "java -server -XX:NewRatio=2 -XX:+UseConcMarkSweepGC " +\
  106. ambari_provider_module_option +\
  107. os.getenv('AMBARI_JVM_ARGS','-Xms512m -Xmx2048m') +\
  108. " -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,"\
  109. "server=y,suspend=n -cp {1}"+ os.pathsep + "{2}" +\
  110. " org.apache.ambari.server.controller.AmbariServer &" \
  111. " echo $! > {3}" # Writing pidfile
  112. SECURITY_PROVIDER_GET_CMD="{0}" + os.sep + "bin" + os.sep + "java -cp {1}" +\
  113. os.pathsep + "{2} " +\
  114. "org.apache.ambari.server.security.encryption" +\
  115. ".CredentialProvider GET {3} {4} {5} " +\
  116. "> /var/log/ambari-server/ambari-server.out 2>&1"
  117. SECURITY_PROVIDER_PUT_CMD="{0}" + os.sep + "bin" + os.sep + "java -cp {1}" +\
  118. os.pathsep + "{2} " +\
  119. "org.apache.ambari.server.security.encryption" +\
  120. ".CredentialProvider PUT {3} {4} {5} " +\
  121. "> /var/log/ambari-server/ambari-server.out 2>&1"
  122. SECURITY_PROVIDER_KEY_CMD="{0}" + os.sep + "bin" + os.sep + "java -cp {1}" +\
  123. os.pathsep + "{2} " +\
  124. "org.apache.ambari.server.security.encryption" +\
  125. ".MasterKeyServiceImpl {3} {4} {5} " +\
  126. "> /var/log/ambari-server/ambari-server.out 2>&1"
  127. SECURITY_KEYS_DIR = "security.server.keys_dir"
  128. SECURITY_MASTER_KEY_LOCATION = "security.master.key.location"
  129. SECURITY_KEY_IS_PERSISTED = "security.master.key.ispersisted"
  130. SECURITY_KEY_ENV_VAR_NAME = "ambari.security.master.key"
  131. SECURITY_MASTER_KEY_FILENAME = "master"
  132. SSL_KEY_DIR = 'security.server.keys_dir'
  133. SSL_API_PORT = 'client.api.ssl.port'
  134. SSL_API = 'api.ssl'
  135. SSL_SERVER_CERT_NAME = 'security.server.cert_name'
  136. SSL_SERVER_KEY_NAME = 'security.server.key_name'
  137. SSL_CERT_FILE_NAME = "ca.crt"
  138. SSL_KEY_FILE_NAME = "ca.key"
  139. SSL_KEYSTORE_FILE_NAME = "keystore.p12"
  140. SSL_KEY_PASSWORD_FILE_NAME = "pass.txt"
  141. DEFAULT_SSL_API_PORT = 8443
  142. JDBC_RCA_PASSWORD_ALIAS = "ambari.db.password"
  143. LDAP_MGR_PASSWORD_ALIAS = "ambari.ldap.manager.password"
  144. LDAP_MGR_PASSWORD_PROPERTY = "authentication.ldap.managerPassword"
  145. AMBARI_CONF_VAR="AMBARI_CONF_DIR"
  146. AMBARI_SERVER_LIB="AMBARI_SERVER_LIB"
  147. JAVA_HOME="JAVA_HOME"
  148. PID_DIR="/var/run/ambari-server"
  149. PID_NAME="ambari-server.pid"
  150. AMBARI_PROPERTIES_FILE="ambari.properties"
  151. AMBARI_PROPERTIES_RPMSAVE_FILE="ambari.properties.rpmsave"
  152. RESOURCES_DIR_PROPERTY="resources.dir"
  153. SETUP_DB_CMD = ['su', '-', 'postgres',
  154. '--command=psql -f {0} -v username=\'"{1}"\' -v password="\'{2}\'"']
  155. UPGRADE_STACK_CMD = ['su', 'postgres',
  156. '--command=psql -f {0} -v stack_name="\'{1}\'" -v stack_version="\'{2}\'"']
  157. UPDATE_METAINFO_CMD = 'curl -X PUT "http://{0}:{1}/api/v1/stacks2" -u "{2}":"{3}"'
  158. PG_ST_CMD = "/sbin/service postgresql status"
  159. PG_INITDB_CMD = "/sbin/service postgresql initdb"
  160. PG_START_CMD = "/sbin/service postgresql start"
  161. PG_RESTART_CMD = "/sbin/service postgresql restart"
  162. PG_STATUS_RUNNING = "running"
  163. PG_HBA_DIR = "/var/lib/pgsql/data/"
  164. PG_HBA_CONF_FILE = PG_HBA_DIR + "pg_hba.conf"
  165. PG_HBA_CONF_FILE_BACKUP = PG_HBA_DIR + "pg_hba_bak.conf.old"
  166. POSTGRESQL_CONF_FILE = PG_HBA_DIR + "postgresql.conf"
  167. PG_HBA_RELOAD_CMD = "su postgres --command='pg_ctl -D {0} reload'"
  168. PG_DEFAULT_PASSWORD = "bigdata"
  169. JDBC_DATABASE_PROPERTY = "server.jdbc.database"
  170. JDBC_HOSTNAME_PROPERTY = "server.jdbc.hostname"
  171. JDBC_PORT_PROPERTY = "server.jdbc.port"
  172. JDBC_SCHEMA_PROPERTY = "server.jdbc.schema"
  173. JDBC_USER_NAME_PROPERTY = "server.jdbc.user.name"
  174. JDBC_PASSWORD_PROPERTY = "server.jdbc.user.passwd"
  175. JDBC_PASSWORD_FILENAME = "password.dat"
  176. JDBC_RCA_PASSWORD_FILENAME = "rca_password.dat"
  177. CLIENT_API_PORT_PROPERTY = "client.api.port"
  178. CLIENT_API_PORT = "8080"
  179. PERSISTENCE_TYPE_PROPERTY = "server.persistence.type"
  180. JDBC_DRIVER_PROPERTY = "server.jdbc.driver"
  181. JDBC_URL_PROPERTY = "server.jdbc.url"
  182. JDBC_RCA_DATABASE_PROPERTY = "server.jdbc.database"
  183. JDBC_RCA_HOSTNAME_PROPERTY = "server.jdbc.hostname"
  184. JDBC_RCA_PORT_PROPERTY = "server.jdbc.port"
  185. JDBC_RCA_SCHEMA_PROPERTY = "server.jdbc.schema"
  186. JDBC_RCA_DRIVER_PROPERTY = "server.jdbc.rca.driver"
  187. JDBC_RCA_URL_PROPERTY = "server.jdbc.rca.url"
  188. JDBC_RCA_USER_NAME_PROPERTY = "server.jdbc.rca.user.name"
  189. JDBC_RCA_PASSWORD_FILE_PROPERTY = "server.jdbc.rca.user.passwd"
  190. CHECK_COMMAND_EXIST_CMD = "type {0}"
  191. DATABASE_INDEX = 0
  192. PROMPT_DATABASE_OPTIONS = False
  193. USERNAME_PATTERN = "^[a-zA-Z_][a-zA-Z0-9_\-]*$"
  194. PASSWORD_PATTERN = "^[a-zA-Z0-9_-]*$"
  195. DATABASE_NAMES =["postgres", "oracle"]
  196. DATABASE_STORAGE_NAMES =["Database","Service","Schema"]
  197. DATABASE_PORTS =["5432", "1521", "3306"]
  198. DATABASE_DRIVER_NAMES = ["org.postgresql.Driver", "oracle.jdbc.driver.OracleDriver", "com.mysql.jdbc.Driver"]
  199. DATABASE_CONNECTION_STRINGS = ["jdbc:postgresql://{0}:{1}/{2}", "jdbc:oracle:thin:@{0}:{1}/{2}", "jdbc:mysql://{0}:{1}/{2}"]
  200. DATABASE_CLI_TOOLS = [["psql"], ["sqlplus", "sqlplus64"], ["mysql"]]
  201. DATABASE_CLI_TOOLS_DESC = ["psql", "sqlplus", "mysql"]
  202. DATABASE_CLI_TOOLS_USAGE = ['su -postgres --command=psql -f {0} -v username=\'"{1}"\' -v password="\'{2}\'"',
  203. 'sqlplus {1}/{2} < {0} ',
  204. 'mysql --user={1} --password={2} {3}<{0}']
  205. DATABASE_INIT_SCRIPTS = ['/var/lib/ambari-server/resources/Ambari-DDL-Postgres-REMOTE-CREATE.sql',
  206. '/var/lib/ambari-server/resources/Ambari-DDL-Oracle-CREATE.sql',
  207. '/var/lib/ambari-server/resources/Ambari-DDL-MySQL-CREATE.sql']
  208. DATABASE_DROP_SCRIPTS = ['/var/lib/ambari-server/resources/Ambari-DDL-Postgres-REMOTE-DROP.sql',
  209. '/var/lib/ambari-server/resources/Ambari-DDL-Oracle-DROP.sql',
  210. '/var/lib/ambari-server/resources/Ambari-DDL-MySQL-DROP.sql']
  211. DATABASE_URL_REGEX = ["jdbc:postgresql://([a-zA-Z0-9._]+):(\d+)/(.+)",
  212. "jdbc:oracle:thin:@([a-zA-Z0-9._]+):(\d+)/(.+)",
  213. "jdbc:mysql://([a-zA-Z0-9._]+):(\d*)/(.+)"]
  214. REGEX_IP_ADDRESS = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
  215. REGEX_HOSTNAME = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"
  216. POSTGRES_EXEC_ARGS = "-h {0} -p {1} -d {2} -U {3} -f {4} -v username='\"{3}\"'"
  217. ORACLE_EXEC_ARGS = "-S '{0}/{1}@(description=(address=(protocol=TCP)(host={2})(port={3}))(connect_data=(sid={4})))' @{5} {0}"
  218. MYSQL_EXEC_ARGS = "--host={0} --port={1} --user={2} --password={3} {4} " \
  219. "-e\"set @schema=\'{4}\'; set @username=\'{2}\'; source {5};\""
  220. JDBC_PATTERNS = {"oracle":"*ojdbc*.jar", "mysql":"*mysql*.jar"}
  221. DATABASE_FULL_NAMES = {"oracle":"Oracle", "mysql":"MySQL", "postgres":"PostgreSQL"}
  222. # jdk commands
  223. JDK_LOCAL_FILENAME = "jdk-6u31-linux-x64.bin"
  224. JDK_MIN_FILESIZE = 5000
  225. JDK_INSTALL_DIR = "/usr/jdk64"
  226. CREATE_JDK_DIR_CMD = "/bin/mkdir -p " + JDK_INSTALL_DIR
  227. MAKE_FILE_EXECUTABLE_CMD = "chmod a+x {0}"
  228. JAVA_HOME_PROPERTY = "java.home"
  229. JDK_URL_PROPERTY='jdk.url'
  230. JCE_URL_PROPERTY='jce_policy.url'
  231. OS_TYPE_PROPERTY = "server.os_type"
  232. JDK_DOWNLOAD_CMD = "curl --create-dirs -o {0} {1}"
  233. JDK_DOWNLOAD_SIZE_CMD = "curl -I {0}"
  234. #JCE Policy files
  235. JCE_POLICY_FILENAME = "jce_policy-6.zip"
  236. JCE_DOWNLOAD_CMD = "curl -o {0} {1}"
  237. JCE_MIN_FILESIZE = 5000
  238. #Apache License Header
  239. ASF_LICENSE_HEADER = '''
  240. # Copyright 2011 The Apache Software Foundation
  241. #
  242. # Licensed to the Apache Software Foundation (ASF) under one
  243. # or more contributor license agreements. See the NOTICE file
  244. # distributed with this work for additional information
  245. # regarding copyright ownership. The ASF licenses this file
  246. # to you under the Apache License, Version 2.0 (the
  247. # "License"); you may not use this file except in compliance
  248. # with the License. You may obtain a copy of the License at
  249. #
  250. # http://www.apache.org/licenses/LICENSE-2.0
  251. #
  252. # Unless required by applicable law or agreed to in writing, software
  253. # distributed under the License is distributed on an "AS IS" BASIS,
  254. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  255. # See the License for the specific language governing permissions and
  256. # limitations under the License.
  257. '''
  258. def get_conf_dir():
  259. try:
  260. conf_dir = os.environ[AMBARI_CONF_VAR]
  261. return conf_dir
  262. except KeyError:
  263. default_conf_dir = "/etc/ambari-server/conf"
  264. print AMBARI_CONF_VAR + " is not set, using default " + default_conf_dir
  265. return default_conf_dir
  266. def find_properties_file():
  267. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  268. if conf_file is None:
  269. err = 'File %s not found in search path $%s: %s' % (AMBARI_PROPERTIES_FILE,
  270. AMBARI_CONF_VAR, get_conf_dir())
  271. print err
  272. raise FatalException(1, err)
  273. else:
  274. print_info_msg ('Loading properties from ' + conf_file)
  275. return conf_file
  276. def update_ambari_properties():
  277. prev_conf_file = search_file(AMBARI_PROPERTIES_RPMSAVE_FILE, get_conf_dir())
  278. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  279. if not prev_conf_file: # Previous config file does not exist
  280. print_warning_msg("Can not find ambari.properties.rpmsave file from previous version, skipping import of settings")
  281. return 0
  282. try:
  283. old_properties = Properties()
  284. old_properties.load(open(prev_conf_file))
  285. except Exception, e:
  286. print 'Could not read "%s": %s' % (prev_conf_file, e)
  287. return -1
  288. try:
  289. new_properties = Properties()
  290. new_properties.load(open(conf_file))
  291. for prop_key, prop_value in old_properties.getPropertyDict().items():
  292. new_properties.process_pair(prop_key,prop_value)
  293. new_properties.store(open(conf_file,'w'))
  294. except Exception, e:
  295. print 'Could not write "%s": %s' % (conf_file, e)
  296. return -1
  297. timestamp = datetime.datetime.now()
  298. format = '%Y%m%d%H%M%S'
  299. os.rename(AMBARI_PROPERTIES_RPMSAVE_FILE, AMBARI_PROPERTIES_RPMSAVE_FILE +
  300. '.' + timestamp.strftime(format))
  301. return 0
  302. # ownership/permissions mapping
  303. # path - permissions - user - group
  304. # {0} in user/group will be replaced by customized ambari-server username
  305. NR_CONF_DIR = get_conf_dir()
  306. NR_ADJUST_OWNERSHIP_LIST =[
  307. ( "/etc/ambari-server/conf", "755", "{0}", "{0}" ),
  308. ( "/etc/ambari-server/conf/ambari.properties", "644", "{0}", "{0}" ),
  309. ( "/etc/ambari-server/conf/log4j.properties", "644", "root", "root" ),
  310. ( "/var/lib/ambari-server/keys", "700", "{0}", "{0}" ),
  311. ( "/var/lib/ambari-server/keys/db", "700", "{0}", "{0}" ),
  312. ( "/var/lib/ambari-server/keys/db/index.txt", "700", "{0}", "{0}" ),
  313. ( "/var/lib/ambari-server/keys/db/serial", "700", "{0}", "{0}" ),
  314. ( "/var/lib/ambari-server/keys/db/newcerts", "700", "{0}", "{0}" ),
  315. ( "/var/run/ambari-server", "755", "{0}", "{0}" ),
  316. ( "/var/run/ambari-server/bootstrap", "755", "{0}", "{0}" ),
  317. ( "/var/log/ambari-server", "755", "{0}", "{0}" ),
  318. ( "/var/lib/ambari-server/ambari-env.sh", "770", "{0}", "root" ),
  319. # Also, /etc/ambari-server/conf/password.dat
  320. # is generated later at store_password_file
  321. ]
  322. ### System interaction ###
  323. class FatalException(Exception):
  324. def __init__(self, code, reason):
  325. self.code = code
  326. self.reason = reason
  327. def __str__(self):
  328. return repr("Fatal exception: %s, exit code %s" % (self.reason, self.code))
  329. def _get_message(self):
  330. return str(self)
  331. def is_root():
  332. '''
  333. Checks effective UUID
  334. Returns True if a program is running under root-level privileges.
  335. '''
  336. return os.geteuid() == 0
  337. def get_exec_path(cmd):
  338. cmd = 'which {0}'.format(cmd)
  339. ret, out, err = run_in_shell(cmd)
  340. if ret == 0:
  341. return out.strip()
  342. else:
  343. return None
  344. def run_in_shell(cmd):
  345. print_info_msg('about to run command: ' + str(cmd))
  346. process = subprocess.Popen(cmd,
  347. stdout=subprocess.PIPE,
  348. stdin=subprocess.PIPE,
  349. stderr=subprocess.PIPE,
  350. shell=True
  351. )
  352. (stdoutdata, stderrdata) = process.communicate()
  353. return process.returncode, stdoutdata, stderrdata
  354. def run_os_command(cmd):
  355. print_info_msg('about to run command: ' + str(cmd))
  356. if type(cmd) == str:
  357. cmd = shlex.split(cmd)
  358. process = subprocess.Popen(cmd,
  359. stdout=subprocess.PIPE,
  360. stdin=subprocess.PIPE,
  361. stderr=subprocess.PIPE
  362. )
  363. (stdoutdata, stderrdata) = process.communicate()
  364. return process.returncode, stdoutdata, stderrdata
  365. #
  366. # Updates metainfo information from stack root. Re-cache information from
  367. # repoinfo.xml , metainfo.xml files , etc.
  368. #
  369. def update_metainfo(args):
  370. configure_update_metainfo_args(args)
  371. hostname = args.hostname
  372. port = args.port
  373. username = args.username
  374. password = args.password
  375. command = UPDATE_METAINFO_CMD
  376. command = command.format(hostname, port, username, password)
  377. retcode, outdata, errdata = run_os_command(command)
  378. if outdata.find("Bad credentials") > 0:
  379. print 'Incorrect credential provided. Please try again.'
  380. if not retcode == 0:
  381. print errdata
  382. return retcode
  383. def configure_update_metainfo_args(args):
  384. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  385. properties = Properties()
  386. try:
  387. properties.load(open(conf_file))
  388. except Exception, e:
  389. print 'Could not read ambari config file "%s": %s' % (conf_file, e)
  390. return -1
  391. default_username = "admin"
  392. username_prompt = 'Username [' + default_username + ']: '
  393. password_prompt = 'Password: '
  394. input_pattern = "^[a-zA-Z_][a-zA-Z0-9_\-]*$"
  395. hostname = socket.gethostname()
  396. port = properties[CLIENT_API_PORT_PROPERTY]
  397. if not port:
  398. port = CLIENT_API_PORT
  399. input_descr = "Invalid characters in received. Start with _ or alpha "\
  400. "followed by alphanumeric or _ or - characters"
  401. print 'Full authentication is required to access the Ambari API'
  402. username = get_validated_string_input(username_prompt, default_username,
  403. input_pattern, input_descr, False)
  404. password = get_validated_string_input(password_prompt, "", input_pattern,
  405. input_descr, True)
  406. args.hostname = hostname
  407. args.port = port
  408. args.username = username
  409. args.password = password
  410. #
  411. # Checks SELinux
  412. #
  413. def check_selinux():
  414. try:
  415. retcode, out, err = run_os_command(GET_SE_LINUX_ST_CMD)
  416. se_status = re.search('(disabled|enabled)', out).group(0)
  417. print "SELinux status is '" + se_status + "'"
  418. if se_status == SE_STATUS_DISABLED:
  419. return 0
  420. else:
  421. try:
  422. se_mode = re.search('(enforcing|permissive)', out).group(0)
  423. except AttributeError:
  424. err = "Error determining SELinux mode. Exiting."
  425. raise FatalException(1, err)
  426. print "SELinux mode is '" + se_mode + "'"
  427. if se_mode == SE_MODE_ENFORCING:
  428. print "Temporarily disabling SELinux"
  429. run_os_command(SE_SETENFORCE_CMD)
  430. print_warning_msg(
  431. "SELinux is set to 'permissive' mode and temporarily disabled."
  432. " You should disable SELinux permanently.")
  433. ok = get_YN_input("OK to continue [y/n] (y)? ", True)
  434. if not ok:
  435. raise FatalException(1, None)
  436. return 0
  437. except OSError:
  438. print_warning_msg("Could not run {0}: OK".format(GET_SE_LINUX_ST_CMD))
  439. return 0
  440. def read_ambari_user():
  441. '''
  442. Reads ambari user from properties file
  443. '''
  444. conf_file = find_properties_file()
  445. try:
  446. properties = Properties()
  447. properties.load(open(conf_file))
  448. user = properties[NR_USER_PROPERTY]
  449. if user:
  450. return user
  451. else:
  452. return None
  453. except Exception, e:
  454. print_error_msg('Could not read "%s": %s' % (conf_file, e))
  455. return None
  456. def adjust_directory_permissions(ambari_user):
  457. print "adjusting directory permissions..."
  458. for pack in NR_ADJUST_OWNERSHIP_LIST:
  459. file = pack[0]
  460. mod = pack[1]
  461. user = pack[2].format(ambari_user)
  462. group = pack[3].format(ambari_user)
  463. set_file_permissions(file, mod, user, group)
  464. def set_file_permissions(file, mod, user, group):
  465. WARN_MSG = "Command {0} returned exit code {1} with message: {2}"
  466. if os.path.exists(file):
  467. command = NR_CHMOD_CMD.format(mod, file)
  468. retcode, out, err = run_os_command(command)
  469. if retcode != 0 :
  470. print_warning_msg(WARN_MSG.format(command, file, err))
  471. command = NR_CHOWN_CMD.format(user, group, file)
  472. retcode, out, err = run_os_command(command)
  473. if retcode != 0 :
  474. print_warning_msg(WARN_MSG.format(command, file, err))
  475. else:
  476. print_warning_msg("File %s does not exist" % file)
  477. def create_custom_user():
  478. user = get_validated_string_input(
  479. "Please choose user name for ambari-server process: ",
  480. "ambari",
  481. "^[a-z_][a-z0-9_-]{1,31}$",
  482. "Invalid username.",
  483. False
  484. )
  485. print_info_msg("Trying to create group {0}".format(user))
  486. command = NR_GROUPADD_CMD.format(user)
  487. retcode, out, err = run_os_command(command)
  488. if retcode == 9: # 9 = group already exists
  489. print_warning_msg("Group {0} already exists, "
  490. "skipping group creation".format(user))
  491. elif retcode != 0: # fail:
  492. print_warning_msg("Can't create group {0}. Command {1} "
  493. "finished with {2}: \n{3}".format(user, command, retcode, err))
  494. return retcode, None
  495. print_info_msg("Trying to create user {0}".format(user))
  496. command = NR_USERADD_CMD.format(user, NR_USER_COMMENT)
  497. retcode, out, err = run_os_command(command)
  498. if retcode == 9: # 9 = username already in use
  499. print_warning_msg("User {0} already exists, "
  500. "skipping user creation".format(user))
  501. print_info_msg("Trying to add user {0} to group {0}".format(user))
  502. command = NR_ADD_USER_TO_GROUP.format(user)
  503. retcode, out, err = run_os_command(command)
  504. if retcode != 0: # fail:
  505. print_warning_msg("Can't add user {0} to group {0}. Command {1} "
  506. "finished with {2}: \n{3}".format(user, command, retcode, err))
  507. return retcode, None
  508. elif retcode != 0: # fail
  509. print_warning_msg("Can't create user {0}. Command {1} "
  510. "finished with {2}: \n{3}".format(user, command, retcode, err))
  511. return retcode, None
  512. print_info_msg("User/group configuration is done.")
  513. return 0, user
  514. def check_ambari_user():
  515. try:
  516. user = read_ambari_user()
  517. if user is not None:
  518. print_info_msg("Detected custom user {0}".format(user))
  519. else: # user is not configured yet or server is running under root
  520. ok = get_YN_input("Create a separate user for ambari-server "
  521. "daemon [y/n] (n)? ", False)
  522. if ok:
  523. (retcode, user) = create_custom_user()
  524. if retcode != 0:
  525. return retcode
  526. else:
  527. user = "root"
  528. write_property(NR_USER_PROPERTY, user)
  529. adjust_directory_permissions(user)
  530. except OSError:
  531. print_error_msg("Failed: %s" % OSError.message)
  532. return 4
  533. except Exception as e:
  534. print_error_msg("Unexpected error %s" % e.message)
  535. return 1
  536. return 0
  537. #
  538. # Checks iptables
  539. #
  540. def check_iptables():
  541. # not used
  542. # retcode, out, err = run_os_command(IP_TBLS_ST_CMD)
  543. ''' This check doesn't work on CentOS 6.2 if firewall AND
  544. iptables service are running if out == IP_TBLS_ENABLED:
  545. print 'iptables is enabled now'
  546. print 'Stopping iptables service'
  547. '''
  548. retcode, out, err = run_os_command(IP_TBLS_STOP_CMD)
  549. print 'iptables is disabled now'
  550. if not retcode == 0 and err and len(err) > 0:
  551. print err
  552. if err.strip() == IP_TBLS_SRVC_NT_FND:
  553. return 0
  554. else:
  555. return retcode, out
  556. ### Postgres ###
  557. def configure_pg_hba_ambaridb_users():
  558. args = optparse.Values()
  559. configure_database_username_password(args)
  560. with open(PG_HBA_CONF_FILE, "a") as pgHbaConf:
  561. pgHbaConf.write("\n")
  562. pgHbaConf.write("local all " + args.database_username +
  563. ",mapred md5")
  564. pgHbaConf.write("\n")
  565. pgHbaConf.write("host all " + args.database_username +
  566. ",mapred 0.0.0.0/0 md5")
  567. pgHbaConf.write("\n")
  568. pgHbaConf.write("host all " + args.database_username +
  569. ",mapred ::/0 md5")
  570. pgHbaConf.write("\n")
  571. command = PG_HBA_RELOAD_CMD.format(PG_HBA_DIR)
  572. retcode, out, err = run_os_command(command)
  573. if not retcode == 0:
  574. raise FatalException(retcode, err)
  575. def configure_pg_hba_postgres_user():
  576. postgresString = "all postgres"
  577. for line in fileinput.input(PG_HBA_CONF_FILE, inplace=1):
  578. print re.sub('all\s*all', postgresString, line),
  579. os.chmod(PG_HBA_CONF_FILE, 0644)
  580. def configure_postgresql_conf():
  581. listenAddress = "listen_addresses = '*' #"
  582. for line in fileinput.input(POSTGRESQL_CONF_FILE, inplace=1):
  583. print re.sub('#+listen_addresses.*?(#|$)', listenAddress, line),
  584. os.chmod(POSTGRESQL_CONF_FILE, 0644)
  585. def configure_postgres():
  586. if os.path.isfile(PG_HBA_CONF_FILE):
  587. if not os.path.isfile(PG_HBA_CONF_FILE_BACKUP):
  588. shutil.copyfile(PG_HBA_CONF_FILE, PG_HBA_CONF_FILE_BACKUP)
  589. else:
  590. #Postgres has been configured before, must not override backup
  591. print "Backup for pg_hba found, reconfiguration not required"
  592. return 0
  593. configure_pg_hba_postgres_user()
  594. configure_pg_hba_ambaridb_users()
  595. os.chmod(PG_HBA_CONF_FILE, 0644)
  596. configure_postgresql_conf()
  597. #restart postgresql if already running
  598. pg_status = get_postgre_status()
  599. if pg_status == PG_STATUS_RUNNING:
  600. retcode = restart_postgres()
  601. return retcode
  602. return 0
  603. def restart_postgres():
  604. print "Restarting PostgreSQL"
  605. process = subprocess.Popen(PG_RESTART_CMD.split(' '),
  606. stdout=subprocess.PIPE,
  607. stdin=subprocess.PIPE,
  608. stderr=subprocess.PIPE
  609. )
  610. time.sleep(5)
  611. result = process.poll()
  612. if result is None:
  613. print_info_msg("Killing restart PostgresSQL process")
  614. process.kill()
  615. pg_status = get_postgre_status()
  616. # SUSE linux set status of stopped postgresql proc to unused
  617. if pg_status == "unused" or pg_status == "stopped":
  618. print_info_msg("PostgreSQL is stopped. Restarting ...")
  619. retcode, out, err = run_os_command(PG_START_CMD)
  620. return retcode
  621. return 0
  622. # todo: check if the scheme is already exist
  623. def write_property(key, value):
  624. conf_file = find_properties_file()
  625. properties = Properties()
  626. try:
  627. properties.load(open(conf_file))
  628. except Exception, e:
  629. print_error_msg('Could not read ambari config file "%s": %s' % (conf_file, e))
  630. return -1
  631. properties.process_pair(key, value)
  632. try:
  633. properties.store(open(conf_file, "w"))
  634. except Exception, e:
  635. print_error_msg('Could not write ambari config file "%s": %s' % (conf_file, e))
  636. return -1
  637. return 0
  638. def setup_db(args):
  639. #password access to ambari-server and mapred
  640. configure_database_username_password(args)
  641. dbname = args.database_name
  642. scriptFile = args.init_script_file
  643. username = args.database_username
  644. password = args.database_password
  645. command = SETUP_DB_CMD[:]
  646. command[-1] = command[-1].format(scriptFile, username, password)
  647. retcode, outdata, errdata = run_os_command(command)
  648. if not retcode == 0:
  649. print errdata
  650. return retcode
  651. def store_password_file(password, filename):
  652. conf_file = find_properties_file()
  653. passFilePath = os.path.join(os.path.dirname(conf_file),
  654. filename)
  655. with open(passFilePath, 'w+') as passFile:
  656. passFile.write(password)
  657. print_info_msg("Adjusting filesystem permissions")
  658. ambari_user = read_ambari_user()
  659. set_file_permissions(passFilePath, "660", ambari_user, "root")
  660. return passFilePath
  661. def execute_db_script(args, file):
  662. #password access to ambari-server and mapred
  663. configure_database_username_password(args)
  664. dbname = args.database_name
  665. username = args.database_username
  666. password = args.database_password
  667. command = SETUP_DB_CMD[:]
  668. command[-1] = command[-1].format(file, username, password)
  669. retcode, outdata, errdata = run_os_command(command)
  670. if not retcode == 0:
  671. print errdata
  672. return retcode
  673. def check_db_consistency(args, file):
  674. #password access to ambari-server and mapred
  675. configure_database_username_password(args)
  676. dbname = args.database_name
  677. username = args.database_username
  678. password = args.database_password
  679. command = SETUP_DB_CMD[:]
  680. command[-1] = command[-1].format(file, username, password)
  681. retcode, outdata, errdata = run_os_command(command)
  682. if not retcode == 0:
  683. print errdata
  684. return retcode
  685. else:
  686. # Assumes that the output is of the form ...\n<count>
  687. print_info_msg("Parsing output: " + outdata)
  688. lines = outdata.splitlines()
  689. if (lines[-1] == '3' or lines[-1] == '0'):
  690. return 0
  691. return -1
  692. def get_postgre_status():
  693. retcode, out, err = run_os_command(PG_ST_CMD)
  694. try:
  695. pg_status = re.search('(stopped|running)', out).group(0)
  696. except AttributeError:
  697. pg_status = None
  698. return pg_status
  699. def check_postgre_up():
  700. pg_status = get_postgre_status()
  701. if pg_status == PG_STATUS_RUNNING:
  702. print_info_msg ("PostgreSQL is running")
  703. return 0
  704. else:
  705. print "Running initdb: This may take upto a minute."
  706. retcode, out, err = run_os_command(PG_INITDB_CMD)
  707. if retcode == 0:
  708. print out
  709. print "About to start PostgreSQL"
  710. try:
  711. process = subprocess.Popen(PG_START_CMD.split(' '),
  712. stdout=subprocess.PIPE,
  713. stdin=subprocess.PIPE,
  714. stderr=subprocess.PIPE
  715. )
  716. time.sleep(20)
  717. result = process.poll()
  718. print_info_msg("Result of postgres start cmd: " + str(result))
  719. if result is None:
  720. process.kill()
  721. pg_status = get_postgre_status()
  722. if pg_status == PG_STATUS_RUNNING:
  723. print_info_msg("Postgres process is running. Returning...")
  724. return 0
  725. else:
  726. retcode = result
  727. except (Exception), e:
  728. pg_status = get_postgre_status()
  729. if pg_status == PG_STATUS_RUNNING:
  730. return 0
  731. else:
  732. print_error_msg("Postgres start failed. " + str(e))
  733. return 1
  734. return retcode
  735. def read_password(passwordDefault=PG_DEFAULT_PASSWORD,
  736. passwordPattern=PASSWORD_PATTERN,
  737. passwordPrompt=None,
  738. passwordDescr=None):
  739. # setup password
  740. if passwordPrompt is None:
  741. passwordPrompt = 'Password [' + passwordDefault + ']: '
  742. if passwordDescr is None:
  743. passwordDescr = "Invalid characters in password. Use only alphanumeric or " \
  744. "_ or - characters"
  745. password = get_validated_string_input(passwordPrompt, passwordDefault,
  746. passwordPattern, passwordDescr, True)
  747. if password != passwordDefault:
  748. password1 = get_validated_string_input("Re-enter password: ",
  749. passwordDefault, passwordPattern, passwordDescr, True)
  750. if password != password1:
  751. print "Passwords do not match"
  752. password = read_password()
  753. return password
  754. def get_pass_file_path(conf_file):
  755. return os.path.join(os.path.dirname(conf_file),
  756. JDBC_PASSWORD_FILENAME)
  757. # Set database properties to default values
  758. def load_default_db_properties(args):
  759. args.database=DATABASE_NAMES[DATABASE_INDEX]
  760. args.database_host = "localhost"
  761. args.database_port = DATABASE_PORTS[DATABASE_INDEX]
  762. args.database_name = "ambari"
  763. args.database_username = "ambari"
  764. args.database_password = "bigdata"
  765. pass
  766. # Ask user for database conenction properties
  767. def prompt_db_properties(args):
  768. global DATABASE_INDEX
  769. if PROMPT_DATABASE_OPTIONS:
  770. load_default_db_properties(args)
  771. ok = get_YN_input("Enter advanced database configuration [y/n] (n)? ", False)
  772. if ok:
  773. database_num = str(DATABASE_INDEX + 1)
  774. database_num = get_validated_string_input(
  775. "Select database:\n1 - Postgres(Embedded)\n2 - Oracle\n[" + database_num + "]:",
  776. database_num,
  777. "^[12]$",
  778. "Invalid number.",
  779. False
  780. )
  781. DATABASE_INDEX = int(database_num) - 1
  782. args.database = DATABASE_NAMES[DATABASE_INDEX]
  783. if args.database != "postgres" :
  784. args.database_host = get_validated_string_input(
  785. "Hostname [" + args.database_host + "]:",
  786. args.database_host,
  787. "^[a-zA-Z0-9.\-]*$",
  788. "Invalid hostname.",
  789. False
  790. )
  791. args.database_port=DATABASE_PORTS[DATABASE_INDEX]
  792. args.database_port = get_validated_string_input(
  793. "Port [" + args.database_port + "]:",
  794. args.database_port,
  795. "^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$",
  796. "Invalid port.",
  797. False
  798. )
  799. pass
  800. else:
  801. args.database_host = "localhost"
  802. args.database_port = DATABASE_PORTS[DATABASE_INDEX]
  803. pass
  804. args.database_name = get_validated_string_input(
  805. DATABASE_STORAGE_NAMES[DATABASE_INDEX] + " Name [" + args.database_name + "]:",
  806. args.database_name,
  807. "^[a-zA-z\-\"]+$",
  808. "Invalid " + DATABASE_STORAGE_NAMES[DATABASE_INDEX] + " name.",
  809. False
  810. )
  811. args.database_username = get_validated_string_input(
  812. 'Username [' + args.database_username + ']: ',
  813. args.database_username,
  814. USERNAME_PATTERN,
  815. "Invalid characters in username. Start with _ or alpha "
  816. "followed by alphanumeric or _ or - characters",
  817. False
  818. )
  819. (masterKey, isSecure, isPersisted) = setup_master_key()
  820. (password, passwordAlias) = configure_database_password(isSecure,
  821. masterKey, True)
  822. args.database_password = password
  823. if passwordAlias:
  824. setattr(args, 'database_password_alias', passwordAlias) # Store alias if present
  825. print_info_msg('Using database options: {database},{host},{port},{schema},{user},{password}'.format(
  826. database=args.database,
  827. host=args.database_host,
  828. port=args.database_port,
  829. schema=args.database_name,
  830. user=args.database_username,
  831. password=args.database_password
  832. ))
  833. # Store set of properties for remote database connection
  834. def store_remote_properties(args):
  835. properties = get_ambari_properties()
  836. if properties == -1:
  837. print_error_msg ("Error getting ambari properties")
  838. return -1
  839. properties.process_pair(PERSISTENCE_TYPE_PROPERTY, "remote")
  840. properties.process_pair(JDBC_DATABASE_PROPERTY, args.database)
  841. properties.process_pair(JDBC_HOSTNAME_PROPERTY, args.database_host)
  842. properties.process_pair(JDBC_PORT_PROPERTY, args.database_port)
  843. properties.process_pair(JDBC_SCHEMA_PROPERTY, args.database_name)
  844. properties.process_pair(JDBC_DRIVER_PROPERTY, DATABASE_DRIVER_NAMES[DATABASE_INDEX])
  845. # fully qualify the hostname to make sure all the other hosts can connect
  846. # to the jdbc hostname since its passed onto the agents for RCA
  847. jdbc_hostname = args.database_host
  848. if (args.database_host == "localhost"):
  849. jdbc_hostname = socket.getfqdn();
  850. properties.process_pair(JDBC_URL_PROPERTY, DATABASE_CONNECTION_STRINGS[DATABASE_INDEX].format(jdbc_hostname, args.database_port, args.database_name))
  851. properties.process_pair(JDBC_USER_NAME_PROPERTY, args.database_username)
  852. if hasattr(args, 'database_password_alias') and args.database_password_alias:
  853. properties.process_pair(JDBC_PASSWORD_PROPERTY, args.database_password_alias)
  854. else:
  855. properties.process_pair(JDBC_PASSWORD_PROPERTY,
  856. store_password_file(args.database_password, JDBC_PASSWORD_FILENAME))
  857. properties.process_pair(JDBC_RCA_DRIVER_PROPERTY, DATABASE_DRIVER_NAMES[DATABASE_INDEX])
  858. properties.process_pair(JDBC_RCA_URL_PROPERTY, DATABASE_CONNECTION_STRINGS[DATABASE_INDEX].format(jdbc_hostname, args.database_port, args.database_name))
  859. properties.process_pair(JDBC_RCA_USER_NAME_PROPERTY, args.database_username)
  860. if hasattr(args, 'database_password_alias') and args.database_password_alias:
  861. properties.process_pair(JDBC_RCA_PASSWORD_FILE_PROPERTY,
  862. args.database_password_alias)
  863. else:
  864. properties.process_pair(JDBC_RCA_PASSWORD_FILE_PROPERTY,
  865. store_password_file(args.database_password, JDBC_PASSWORD_FILENAME))
  866. conf_file = properties.fileName
  867. try:
  868. properties.store(open(conf_file, "w"))
  869. except Exception, e:
  870. print 'Could not write ambari config file "%s": %s' % (conf_file, e)
  871. return -1
  872. return 0
  873. # Initialize remote database schema
  874. def setup_remote_db(args):
  875. not_found_msg = "Cannot find {0} {1} client in the path to load the Ambari Server schema.\
  876. Before starting Ambari Server, you must run the following DDL against the database to create \
  877. the schema ".format(DATABASE_NAMES[DATABASE_INDEX], str(DATABASE_CLI_TOOLS_DESC[DATABASE_INDEX]))
  878. client_usage_cmd = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_INIT_SCRIPTS[DATABASE_INDEX], args.database_username,
  879. args.database_password, args.database_name)
  880. retcode, out, err = execute_remote_script(args, DATABASE_INIT_SCRIPTS[DATABASE_INDEX])
  881. if retcode != 0:
  882. if retcode == -1:
  883. print_warning_msg(not_found_msg + os.linesep + client_usage_cmd)
  884. if not SILENT:
  885. raw_input(PRESS_ENTER_MSG)
  886. return retcode
  887. print err
  888. print_error_msg('Database bootstrap failed. Please, provide correct connection properties.')
  889. return retcode
  890. return 0
  891. # Get database client executable path
  892. def get_db_cli_tool(args):
  893. for tool in DATABASE_CLI_TOOLS[DATABASE_INDEX]:
  894. cmd =CHECK_COMMAND_EXIST_CMD.format(tool)
  895. ret, out, err = run_in_shell(cmd)
  896. if ret == 0:
  897. return get_exec_path(tool)
  898. return None
  899. #execute SQL script on remote database
  900. def execute_remote_script(args, scriptPath):
  901. tool = get_db_cli_tool(args)
  902. if not tool:
  903. args.warnings.append('{0} not found. Please, run DDL script manually'.format(DATABASE_CLI_TOOLS[DATABASE_INDEX]))
  904. if VERBOSE:
  905. print_warning_msg('{0} not found'.format(DATABASE_CLI_TOOLS[DATABASE_INDEX]))
  906. return -1, "Client wasn't found", "Client wasn't found"
  907. if args.database == "postgres":
  908. os.environ["PGPASSWORD"] = args.database_password
  909. retcode, out, err = run_in_shell('{0} {1}'.format(tool, POSTGRES_EXEC_ARGS.format(
  910. args.database_host,
  911. args.database_port,
  912. args.database_name,
  913. args.database_username,
  914. scriptPath
  915. )))
  916. return retcode, out, err
  917. elif args.database == "oracle":
  918. retcode, out, err = run_in_shell('{0} {1}'.format(tool, ORACLE_EXEC_ARGS.format(
  919. args.database_username,
  920. args.database_password,
  921. args.database_host,
  922. args.database_port,
  923. args.database_name,
  924. scriptPath
  925. )))
  926. return retcode, out, err
  927. elif args.database=="mysql":
  928. retcode, out, err = run_in_shell('{0} {1}'.format(tool, MYSQL_EXEC_ARGS.format(
  929. args.database_host,
  930. args.database_port,
  931. args.database_username,
  932. args.database_password,
  933. args.database_name,
  934. scriptPath
  935. )))
  936. return retcode, out, err
  937. return -2, "Wrong database", "Wrong database"
  938. def configure_database_password(isSecure=False, masterKey=None, showDefault=True):
  939. passwordDefault = PG_DEFAULT_PASSWORD
  940. if showDefault:
  941. passwordPrompt = 'Enter Database Password [' + passwordDefault + ']: '
  942. else:
  943. passwordPrompt = 'Enter Database Password: '
  944. passwordPattern = "^[a-zA-Z0-9_-]*$"
  945. passwordDescr = "Invalid characters in password. Use only alphanumeric or "\
  946. "_ or - characters"
  947. password = read_password(passwordDefault, passwordPattern, passwordPrompt,
  948. passwordDescr)
  949. aliasStr = None
  950. if isSecure:
  951. retCode = save_passwd_for_alias(JDBC_RCA_PASSWORD_ALIAS, password, masterKey)
  952. if retCode != 0:
  953. print 'Saving secure database password failed.'
  954. return password, aliasStr
  955. return password, get_alias_string(JDBC_RCA_PASSWORD_ALIAS)
  956. return password, aliasStr
  957. def configure_database_username_password(args):
  958. properties = get_ambari_properties()
  959. if properties == -1:
  960. print_error_msg ("Error getting ambari properties")
  961. return -1
  962. username = properties[JDBC_USER_NAME_PROPERTY]
  963. passwordProp = properties[JDBC_PASSWORD_PROPERTY]
  964. isPersisted = get_master_key_ispersisted(properties)
  965. if username and passwordProp:
  966. print_info_msg("Database username + password already configured")
  967. args.database_username=username
  968. if is_alias_string(passwordProp):
  969. if isPersisted:
  970. # No need to prompt for key
  971. args.database_password = read_passwd_for_alias(JDBC_RCA_PASSWORD_ALIAS)
  972. else:
  973. (masterKey, isSecure, isPersisted) = setup_master_key()
  974. args.database_password = read_passwd_for_alias(
  975. JDBC_RCA_PASSWORD_ALIAS, masterKey)
  976. return 1
  977. else:
  978. print_error_msg("Connection properties not set in config file.")
  979. # Store local database connection properties
  980. def store_local_properties(args):
  981. properties = get_ambari_properties()
  982. if properties == -1:
  983. print_error_msg ("Error getting ambari properties")
  984. return -1
  985. properties.removeOldProp(JDBC_SCHEMA_PROPERTY)
  986. properties.removeOldProp(JDBC_HOSTNAME_PROPERTY)
  987. properties.removeOldProp(JDBC_DATABASE_PROPERTY)
  988. properties.removeOldProp(JDBC_RCA_DRIVER_PROPERTY)
  989. properties.removeOldProp(JDBC_RCA_URL_PROPERTY)
  990. properties.removeOldProp(JDBC_PORT_PROPERTY)
  991. properties.removeOldProp(JDBC_PORT_PROPERTY)
  992. properties.removeOldProp(JDBC_DRIVER_PROPERTY)
  993. properties.removeOldProp(JDBC_URL_PROPERTY)
  994. properties.removeOldProp(JDBC_DATABASE_PROPERTY)
  995. properties.process_pair(PERSISTENCE_TYPE_PROPERTY, "local")
  996. properties.process_pair(JDBC_USER_NAME_PROPERTY, args.database_username)
  997. if hasattr(args, 'database_password_alias') and args.database_password_alias:
  998. properties.process_pair(JDBC_PASSWORD_PROPERTY,
  999. args.database_password_alias)
  1000. else:
  1001. properties.process_pair(JDBC_PASSWORD_PROPERTY,
  1002. store_password_file(args.database_password, JDBC_PASSWORD_FILENAME))
  1003. conf_file = properties.fileName
  1004. try:
  1005. properties.store(open(conf_file, "w"))
  1006. except Exception, e:
  1007. print 'Could not write ambari config file "%s": %s' % (conf_file, e)
  1008. return -1
  1009. return 0
  1010. # Load ambari properties and return dict with values
  1011. def get_ambari_properties():
  1012. conf_file = find_properties_file()
  1013. properties = None
  1014. try:
  1015. properties = Properties()
  1016. properties.load(open(conf_file))
  1017. except (Exception), e:
  1018. print 'Could not read "%s": %s' % (conf_file, e)
  1019. return -1
  1020. return properties
  1021. # Load database connection properties from conf file
  1022. def parse_properties_file(args):
  1023. conf_file = find_properties_file()
  1024. properties = Properties()
  1025. try:
  1026. properties.load(open(conf_file))
  1027. except Exception, e:
  1028. print 'Could not read ambari config file "%s": %s' % (conf_file, e)
  1029. return -1
  1030. args.persistence_type = properties[PERSISTENCE_TYPE_PROPERTY]
  1031. if not args.persistence_type:
  1032. args.persistence_type = "local"
  1033. if args.persistence_type == 'remote':
  1034. args.database = properties[JDBC_DATABASE_PROPERTY]
  1035. args.database_host = properties[JDBC_HOSTNAME_PROPERTY]
  1036. args.database_port = properties[JDBC_PORT_PROPERTY]
  1037. args.database_name = properties[JDBC_SCHEMA_PROPERTY]
  1038. global DATABASE_INDEX
  1039. try:
  1040. DATABASE_INDEX = DATABASE_NAMES.index(args.database)
  1041. except ValueError:
  1042. pass
  1043. args.database_username = properties[JDBC_USER_NAME_PROPERTY]
  1044. args.database_password_file = properties[JDBC_PASSWORD_PROPERTY]
  1045. if args.database_password_file:
  1046. if not is_alias_string(args.database_password_file):
  1047. args.database_password = open(properties[JDBC_PASSWORD_PROPERTY]).read()
  1048. else:
  1049. args.database_password = args.database_password_file
  1050. return 0
  1051. ### JDK ###
  1052. def get_ambari_jars():
  1053. try:
  1054. conf_dir = os.environ[AMBARI_SERVER_LIB]
  1055. return conf_dir
  1056. except KeyError:
  1057. default_jar_location = "/usr/lib/ambari-server"
  1058. print_info_msg(AMBARI_SERVER_LIB + " is not set, using default "
  1059. + default_jar_location)
  1060. return default_jar_location
  1061. def get_share_jars():
  1062. share_jars = ""
  1063. file_list = []
  1064. file_list.extend(glob.glob(JAVA_SHARE_PATH + os.sep + "*mysql*"))
  1065. file_list.extend(glob.glob(JAVA_SHARE_PATH + os.sep + "*ojdbc*"))
  1066. if len(file_list) > 0:
  1067. share_jars = string.join(file_list, os.pathsep)
  1068. return share_jars
  1069. def get_ambari_classpath():
  1070. ambari_cp = get_ambari_jars() + os.sep + "*"
  1071. share_cp = get_share_jars()
  1072. if len(share_cp) > 0:
  1073. ambari_cp = ambari_cp + os.pathsep + share_cp
  1074. return ambari_cp
  1075. def search_file(filename, search_path, pathsep=os.pathsep):
  1076. """ Given a search path, find file with requested name """
  1077. for path in string.split(search_path, pathsep):
  1078. candidate = os.path.join(path, filename)
  1079. if os.path.exists(candidate): return os.path.abspath(candidate)
  1080. return None
  1081. def dlprogress(base_name, count, blockSize, totalSize):
  1082. percent = int(count * blockSize * 100 / totalSize)
  1083. if (totalSize < blockSize):
  1084. sys.stdout.write("\r" + base_name + "... %d%%" % (100))
  1085. else:
  1086. sys.stdout.write("\r" + base_name + "... %d%% (%.1f MB of %.1f MB)" % (
  1087. percent, count * blockSize / 1024 / 1024.0, totalSize / 1024 / 1024.0))
  1088. if (percent == 100 or totalSize < blockSize):
  1089. sys.stdout.write("\n")
  1090. sys.stdout.flush()
  1091. def track_jdk(base_name, url, local_name):
  1092. u = urllib2.urlopen(url)
  1093. h = u.info()
  1094. totalSize = int(h["Content-Length"])
  1095. fp = open(local_name, "wb")
  1096. blockSize = 8192
  1097. count = 0
  1098. percent = 0
  1099. while True:
  1100. chunk = u.read(blockSize)
  1101. if not chunk:
  1102. break
  1103. fp.write(chunk)
  1104. count += 1
  1105. dlprogress(base_name, count, blockSize, totalSize)
  1106. fp.flush()
  1107. fp.close()
  1108. def install_jce_manualy(args):
  1109. properties = get_ambari_properties()
  1110. if properties == -1:
  1111. err = "Error getting ambari properties"
  1112. raise FatalException(-1, err)
  1113. if args.jce_policy and os.path.exists(args.jce_policy):
  1114. jce_destination = os.path.join(properties[RESOURCES_DIR_PROPERTY], JCE_POLICY_FILENAME)
  1115. shutil.copy(args.jce_policy, jce_destination)
  1116. print "JCE policy copied from " + args.jce_policy + " to " + jce_destination
  1117. return 0
  1118. else:
  1119. return 1
  1120. #
  1121. # Downloads the JDK
  1122. #
  1123. def download_jdk(args):
  1124. jce_installed = install_jce_manualy(args)
  1125. if get_JAVA_HOME():
  1126. return 0
  1127. if args.java_home and os.path.exists(args.java_home):
  1128. print_warning_msg("JAVA_HOME " + args.java_home
  1129. + " must be valid on ALL hosts")
  1130. write_property(JAVA_HOME_PROPERTY, args.java_home)
  1131. return 0
  1132. properties = get_ambari_properties()
  1133. if properties == -1:
  1134. err = "Error getting ambari properties"
  1135. raise FatalException(-1, err)
  1136. conf_file = properties.fileName
  1137. try:
  1138. jdk_url = properties[JDK_URL_PROPERTY]
  1139. resources_dir = properties[RESOURCES_DIR_PROPERTY]
  1140. except (KeyError), e:
  1141. err = 'Property ' + str(e) + ' is not defined at ' + conf_file
  1142. raise FatalException(1, err)
  1143. dest_file = resources_dir + os.sep + JDK_LOCAL_FILENAME
  1144. if not os.path.exists(dest_file):
  1145. print 'Downloading JDK from ' + jdk_url + ' to ' + dest_file
  1146. try:
  1147. size_command = JDK_DOWNLOAD_SIZE_CMD.format(jdk_url);
  1148. #Get Header from url,to get file size then
  1149. retcode, out, err = run_os_command(size_command)
  1150. if out.find("Content-Length") == -1:
  1151. err = "Request header doesn't contain Content-Length"
  1152. raise FatalException(1, err)
  1153. start_with = int(out.find("Content-Length") + len("Content-Length") + 2)
  1154. end_with = out.find("\r\n", start_with)
  1155. src_size = int(out[start_with:end_with])
  1156. print 'JDK distribution size is ' + str(src_size) + ' bytes'
  1157. file_exists = os.path.isfile(dest_file)
  1158. file_size = -1
  1159. if file_exists:
  1160. file_size = os.stat(dest_file).st_size
  1161. if file_exists and file_size == src_size:
  1162. print_info_msg("File already exists")
  1163. else:
  1164. track_jdk(JDK_LOCAL_FILENAME, jdk_url, dest_file)
  1165. print 'Successfully downloaded JDK distribution to ' + dest_file
  1166. except FatalException:
  1167. raise
  1168. except Exception, e:
  1169. err = 'Failed to download JDK: ' + str(e)
  1170. raise FatalException(1, err)
  1171. downloaded_size = os.stat(dest_file).st_size
  1172. if downloaded_size != src_size or downloaded_size < JDK_MIN_FILESIZE:
  1173. err = 'Size of downloaded JDK distribution file is ' \
  1174. + str(downloaded_size) + ' bytes, it is probably \
  1175. damaged or incomplete'
  1176. raise FatalException(1, err)
  1177. else:
  1178. print "JDK already exists using " + dest_file
  1179. try:
  1180. out, ok = install_jdk(dest_file)
  1181. jdk_version = re.search('Creating (jdk.*)/jre', out).group(1)
  1182. except Exception, e:
  1183. print "Installation of JDK has failed: %s\n" % e.message
  1184. file_exists = os.path.isfile(dest_file)
  1185. if file_exists:
  1186. ok = get_YN_input("JDK found at "+dest_file+". "
  1187. "Would you like to re-download the JDK [y/n] (y)? ", True)
  1188. if not ok:
  1189. err = "Unable to install JDK. Please remove JDK file found at "+ dest_file +" and re-run Ambari Server setup"
  1190. raise FatalException(1, err)
  1191. else:
  1192. track_jdk(JDK_LOCAL_FILENAME, jdk_url, dest_file)
  1193. print 'Successfully re-downloaded JDK distribution to ' + dest_file
  1194. try:
  1195. out, ok = install_jdk(dest_file)
  1196. jdk_version = re.search('Creating (jdk.*)/jre', out).group(1)
  1197. except Exception, e:
  1198. print "Installation of JDK was failed: %s\n" % e.message
  1199. err = "Unable to install JDK. Please remove JDK, file found at "+ dest_file +" and re-run Ambari Server setup"
  1200. raise FatalException(1, err)
  1201. else:
  1202. err = "Unable to install JDK. File "+ dest_file +" does not exist, please re-run Ambari Server setup"
  1203. raise FatalException(1, err)
  1204. print "Successfully installed JDK to {0}/{1}".\
  1205. format(JDK_INSTALL_DIR, jdk_version)
  1206. write_property(JAVA_HOME_PROPERTY, "{0}/{1}".
  1207. format(JDK_INSTALL_DIR, jdk_version))
  1208. if jce_installed != 0:
  1209. try:
  1210. download_jce_policy(properties, ok)
  1211. except FatalException as e:
  1212. print "JCE Policy files are required for secure HDP setup. Please ensure " \
  1213. " all hosts have the JCE unlimited strength policy 6, files."
  1214. print_error_msg("Failed to download JCE policy files:")
  1215. if e.reason is not None:
  1216. print_error_msg("Reason: {0}".format(e.reason))
  1217. # TODO: We don't fail installation if download_jce_policy fails. Is it OK?
  1218. return 0
  1219. def download_jce_policy(properties, accpeted_bcl):
  1220. try:
  1221. jce_url = properties[JCE_URL_PROPERTY]
  1222. resources_dir = properties[RESOURCES_DIR_PROPERTY]
  1223. except KeyError, e:
  1224. err = 'Property ' + str(e) + ' is not defined in properties file'
  1225. raise FatalException(1, err)
  1226. dest_file = resources_dir + os.sep + JCE_POLICY_FILENAME
  1227. if not os.path.exists(dest_file):
  1228. print 'Downloading JCE Policy archive from ' + jce_url + ' to ' + dest_file
  1229. try:
  1230. size_command = JDK_DOWNLOAD_SIZE_CMD.format(jce_url);
  1231. #Get Header from url,to get file size then
  1232. retcode, out, err = run_os_command(size_command)
  1233. if out.find("Content-Length") == -1:
  1234. err = "Request header doesn't contain Content-Length";
  1235. raise FatalException(1, err)
  1236. start_with = int(out.find("Content-Length") + len("Content-Length") + 2)
  1237. end_with = out.find("\r\n", start_with)
  1238. src_size = int(out[start_with:end_with])
  1239. print_info_msg('JCE zip distribution size is ' + str(src_size) + ' bytes')
  1240. file_exists = os.path.isfile(dest_file)
  1241. file_size = -1
  1242. if file_exists:
  1243. file_size = os.stat(dest_file).st_size
  1244. if file_exists and file_size == src_size:
  1245. print_info_msg("File already exists")
  1246. else:
  1247. #BCL license before download
  1248. jce_download_cmd = JCE_DOWNLOAD_CMD.format(dest_file, jce_url)
  1249. print_info_msg("JCE download cmd: " + jce_download_cmd)
  1250. if accpeted_bcl:
  1251. retcode, out, err = run_os_command(jce_download_cmd)
  1252. if retcode == 0:
  1253. print 'Successfully downloaded JCE Policy archive to ' + dest_file
  1254. else:
  1255. raise FatalException(1, err)
  1256. else:
  1257. ok = get_YN_input("To download the JCE Policy archive you must "
  1258. "accept the license terms found at "
  1259. "http://www.oracle.com/technetwork/java/javase"
  1260. "/terms/license/index.html"
  1261. "Not accepting might result in failure when "
  1262. "setting up HDP security. \nDo you accept the "
  1263. "Oracle Binary Code License Agreement [y/n] (y)? ", True)
  1264. if ok:
  1265. retcode, out, err = run_os_command(jce_download_cmd)
  1266. if retcode == 0:
  1267. print 'Successfully downloaded JCE Policy archive to ' + dest_file
  1268. else:
  1269. raise FatalException(1, None)
  1270. except FatalException:
  1271. raise
  1272. except Exception, e:
  1273. err = 'Failed to download JCE Policy archive: ' + str(e)
  1274. raise FatalException(1, err)
  1275. downloaded_size = os.stat(dest_file).st_size
  1276. if downloaded_size != src_size or downloaded_size < JCE_MIN_FILESIZE:
  1277. err = 'Size of downloaded JCE Policy archive is ' \
  1278. + str(downloaded_size) + ' bytes, it is probably \
  1279. damaged or incomplete'
  1280. raise FatalException(1, err)
  1281. else:
  1282. print "JCE Policy archive already exists, using " + dest_file
  1283. class RetCodeException(Exception): pass
  1284. def install_jdk(dest_file):
  1285. ok = get_YN_input("To install the Oracle JDK you must accept the "
  1286. "license terms found at "
  1287. "http://www.oracle.com/technetwork/java/javase/"
  1288. "downloads/jdk-6u21-license-159167.txt. Not accepting will "
  1289. "cancel the Ambari Server setup.\nDo you accept the "
  1290. "Oracle Binary Code License Agreement [y/n] (y)? ", True)
  1291. if not ok:
  1292. raise FatalException(1, None)
  1293. print "Installing JDK to {0}".format(JDK_INSTALL_DIR)
  1294. retcode, out, err = run_os_command(CREATE_JDK_DIR_CMD)
  1295. savedPath = os.getcwd()
  1296. os.chdir(JDK_INSTALL_DIR)
  1297. retcode, out, err = run_os_command(MAKE_FILE_EXECUTABLE_CMD.format(dest_file))
  1298. retcode, out, err = run_os_command(dest_file + ' -noregister')
  1299. os.chdir(savedPath)
  1300. if retcode != 0:
  1301. err = "Installation of JDK returned exit code %s" % retcode
  1302. raise FatalException(retcode, err)
  1303. return out, ok
  1304. #
  1305. # Configures the OS settings in ambari properties.
  1306. #
  1307. def configure_os_settings():
  1308. properties = get_ambari_properties()
  1309. if properties == -1:
  1310. print_error_msg ("Error getting ambari properties")
  1311. return -1
  1312. try:
  1313. conf_os_type = properties[OS_TYPE_PROPERTY]
  1314. if conf_os_type != '':
  1315. print_info_msg ("os_type already setting in properties file")
  1316. return 0
  1317. except (KeyError), e:
  1318. print_error_msg ("os_type is not set in properties file")
  1319. os_system = platform.system()
  1320. if os_system != 'Linux':
  1321. print_error_msg ("Non-Linux systems are not supported")
  1322. return -1
  1323. os_info = platform.linux_distribution(
  1324. None, None, None, ['SuSE', 'redhat' ], 0
  1325. )
  1326. os_name = os_info[0].lower()
  1327. if os_name == 'suse':
  1328. os_name = 'sles'
  1329. os_version = os_info[1].split('.', 1)[0]
  1330. master_os_type = os_name + os_version
  1331. write_property(OS_TYPE_PROPERTY, master_os_type)
  1332. return 0
  1333. def get_JAVA_HOME():
  1334. properties = get_ambari_properties()
  1335. if properties == -1:
  1336. print_error_msg ("Error getting ambari properties")
  1337. return None
  1338. java_home = properties[JAVA_HOME_PROPERTY]
  1339. if (not 0 == len(java_home)) and (os.path.exists(java_home)):
  1340. return java_home
  1341. return None
  1342. #
  1343. # Finds the available JDKs.
  1344. #
  1345. def find_jdk():
  1346. if get_JAVA_HOME():
  1347. return get_JAVA_HOME()
  1348. print "Looking for available JDKs at " + JDK_INSTALL_DIR
  1349. jdks = glob.glob(JDK_INSTALL_DIR + os.sep + "jdk*")
  1350. jdks.sort()
  1351. print "Found: " + str(jdks)
  1352. count = len(jdks)
  1353. if count == 0:
  1354. return
  1355. jdkPath = jdks[count - 1]
  1356. print "Selected JDK {0}".format(jdkPath)
  1357. return jdkPath
  1358. #
  1359. # Checks if options determine local DB configuration
  1360. #
  1361. def is_local_database(options):
  1362. if options.database == DATABASE_NAMES[0] \
  1363. and options.database_host == "localhost" \
  1364. and options.database_port == DATABASE_PORTS[0] \
  1365. and options.database_name == "ambari":
  1366. return True
  1367. return False
  1368. #Check if required jdbc drivers present
  1369. def find_jdbc_driver(args):
  1370. if args.database in JDBC_PATTERNS.keys():
  1371. drivers = []
  1372. drivers.extend(glob.glob(JAVA_SHARE_PATH + os.sep + JDBC_PATTERNS[args.database]))
  1373. if drivers:
  1374. return drivers
  1375. return -1
  1376. return 0
  1377. def copy_files(files, dest_dir):
  1378. if os.path.isdir(dest_dir):
  1379. for filepath in files:
  1380. shutil.copy(filepath, dest_dir)
  1381. return 0
  1382. else:
  1383. return -1
  1384. def check_jdbc_drivers(args):
  1385. properties = get_ambari_properties()
  1386. ## ask user twice
  1387. for i in range(0,2):
  1388. result = find_jdbc_driver(args)
  1389. if result == -1:
  1390. msg = 'WARNING: Before starting Ambari Server, ' \
  1391. 'the {0} JDBC driver JAR file must be copied to {1}. Press enter to continue.'.format(
  1392. DATABASE_FULL_NAMES[args.database],
  1393. JAVA_SHARE_PATH
  1394. )
  1395. if not SILENT:
  1396. raw_input(msg)
  1397. else:
  1398. print_warning_msg(msg)
  1399. # check if user provided drivers
  1400. result = find_jdbc_driver(args)
  1401. if type(result) is not int:
  1402. print 'Copying JDBC drivers to server resources...'
  1403. try:
  1404. resources_dir = properties[RESOURCES_DIR_PROPERTY]
  1405. except KeyError:
  1406. print_error_msg("There is no value for " + RESOURCES_DIR_PROPERTY + "in " + AMBARI_PROPERTIES_FILE)
  1407. return -1
  1408. copy_files(result, resources_dir)
  1409. break
  1410. return 0
  1411. #
  1412. # Setup the Ambari Server.
  1413. #
  1414. def setup(args):
  1415. if not is_root():
  1416. err = 'Ambari-server setup should be run with '\
  1417. 'root-level privileges'
  1418. raise FatalException(4, err)
  1419. print 'Checking SELinux...'
  1420. retcode = check_selinux()
  1421. if not retcode == 0:
  1422. err = 'Failed to disable SELinux. Exiting.'
  1423. raise FatalException(retcode, err)
  1424. # Create ambari user, if needed
  1425. retcode = check_ambari_user()
  1426. if not retcode == 0:
  1427. err = 'Failed to create user. Exiting.'
  1428. raise FatalException(retcode, err)
  1429. print 'Checking iptables...'
  1430. retcode, out = check_iptables()
  1431. if not retcode == 0 and out == IP_TBLS_ENABLED:
  1432. err = 'Failed to stop iptables. Exiting.'
  1433. raise FatalException(retcode, err)
  1434. print 'Checking JDK...'
  1435. try:
  1436. download_jdk(args)
  1437. except FatalException as e:
  1438. err = 'Downloading or installing JDK failed: {0}. Exiting.'.format(e)
  1439. raise FatalException(e.code, err)
  1440. print 'Completing setup...'
  1441. retcode = configure_os_settings()
  1442. if not retcode == 0:
  1443. err = 'Configure of OS settings in ambari.properties failed. Exiting.'
  1444. raise FatalException(retcode, err)
  1445. print 'Configuring database...'
  1446. prompt_db_properties(args)
  1447. #DB setup should be done last after doing any setup.
  1448. if is_local_database(args):
  1449. print 'Default properties detected. Using built-in database.'
  1450. store_local_properties(args)
  1451. print 'Checking PostgreSQL...'
  1452. retcode = check_postgre_up()
  1453. if not retcode == 0:
  1454. err = 'Unable to start PostgreSQL server. Exiting'
  1455. raise FatalException(retcode, err)
  1456. print 'Configuring database...'
  1457. retcode = setup_db(args)
  1458. if not retcode == 0:
  1459. err = 'Running database init script was failed. Exiting.'
  1460. raise FatalException(retcode, err)
  1461. print 'Configuring PostgreSQL...'
  1462. retcode = configure_postgres()
  1463. if not retcode == 0:
  1464. err = 'Unable to configure PostgreSQL server. Exiting'
  1465. raise FatalException(retcode, err)
  1466. else:
  1467. retcode = store_remote_properties(args)
  1468. if retcode != 0:
  1469. err = 'Unable to save config file'
  1470. raise FatalException(retcode, err)
  1471. check_jdbc_drivers(args)
  1472. print 'Configuring remote database connection properties...'
  1473. retcode = setup_remote_db(args)
  1474. if retcode == -1:
  1475. err = "The cli was not found"
  1476. raise FatalException(retcode, err)
  1477. if not retcode == 0:
  1478. err = 'Error while configuring connection properties. Exiting'
  1479. raise FatalException(retcode, err)
  1480. check_jdbc_drivers(args)
  1481. if args.warnings:
  1482. print "Ambari Server 'setup' finished with warnings:"
  1483. for warning in args.warnings:
  1484. print warning
  1485. else:
  1486. print "Ambari Server 'setup' finished successfully"
  1487. #
  1488. # Resets the Ambari Server.
  1489. #
  1490. def reset(args):
  1491. if not is_root():
  1492. err = 'Ambari-server reset should be run with ' \
  1493. 'root-level privileges'
  1494. raise FatalException(4, err)
  1495. choice = get_YN_input("**** WARNING **** You are about to reset and clear the "
  1496. "Ambari Server database. This will remove all cluster "
  1497. "host and configuration information from the database. "
  1498. "You will be required to re-configure the Ambari server "
  1499. "and re-run the cluster wizard. \n"
  1500. "Are you SURE you want to perform the reset "
  1501. "[yes/no]? ", True)
  1502. okToRun = choice
  1503. if not okToRun:
  1504. err = "Ambari Server 'reset' cancelled"
  1505. raise FatalException(1, err)
  1506. okToRun = get_YN_input("Confirm server reset [yes/no]? ", True)
  1507. if not okToRun:
  1508. err = "Ambari Server 'reset' cancelled"
  1509. raise FatalException(1, err)
  1510. print "Resetting the Server database..."
  1511. parse_properties_file(args)
  1512. # configure_database_username_password(args)
  1513. if args.persistence_type=="remote":
  1514. client_desc = DATABASE_NAMES[DATABASE_INDEX] + ' ' + DATABASE_CLI_TOOLS_DESC[DATABASE_INDEX]
  1515. client_usage_cmd_drop = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_DROP_SCRIPTS[DATABASE_INDEX], args.database_username,
  1516. args.database_password, args.database_name)
  1517. client_usage_cmd_init = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_INIT_SCRIPTS[DATABASE_INDEX], args.database_username,
  1518. args.database_password, args.database_name)
  1519. if get_db_cli_tool(args) != -1:
  1520. retcode, out, err = execute_remote_script(args, DATABASE_DROP_SCRIPTS[DATABASE_INDEX])
  1521. if not retcode == 0:
  1522. if retcode == -1:
  1523. print_warning_msg('Cannot find ' + client_desc + ' client in the path to reset the Ambari Server schema. To reset Ambari Server schema ' +
  1524. 'you must run the following DDL against the database to drop the schema:' + os.linesep + client_usage_cmd_drop + os.linesep +
  1525. ', then you must run the following DDL against the database to create the schema ' + os.linesep + client_usage_cmd_init + os.linesep )
  1526. raise FatalException(retcode, err)
  1527. retcode, out, err = execute_remote_script(args, DATABASE_INIT_SCRIPTS[DATABASE_INDEX])
  1528. if not retcode == 0:
  1529. if retcode == -1:
  1530. print_warning_msg('Cannot find ' + client_desc + ' client in the path to reset the Ambari Server schema. To reset Ambari Server schema ' +
  1531. 'you must run the following DDL against the database to drop the schema:' + os.linesep + client_usage_cmd_drop + os.linesep +
  1532. ', then you must run the following DDL against the database to create the schema ' + os.linesep + client_usage_cmd_init + os.linesep )
  1533. raise FatalException(retcode, err)
  1534. else:
  1535. err = 'Cannot find ' + client_desc + ' client in the path to reset the Ambari Server schema. To reset Ambari Server schema ' + \
  1536. 'you must run the following DDL against the database to drop the schema:' + os.linesep + client_usage_cmd_drop + os.linesep + \
  1537. ', then you must run the following DDL against the database to create the schema ' + os.linesep + client_usage_cmd_init + os.linesep
  1538. raise FatalException(-1, err)
  1539. else:
  1540. dbname = args.database_name
  1541. filename = args.drop_script_file
  1542. username = args.database_username
  1543. password = args.database_password
  1544. command = SETUP_DB_CMD[:]
  1545. command[-1] = command[-1].format(filename, username, password)
  1546. retcode, outdata, errdata = run_os_command(command)
  1547. if not retcode == 0:
  1548. raise FatalException(1, errdata)
  1549. print_info_msg ("About to run database setup")
  1550. setup_db(args)
  1551. print "Ambari Server 'reset' complete"
  1552. #
  1553. # Starts the Ambari Server.
  1554. #
  1555. def start(args):
  1556. parse_properties_file(args)
  1557. if os.path.exists(PID_DIR + os.sep + PID_NAME):
  1558. f = open(PID_DIR + os.sep + PID_NAME, "r")
  1559. pid = int(f.readline())
  1560. f.close()
  1561. try:
  1562. os.kill(pid, 0)
  1563. err = "Server is already running."
  1564. raise FatalException(1, err)
  1565. except OSError as e:
  1566. print_info_msg("Server is not running...")
  1567. current_user = getpass.getuser()
  1568. ambari_user = read_ambari_user()
  1569. if ambari_user is None:
  1570. err = "Can not detect a system user for Ambari. " \
  1571. "Please run \"setup\" command to create such user "
  1572. raise FatalException(1, err)
  1573. if current_user != ambari_user and not is_root():
  1574. err = "Can not start ambari-server as user {0}. Please either run \"start\" " \
  1575. "command as root or as user {1}".format(current_user, ambari_user)
  1576. raise FatalException(1, err)
  1577. conf_dir = get_conf_dir()
  1578. jdk_path = find_jdk()
  1579. if jdk_path is None:
  1580. err = "No JDK found, please run the \"setup\" " \
  1581. "command to install a JDK automatically or install any " \
  1582. "JDK manually to " + JDK_INSTALL_DIR
  1583. raise FatalException(1, err)
  1584. # Preparations
  1585. if is_root():
  1586. print "Have root privileges."
  1587. if args.persistence_type == "local":
  1588. retcode = check_postgre_up()
  1589. if not retcode == 0:
  1590. err = "Unable to start PostgreSQL server. Exiting"
  1591. raise FatalException(retcode, err)
  1592. print 'Checking iptables...'
  1593. retcode, out = check_iptables()
  1594. if not retcode == 0 and out == IP_TBLS_ENABLED:
  1595. err = "Failed to stop iptables. Exiting"
  1596. raise FatalException(retcode, err)
  1597. else: # Skipping actions that require root permissions
  1598. print "Can not check iptables status when starting "\
  1599. "without root privileges."
  1600. print "Please don't forget to disable or adjust iptables if needed"
  1601. if args.persistence_type == "local":
  1602. print "Can not check PostgreSQL server status when starting " \
  1603. "without root privileges."
  1604. print "Please don't forget to start PostgreSQL server."
  1605. properties = get_ambari_properties()
  1606. persist = get_master_key_ispersisted(properties)
  1607. environ = os.environ.copy()
  1608. # Need to handle master key not persisted scenario
  1609. if persist is not None and not persist:
  1610. prompt = False
  1611. try:
  1612. masterKey = environ[SECURITY_KEY_ENV_VAR_NAME]
  1613. except KeyError:
  1614. masterKey = None
  1615. if masterKey is not None and masterKey != "":
  1616. pass
  1617. else:
  1618. try:
  1619. keyLocation = environ[SECURITY_MASTER_KEY_LOCATION]
  1620. except KeyError:
  1621. keyLocation = None
  1622. if keyLocation is not None:
  1623. try:
  1624. # Verify master key can be read by the java process
  1625. with open(keyLocation, 'r') : pass
  1626. except IOError:
  1627. print_warning_msg("Cannot read Master key from path specified in "
  1628. "environemnt.")
  1629. prompt = True
  1630. else:
  1631. # Key not provided in the environment
  1632. prompt = True
  1633. if prompt:
  1634. masterKey = get_validated_string_input("Please provide master key " +\
  1635. "for unlocking credential store: ", "", ".*", "", False)
  1636. tempDir = tempfile.gettempdir()
  1637. tempFilePath = tempDir + os.sep + "masterkey"
  1638. save_master_key(masterKey, tempFilePath, True)
  1639. os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)
  1640. if tempFilePath is not None:
  1641. environ[SECURITY_MASTER_KEY_LOCATION] = tempFilePath
  1642. pidfile = PID_DIR + os.sep + PID_NAME
  1643. command_base = SERVER_START_CMD_DEBUG if (SERVER_DEBUG_MODE or SERVER_START_DEBUG) else SERVER_START_CMD
  1644. command = command_base.format(jdk_path, conf_dir, get_ambari_classpath(), pidfile)
  1645. if is_root() and ambari_user != "root":
  1646. # To inherit exported environment variables (especially AMBARI_PASSPHRASE),
  1647. # from subprocess, we have to skip --login option of su command. That's why
  1648. # we change dir to / (otherwise subprocess can face with 'permission denied'
  1649. # errors while trying to list current directory
  1650. os.chdir("/")
  1651. param_list = ["/bin/su", ambari_user, "-s", "/bin/sh", "-c", command]
  1652. else:
  1653. param_list = ["/bin/sh", "-c", command]
  1654. print "Running server: " + str(param_list)
  1655. server_process = subprocess.Popen(param_list, env=environ)
  1656. print "done."
  1657. #
  1658. # Stops the Ambari Server.
  1659. #
  1660. def stop(args):
  1661. if os.path.exists(PID_DIR + os.sep + PID_NAME):
  1662. f = open(PID_DIR + os.sep + PID_NAME, "r")
  1663. pid = int(f.readline())
  1664. try:
  1665. os.killpg(os.getpgid(pid), signal.SIGKILL)
  1666. except OSError, e:
  1667. print_info_msg( "Unable to stop Ambari Server - " + str(e) )
  1668. return
  1669. f.close()
  1670. os.remove(f.name)
  1671. print "Ambari Server stopped"
  1672. else:
  1673. print "Ambari Server is not running"
  1674. ### Stack upgrade ###
  1675. def upgrade_stack(args, stack_id):
  1676. if not is_root():
  1677. err = 'Ambari-server upgradestack should be run with ' \
  1678. 'root-level privileges'
  1679. raise FatalException(4, err)
  1680. #password access to ambari-server and mapred
  1681. configure_database_username_password(args)
  1682. dbname = args.database_name
  1683. file = args.upgrade_stack_script_file
  1684. stack_name, stack_version = stack_id.split(STACK_NAME_VER_SEP)
  1685. command = UPGRADE_STACK_CMD[:]
  1686. command[-1] = command[-1].format(file, stack_name, stack_version)
  1687. retcode, outdata, errdata = run_os_command(command)
  1688. if not retcode == 0:
  1689. raise FatalException(retcode, errdata)
  1690. return retcode
  1691. #
  1692. # Upgrades the Ambari Server.
  1693. #
  1694. def upgrade(args):
  1695. if not is_root():
  1696. err = 'Ambari-server upgrade should be run with ' \
  1697. 'root-level privileges'
  1698. raise FatalException(4, err)
  1699. print 'Updating properties in ' + AMBARI_PROPERTIES_FILE + ' ...'
  1700. retcode = update_ambari_properties()
  1701. if not retcode == 0:
  1702. err = AMBARI_PROPERTIES_FILE + ' file can\'t be updated. Exiting'
  1703. raise FatalException(retcode, err)
  1704. parse_properties_file(args)
  1705. if args.persistence_type == "remote":
  1706. pass
  1707. else:
  1708. print 'Checking PostgreSQL...'
  1709. retcode = check_postgre_up()
  1710. if not retcode == 0:
  1711. err = 'PostgreSQL server not running. Exiting'
  1712. raise FatalException(retcode, err)
  1713. file = args.upgrade_script_file
  1714. print 'Upgrading database...'
  1715. retcode = execute_db_script(args, file)
  1716. if not retcode == 0:
  1717. err = 'Database upgrade script has failed. Exiting.'
  1718. raise FatalException(retcode, err)
  1719. print 'Checking database integrity...'
  1720. check_file = file[:-3] + "Check" + file[-4:]
  1721. retcode = check_db_consistency(args, check_file)
  1722. if not retcode == 0:
  1723. print 'Found inconsistency. Trying to fix...'
  1724. fix_file = file[:-3] + "Fix" + file[-4:]
  1725. retcode = execute_db_script(args, fix_file)
  1726. if not retcode == 0:
  1727. err = 'Database cannot be fixed. Exiting.'
  1728. raise FatalException(retcode, err)
  1729. else:
  1730. print 'Database is consistent.'
  1731. user = read_ambari_user()
  1732. if user is None:
  1733. warn = 'Can not determine custom ambari user. Please run ' \
  1734. '"ambari-server setup" before starting server'
  1735. print_warning_msg(warn)
  1736. else:
  1737. adjust_directory_permissions(user)
  1738. print "Ambari Server 'upgrade' finished successfully"
  1739. #
  1740. # The Ambari Server status.
  1741. #
  1742. def status(args):
  1743. status, pid = is_server_runing()
  1744. if status:
  1745. print "Ambari Server running"
  1746. print "Found Ambari Server PID: '" + str(pid) + " at: " + PID_DIR + os.sep + PID_NAME
  1747. else:
  1748. print "Ambari Server not running. Stale PID File at: " + PID_DIR + os.sep + PID_NAME
  1749. #
  1750. # Prints an "info" messsage.
  1751. #
  1752. def print_info_msg(msg):
  1753. if VERBOSE:
  1754. print("INFO: " + msg)
  1755. #
  1756. # Prints an "error" messsage.
  1757. #
  1758. def print_error_msg(msg):
  1759. print("ERROR: " + msg)
  1760. #
  1761. # Prints a "warning" messsage.
  1762. #
  1763. def print_warning_msg(msg, bold=False):
  1764. if bold:
  1765. print(BOLD_ON + "WARNING: " + msg + BOLD_OFF)
  1766. else:
  1767. print("WARNING: " + msg)
  1768. #
  1769. # Gets the y/n input.
  1770. #
  1771. # return True if 'y' or False if 'n'
  1772. #
  1773. def get_YN_input(prompt,default):
  1774. yes = set(['yes','ye', 'y'])
  1775. no = set(['no','n'])
  1776. return get_choice_string_input(prompt,default,yes,no)
  1777. def get_choice_string_input(prompt,default,firstChoice,secondChoice):
  1778. if SILENT:
  1779. print(prompt)
  1780. return default
  1781. choice = raw_input(prompt).lower()
  1782. if choice in firstChoice:
  1783. return True
  1784. elif choice in secondChoice:
  1785. return False
  1786. elif choice is "": # Just enter pressed
  1787. return default
  1788. else:
  1789. print "input not recognized, please try again: "
  1790. return get_choice_string_input(prompt,default,firstChoice,secondChoice)
  1791. def get_validated_string_input(prompt, default, pattern, description, is_pass):
  1792. input =""
  1793. while not input:
  1794. if SILENT:
  1795. print (prompt)
  1796. input = default
  1797. elif is_pass:
  1798. input = getpass.getpass(prompt)
  1799. else:
  1800. input = raw_input(prompt)
  1801. if not input.strip():
  1802. input = default
  1803. break #done here and picking up default
  1804. else:
  1805. if not pattern==None and not re.search(pattern,input.strip()):
  1806. print description
  1807. input=""
  1808. return input
  1809. def get_value_from_properties(properties, key):
  1810. try:
  1811. value = properties[key]
  1812. except KeyError:
  1813. return ""
  1814. return value
  1815. def setup_ldap():
  1816. properties = get_ambari_properties()
  1817. # Setup secure key
  1818. (masterKey, isSecure, isPersisted) = setup_master_key(False)
  1819. LDAP_PRIMARY_URL_DEFAULT = get_value_from_properties(properties,
  1820. "authentication.ldap.primaryUrl")
  1821. LDAP_SECONDARY_URL_DEFAULT = get_value_from_properties(properties,
  1822. "authentication.ldap.secondaryUrl")
  1823. LDAP_BASE_DN_DEFAULT = get_value_from_properties(properties,
  1824. "authentication.ldap.baseDn")
  1825. LDAP_BIND_DEFAULT = get_value_from_properties(properties,
  1826. "authentication.ldap.bindAnonymously")
  1827. LDAP_USER_ATT_DEFAULT = get_value_from_properties(properties,
  1828. "authentication.ldap.usernameAttribute")
  1829. LDAP_GROUP_BASE_DEFAULT = get_value_from_properties(properties,
  1830. "authorization.ldap.groupBase")
  1831. LDAP_GROUP_OBJ_DEFAULT = get_value_from_properties(properties,
  1832. "authorization.ldap.groupObjectClass")
  1833. LDAP_GROUP_NAME_DEFAULT = get_value_from_properties(properties,
  1834. "authorization.ldap.groupNamingAttr")
  1835. LDAP_GROUP_MEM_DEFAULT = get_value_from_properties(properties,
  1836. "authorization.ldap.groupMembershipAttr")
  1837. LDAP_GROUP_MAP_DEFAULT = get_value_from_properties(properties,
  1838. "authorization.ldap.adminGroupMappingRules")
  1839. LDAP_GROUP_SEARCH_DEFAULT = get_value_from_properties(properties,
  1840. "authorization.ldap.groupSearchFilter")
  1841. LDAP_USER_ROLE_DEFAULT = get_value_from_properties(properties,
  1842. "authorization.userRoleName")
  1843. LDAP_ADMIN_ROLE_DEFAULT = get_value_from_properties(properties,
  1844. "authorization.adminRoleName")
  1845. LDAP_MGR_DN_DEFAULT = get_value_from_properties(properties,
  1846. "authentication.ldap.managerDn")
  1847. ldap_properties_map =\
  1848. {
  1849. "authentication.ldap.primaryUrl":(LDAP_PRIMARY_URL_DEFAULT, "Primary URL: "),\
  1850. "authentication.ldap.secondaryUrl":(LDAP_SECONDARY_URL_DEFAULT, "Secondary URL: "),\
  1851. "authentication.ldap.baseDn":(LDAP_BASE_DN_DEFAULT, "Base DN: "),\
  1852. "authentication.ldap.bindAnonymously":(LDAP_BIND_DEFAULT, "Bind anonymously? [true/alse]?: "),\
  1853. "authentication.ldap.usernameAttribute":(LDAP_USER_ATT_DEFAULT, "User name attribute uid): "),\
  1854. "authorization.ldap.groupBase":(LDAP_GROUP_BASE_DEFAULT, "Group base ou=groups,dc=ambari): "),\
  1855. "authorization.ldap.groupObjectClass":(LDAP_GROUP_OBJ_DEFAULT, "Group object class group): "),\
  1856. "authorization.ldap.groupNamingAttr":(LDAP_GROUP_NAME_DEFAULT, "Group name attribute cn): "),\
  1857. "authorization.ldap.groupMembershipAttr":(LDAP_GROUP_MEM_DEFAULT, "Group membership ttribute (member): "),\
  1858. "authorization.ldap.adminGroupMappingRules":(LDAP_GROUP_MAP_DEFAULT, "Admin group apping rules: "),\
  1859. "authorization.ldap.groupSearchFilter":(LDAP_GROUP_SEARCH_DEFAULT, "Group search filter: "),\
  1860. "authorization.userRoleName":(LDAP_USER_ROLE_DEFAULT, "User role name (user): "),\
  1861. "authorization.adminRoleName":(LDAP_ADMIN_ROLE_DEFAULT, "Admin role name (admin): "),
  1862. "authentication.ldap.managerDn":(LDAP_MGR_DN_DEFAULT, "Manager DN: ")
  1863. }
  1864. print "Input LDAP properties. Hit [Enter] to skip property."
  1865. ldap_property_value_map = {}
  1866. for key in ldap_properties_map.keys():
  1867. input = get_validated_string_input(ldap_properties_map[key][1],
  1868. ldap_properties_map[key][0], ".*", "", False)
  1869. if input is not None and input != "":
  1870. ldap_property_value_map[key] = input
  1871. ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] =\
  1872. configure_ldap_password(isSecure, masterKey)
  1873. # Persisting values
  1874. update_properties(ldap_property_value_map)
  1875. return 0
  1876. def reset_master_key():
  1877. setup_master_key(resetKey=True)
  1878. def setup_master_key(resetKey=False):
  1879. properties = get_ambari_properties()
  1880. passwordPattern = "^[a-zA-Z0-9_-]*$"
  1881. passwordDescr = "Invalid characters in password. Use only alphanumeric or "\
  1882. "_ or - characters"
  1883. passwordDefault = "hadooprocks!"
  1884. # check configuration for location of master key
  1885. keyLocation = get_master_key_location(properties)
  1886. persist = get_master_key_ispersisted(properties)
  1887. masterKeyFile = search_file(SECURITY_MASTER_KEY_FILENAME, keyLocation)
  1888. if persist is not None:
  1889. if persist and masterKeyFile is not None and not resetKey:
  1890. return None, True, True # setup is secure and key persisted
  1891. elif not persist and not resetKey:
  1892. masterKey = get_validated_string_input("Please provide master key " +\
  1893. "for unlocking credential store: ", "", ".*", "", False)
  1894. return masterKey, True, False # return master key for saving passwords
  1895. else:
  1896. if masterKeyFile is not None:
  1897. print_info_msg("Master key file exists. Updating property...")
  1898. update_properties({SECURITY_KEY_IS_PERSISTED : True})
  1899. return None, True, True
  1900. enable_ok = True
  1901. if not resetKey:
  1902. enable_ok = get_YN_input("Do you want encryption enabled for saving " +\
  1903. "passwords [y/n] (n)? ", False)
  1904. if not enable_ok:
  1905. return None, False, None
  1906. key = None
  1907. if masterKeyFile is None or resetKey:
  1908. key = get_validated_string_input(
  1909. "Please provide master key for the credential store: ",
  1910. passwordDefault, passwordPattern, passwordDescr, True)
  1911. if key != passwordDefault:
  1912. key = get_validated_string_input("Please re-enter master key: ",
  1913. passwordDefault, passwordPattern, passwordDescr, True)
  1914. persist = get_YN_input("Do you want to persist master key. If you choose "\
  1915. "not to persist, you need to provide the master "\
  1916. "key while starting the ambari server as a env "\
  1917. "variable named " + SECURITY_KEY_ENV_VAR_NAME +\
  1918. " or the start will prompt for the master key."
  1919. " Persist [y/n] (y)? ", True)
  1920. if persist:
  1921. save_master_key(key, keyLocation + os.sep + SECURITY_MASTER_KEY_FILENAME,
  1922. persist)
  1923. elif not persist and masterKeyFile is not None:
  1924. try:
  1925. os.remove(masterKeyFile)
  1926. print_warning_msg("Master key exists although security " +\
  1927. "is disabled. location: " + str(masterKeyFile))
  1928. except Exception, e:
  1929. print 'Could not remove master key file. %s' % e
  1930. if persist is not None:
  1931. update_properties({SECURITY_KEY_IS_PERSISTED : persist})
  1932. if resetKey:
  1933. # Blow up the credential store made with previous key
  1934. store_file = get_credential_store_location(properties)
  1935. if os.path.exists(store_file):
  1936. os.remove(store_file)
  1937. # Encrypt the passwords with new key
  1938. try:
  1939. db_password_alias = properties[JDBC_PASSWORD_PROPERTY]
  1940. ldap_password_alias = properties[LDAP_MGR_PASSWORD_PROPERTY]
  1941. except (KeyError), e:
  1942. print_warning_msg("KeyError: " + str(e))
  1943. if db_password_alias is not None and is_alias_string(db_password_alias):
  1944. configure_database_password(True, key, True)
  1945. if ldap_password_alias is not None and is_alias_string(ldap_password_alias):
  1946. configure_ldap_password(True)
  1947. return key, True, persist
  1948. def get_credential_store_location(properties):
  1949. store_loc = properties[SECURITY_KEYS_DIR]
  1950. if store_loc is None or store_loc == "":
  1951. store_loc = "/var/lib/ambari-server/keys/credentials.jceks"
  1952. else:
  1953. store_loc += os.sep + "credentials.jceks"
  1954. return store_loc
  1955. def get_master_key_location(properties):
  1956. keyLocation = properties[SECURITY_MASTER_KEY_LOCATION]
  1957. if keyLocation is None or keyLocation == "":
  1958. keyLocation = properties[SECURITY_KEYS_DIR]
  1959. return keyLocation
  1960. def get_master_key_ispersisted(properties):
  1961. try:
  1962. isPersisted = properties[SECURITY_KEY_IS_PERSISTED]
  1963. except (KeyError), e:
  1964. return None
  1965. if isPersisted is not None and isPersisted != "":
  1966. return isPersisted == 'true' or isPersisted == 'TRUE' or\
  1967. isPersisted == 'True'
  1968. return None
  1969. def is_alias_string(passwdStr):
  1970. regex = re.compile("\$\{alias=[\w\.]+\}")
  1971. # Match implies string at beginning of word
  1972. r = regex.match(passwdStr)
  1973. if r is not None:
  1974. return True
  1975. else:
  1976. return False
  1977. def get_alias_string(alias):
  1978. return "${alias=" + alias + "}"
  1979. def read_passwd_for_alias(alias, masterKey=""):
  1980. if alias:
  1981. jdk_path = find_jdk()
  1982. if jdk_path is None:
  1983. print_error_msg("No JDK found, please run the \"setup\" "
  1984. "command to install a JDK automatically or install any "
  1985. "JDK manually to " + JDK_INSTALL_DIR)
  1986. return 1
  1987. tempFileName = "ambari.passwd"
  1988. passwd = ""
  1989. tempDir = tempfile.gettempdir()
  1990. #create temporary file for writing
  1991. tempFilePath = tempDir + os.sep + tempFileName
  1992. file = open(tempFilePath, 'w+')
  1993. os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)
  1994. file.close()
  1995. if masterKey is None or masterKey == "":
  1996. masterKey = "None"
  1997. command = SECURITY_PROVIDER_GET_CMD.format(jdk_path,
  1998. get_conf_dir(), get_ambari_classpath(), alias, tempFilePath, masterKey)
  1999. (retcode, stdout, stderr) = run_os_command(command)
  2000. print_info_msg("Return code from credential provider get passwd: " +
  2001. str(retcode))
  2002. if retcode != 0:
  2003. print 'Unable to read password from store. alias = ' + alias
  2004. else:
  2005. passwd = open(tempFilePath, 'r').read()
  2006. # Remove temporary file
  2007. os.remove(tempFilePath)
  2008. return passwd
  2009. else:
  2010. print_error_msg("Alias is unreadable.")
  2011. def save_passwd_for_alias(alias, passwd, masterKey=""):
  2012. if alias and passwd:
  2013. jdk_path = find_jdk()
  2014. if jdk_path is None:
  2015. print_error_msg("No JDK found, please run the \"setup\" "
  2016. "command to install a JDK automatically or install any "
  2017. "JDK manually to " + JDK_INSTALL_DIR)
  2018. return 1
  2019. if masterKey is None or masterKey == "":
  2020. masterKey = "None"
  2021. command = SECURITY_PROVIDER_PUT_CMD.format(jdk_path, get_conf_dir(),
  2022. get_ambari_classpath(), alias, passwd, masterKey)
  2023. (retcode, stdout, stderr) = run_os_command(command)
  2024. print_info_msg("Return code from credential provider save passwd: " +
  2025. str(retcode))
  2026. return retcode
  2027. else:
  2028. print_error_msg("Alias or password is unreadable.")
  2029. def save_master_key(master_key, key_location, persist=True):
  2030. if master_key:
  2031. jdk_path = find_jdk()
  2032. if jdk_path is None:
  2033. print_error_msg("No JDK found, please run the \"setup\" "
  2034. "command to install a JDK automatically or install any "
  2035. "JDK manually to " + JDK_INSTALL_DIR)
  2036. return 1
  2037. command = SECURITY_PROVIDER_KEY_CMD.format(jdk_path,
  2038. get_ambari_classpath(), get_conf_dir(), master_key, key_location, persist)
  2039. (retcode, stdout, stderr) = run_os_command(command)
  2040. print_info_msg("Return code from credential provider save KEY: " +
  2041. str(retcode))
  2042. else:
  2043. print_error_msg("Master key cannot be None.")
  2044. def configure_ldap_password(isSecure=False, masterKey=None):
  2045. passwordDefault = ""
  2046. passwordPrompt = 'Enter LDAP Password: '
  2047. passwordPattern = ".*"
  2048. passwordDescr = "Invalid characters in password."
  2049. password = read_password(passwordDefault, passwordPattern, passwordPrompt,
  2050. passwordDescr)
  2051. if isSecure:
  2052. retCode = save_passwd_for_alias(LDAP_MGR_PASSWORD_ALIAS, password, masterKey)
  2053. if retCode != 0:
  2054. print 'Saving secure ldap password failed.'
  2055. return password
  2056. return get_alias_string(LDAP_MGR_PASSWORD_ALIAS)
  2057. return password
  2058. # Copy file to /tmp and save with file.# (largest # is latest file)
  2059. def backup_file_in_temp(filePath):
  2060. if filePath is not None:
  2061. tmpDir = tempfile.gettempdir()
  2062. back_up_file_count = len(glob.glob1(tmpDir, AMBARI_PROPERTIES_FILE + "*"))
  2063. try:
  2064. shutil.copyfile(filePath, tmpDir + os.sep +
  2065. AMBARI_PROPERTIES_FILE + "." + str(back_up_file_count + 1))
  2066. except (Exception), e:
  2067. print_error_msg('Could not backup file in temp "%s": %s' % (str(
  2068. back_up_file_count, e)))
  2069. return 0
  2070. # update properties in a section-less properties file
  2071. # Cannot use ConfigParser due to bugs in version 2.6
  2072. def update_properties(propertyMap):
  2073. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  2074. backup_file_in_temp(conf_file)
  2075. if propertyMap is not None and conf_file is not None:
  2076. properties = Properties()
  2077. try:
  2078. with open(conf_file, 'r') as file:
  2079. properties.load(file)
  2080. except (Exception), e:
  2081. print_error_msg ('Could not read "%s": %s' % (conf_file, e))
  2082. return -1
  2083. #for key in propertyMap.keys():
  2084. #properties[key] = propertyMap[key]
  2085. for key in propertyMap.keys():
  2086. properties.removeOldProp(key)
  2087. properties.process_pair(key, str(propertyMap[key]))
  2088. with open(conf_file, 'w') as file:
  2089. properties.store(file)
  2090. return 0
  2091. def setup_https(args):
  2092. if not SILENT:
  2093. properties = get_ambari_properties()
  2094. try:
  2095. security_server_keys_dir = properties.get_property(SSL_KEY_DIR)
  2096. client_api_ssl_port = DEFAULT_SSL_API_PORT if properties.get_property(SSL_API_PORT) in ("")\
  2097. else properties.get_property(SSL_API_PORT)
  2098. api_ssl = properties.get_property(SSL_API) in ['true']
  2099. cert_was_imported = False
  2100. if api_ssl:
  2101. if get_YN_input("Do you want to disable SSL (y/n) n? ", False):
  2102. properties.process_pair(SSL_API, "false")
  2103. else:
  2104. properties.process_pair(SSL_API_PORT, \
  2105. get_validated_string_input(\
  2106. "SSL port ["+str(client_api_ssl_port)+"] ? ",\
  2107. str(client_api_ssl_port),\
  2108. "^[0-9]{1,5}$", "Invalid port.", False))
  2109. if get_YN_input(\
  2110. "Do you want to import trusted certificate and private key (y/n) y? ",\
  2111. True):
  2112. import_cert_and_key_action(security_server_keys_dir, properties)
  2113. cert_was_imported = True
  2114. else:
  2115. if get_YN_input("Do you want to configure HTTPS (y/n) y? ", True):
  2116. properties.process_pair(SSL_API_PORT,\
  2117. get_validated_string_input("SSL port ["+str(client_api_ssl_port)+"] ? ",\
  2118. str(client_api_ssl_port), "^[0-9]{1,5}$", "Invalid port.", False))
  2119. if get_YN_input(\
  2120. "Do you want to import trusted certificate and private key (y/n) y? ",\
  2121. True):
  2122. import_cert_and_key_action(security_server_keys_dir, properties)
  2123. cert_was_imported = True
  2124. else:
  2125. return
  2126. conf_file = find_properties_file()
  2127. f = open(conf_file, 'w')
  2128. properties.store(f, "Changed by 'ambari-server setup-https' command")
  2129. if cert_was_imported:
  2130. print "NOTE: If cluster have been already created,"+\
  2131. " agent's keystors should be cleared manually!"
  2132. if is_server_runing():
  2133. print "To apply changes server should be restarted"+\
  2134. " by command: ambari-server restart|(stop|start)"
  2135. except (KeyError), e:
  2136. err = 'Property ' + str(e) + ' is not defined at ' + conf_file
  2137. raise FatalException(1, err)
  2138. else:
  2139. print "setup-https is not enabled in silent mode."
  2140. def is_server_runing():
  2141. if os.path.exists(PID_DIR + os.sep + PID_NAME):
  2142. f = open(PID_DIR + os.sep + PID_NAME, "r")
  2143. pid = int(f.readline())
  2144. f.close()
  2145. retcode, out, err = run_os_command("ps -p " + str(pid))
  2146. if retcode == 0:
  2147. return True, pid
  2148. else:
  2149. return False, None
  2150. else:
  2151. return False, None
  2152. def import_cert_and_key_action(security_server_keys_dir, properties):
  2153. if import_cert_and_key(security_server_keys_dir):
  2154. properties.process_pair(SSL_SERVER_CERT_NAME, SSL_CERT_FILE_NAME)
  2155. properties.process_pair(SSL_SERVER_KEY_NAME, SSL_KEY_FILE_NAME)
  2156. properties.process_pair(SSL_API, "true")
  2157. def import_cert_and_key(security_server_keys_dir):
  2158. import_cert_path = get_validated_filepath_input(\
  2159. "Please enter path to certificate: ",\
  2160. "Certificate not found")
  2161. import_key_path = get_validated_filepath_input(\
  2162. "Please enter path to key: ", "Key not found")
  2163. pem_password = get_validated_string_input("Please enter password for private key: ", "", None, None, True)
  2164. keystoreFilePath = os.path.join(security_server_keys_dir,\
  2165. SSL_KEYSTORE_FILE_NAME)
  2166. passFilePath = os.path.join(security_server_keys_dir,\
  2167. SSL_KEY_PASSWORD_FILE_NAME)
  2168. retcode, out, err = run_os_command(EXPRT_KSTR_CMD.format(import_cert_path,\
  2169. import_key_path, pem_password, keystoreFilePath))
  2170. if retcode == 0:
  2171. print 'Successfully imported trusted cerificate and private key'
  2172. set_file_permissions(keystoreFilePath, "660", read_ambari_user(), "root")
  2173. with open(passFilePath, 'w+') as passFile:
  2174. passFile.write(pem_password)
  2175. pass
  2176. set_file_permissions(passFilePath, "660", read_ambari_user(), "root")
  2177. import_file_to_keystore(import_cert_path, os.path.join(\
  2178. security_server_keys_dir, SSL_CERT_FILE_NAME))
  2179. import_file_to_keystore(import_key_path, os.path.join(\
  2180. security_server_keys_dir, SSL_KEY_FILE_NAME))
  2181. return True
  2182. else:
  2183. print 'Could not import trusted cerificate and private key:'
  2184. print err
  2185. return False
  2186. def import_file_to_keystore(source, destination):
  2187. shutil.copy(source, destination)
  2188. set_file_permissions(destination, "660", read_ambari_user(), "root")
  2189. def get_validated_filepath_input(prompt, description, default=None):
  2190. input = False
  2191. while not input:
  2192. if SILENT:
  2193. print (prompt)
  2194. return default
  2195. else:
  2196. input = raw_input(prompt)
  2197. if not input==None:
  2198. input = input.strip()
  2199. if not input==None and not ""==input and os.path.exists(input):
  2200. return input
  2201. else:
  2202. print description
  2203. input=False
  2204. #
  2205. # Main.
  2206. #
  2207. def main():
  2208. parser = optparse.OptionParser(usage="usage: %prog [options] action [stack_id]",)
  2209. parser.add_option('-f', '--init-script-file',
  2210. default='/var/lib/ambari-server/'
  2211. 'resources/Ambari-DDL-Postgres-CREATE.sql',
  2212. help="File with setup script")
  2213. parser.add_option('-r', '--drop-script-file', default="/var/lib/"
  2214. "ambari-server/resources/"
  2215. "Ambari-DDL-Postgres-DROP.sql",
  2216. help="File with drop script")
  2217. parser.add_option('-u', '--upgrade-script-file', default="/var/lib/"
  2218. "ambari-server/resources/upgrade/ddl/"
  2219. "Ambari-DDL-Postgres-UPGRADE-1.3.0.sql",
  2220. help="File with upgrade script")
  2221. parser.add_option('-t', '--upgrade-stack-script-file', default="/var/lib/"
  2222. "ambari-server/resources/upgrade/dml/"
  2223. "Ambari-DML-Postgres-UPGRADE_STACK.sql",
  2224. help="File with stack upgrade script")
  2225. parser.add_option('-j', '--java-home', default=None,
  2226. help="Use specified java_home. Must be valid on all hosts")
  2227. parser.add_option('-c', '--jce-policy', default=None,
  2228. help="Use specified jce_policy. Must be valid on all hosts", dest="jce_policy")
  2229. parser.add_option("-v", "--verbose",
  2230. action="store_true", dest="verbose", default=False,
  2231. help="Print verbose status messages")
  2232. parser.add_option("-s", "--silent",
  2233. action="store_true", dest="silent", default=False,
  2234. help="Silently accepts default prompt values")
  2235. parser.add_option('-g', '--debug', action="store_true", dest='debug', default=False,
  2236. help="Start ambari-server in debug mode")
  2237. parser.add_option('--database', default=None, help ="Database to use postgres|oracle", dest="database")
  2238. parser.add_option('--databasehost', default=None, help="Hostname of database server", dest="database_host")
  2239. parser.add_option('--databaseport', default=None, help="Database port", dest="database_port")
  2240. parser.add_option('--databasename', default=None, help="Database/Schema/Service name", dest="database_name")
  2241. parser.add_option('--databaseusername', default=None, help="Database user login", dest="database_username")
  2242. parser.add_option('--databasepassword', default=None, help="Database user password", dest="database_password")
  2243. (options, args) = parser.parse_args()
  2244. # set verbose
  2245. global VERBOSE
  2246. VERBOSE = options.verbose
  2247. # set silent
  2248. global SILENT
  2249. SILENT = options.silent
  2250. # debug mode
  2251. global SERVER_DEBUG_MODE
  2252. SERVER_DEBUG_MODE = options.debug
  2253. global DATABASE_INDEX
  2254. global PROMPT_DATABASE_OPTIONS
  2255. #perform checks
  2256. options.warnings = []
  2257. if options.database is None \
  2258. and options.database_host is None \
  2259. and options.database_port is None \
  2260. and options.database_name is None \
  2261. and options.database_username is None \
  2262. and options.database_password is None:
  2263. PROMPT_DATABASE_OPTIONS = True
  2264. elif not (options.database is not None
  2265. and options.database_host is not None
  2266. and options.database_port is not None
  2267. and options.database_name is not None
  2268. and options.database_username is not None
  2269. and options.database_password is not None):
  2270. parser.error('All database options should be set. Please see help for the options.')
  2271. #correct database
  2272. if options.database is not None and options.database not in DATABASE_NAMES:
  2273. parser.print_help()
  2274. print "Unsupported Database " + options.database
  2275. elif options.database is not None:
  2276. options.database = options.database.lower()
  2277. DATABASE_INDEX = DATABASE_NAMES.index(options.database)
  2278. #correct port
  2279. if options.database_port is not None:
  2280. correct=False
  2281. try:
  2282. port = int(options.database_port)
  2283. if 65536 > port > 0:
  2284. correct = True
  2285. except ValueError:
  2286. pass
  2287. if not correct:
  2288. parser.print_help()
  2289. parser.error("Incorrect database port " + options.database_port)
  2290. if options.database is not None and options.database == "postgres":
  2291. print "WARNING: HostName for postgres server " + options.database_host + \
  2292. " will be ignored: using localhost."
  2293. options.database_host = "localhost"
  2294. if len(args) == 0:
  2295. print parser.print_help()
  2296. parser.error("No action entered")
  2297. action = args[0]
  2298. if action == UPGRADE_STACK_ACTION:
  2299. args_number_required = 2
  2300. else:
  2301. args_number_required = 1
  2302. if len(args) < args_number_required:
  2303. print parser.print_help()
  2304. parser.error("Invalid number of arguments. Entered: " + str(len(args)) + ", required: " + str(args_number_required))
  2305. try:
  2306. if action == SETUP_ACTION:
  2307. setup(options)
  2308. elif action == START_ACTION:
  2309. start(options)
  2310. elif action == STOP_ACTION:
  2311. stop(options)
  2312. elif action == RESET_ACTION:
  2313. reset(options)
  2314. elif action == STATUS_ACTION:
  2315. status(options)
  2316. elif action == UPGRADE_ACTION:
  2317. upgrade(options)
  2318. elif action == UPGRADE_STACK_ACTION:
  2319. stack_id = args[1]
  2320. upgrade_stack(options, stack_id)
  2321. elif action == LDAP_SETUP_ACTION:
  2322. setup_ldap()
  2323. elif action == RESET_MASTER_KEY_ACTION:
  2324. reset_master_key()
  2325. elif action == UPDATE_METAINFO_ACTION:
  2326. update_metainfo(options)
  2327. elif action == SETUP_HTTPS_ACTION:
  2328. setup_https(options)
  2329. else:
  2330. parser.error("Invalid action")
  2331. except FatalException as e:
  2332. if e.reason is not None:
  2333. print_error_msg("Exiting with exit code {0}. Reason: {1}".format(e.code, e.reason))
  2334. sys.exit(e.code)
  2335. # A Python replacement for java.util.Properties
  2336. # Based on http://code.activestate.com/recipes
  2337. # /496795-a-python-replacement-for-javautilproperties/
  2338. class Properties(object):
  2339. def __init__(self, props=None):
  2340. self._props = {}
  2341. self._origprops = {}
  2342. self._keymap = {}
  2343. self.othercharre = re.compile(r'(?<!\\)(\s*\=)|(?<!\\)(\s*\:)')
  2344. self.othercharre2 = re.compile(r'(\s*\=)|(\s*\:)')
  2345. self.bspacere = re.compile(r'\\(?!\s$)')
  2346. def __parse(self, lines):
  2347. lineno = 0
  2348. i = iter(lines)
  2349. for line in i:
  2350. lineno += 1
  2351. line = line.strip()
  2352. if not line: continue
  2353. if line[0] == '#': continue
  2354. escaped = False
  2355. sepidx = -1
  2356. flag = 0
  2357. m = self.othercharre.search(line)
  2358. if m:
  2359. first, last = m.span()
  2360. start, end = 0, first
  2361. flag = 1
  2362. wspacere = re.compile(r'(?<![\\\=\:])(\s)')
  2363. else:
  2364. if self.othercharre2.search(line):
  2365. wspacere = re.compile(r'(?<![\\])(\s)')
  2366. start, end = 0, len(line)
  2367. m2 = wspacere.search(line, start, end)
  2368. if m2:
  2369. first, last = m2.span()
  2370. sepidx = first
  2371. elif m:
  2372. first, last = m.span()
  2373. sepidx = last - 1
  2374. while line[-1] == '\\':
  2375. nextline = i.next()
  2376. nextline = nextline.strip()
  2377. lineno += 1
  2378. line = line[:-1] + nextline
  2379. if sepidx != -1:
  2380. key, value = line[:sepidx], line[sepidx + 1:]
  2381. else:
  2382. key, value = line, ''
  2383. self.process_pair(key, value)
  2384. def process_pair(self, key, value):
  2385. oldkey = key
  2386. oldvalue = value
  2387. keyparts = self.bspacere.split(key)
  2388. strippable = False
  2389. lastpart = keyparts[-1]
  2390. if lastpart.find('\\ ') != -1:
  2391. keyparts[-1] = lastpart.replace('\\', '')
  2392. elif lastpart and lastpart[-1] == ' ':
  2393. strippable = True
  2394. key = ''.join(keyparts)
  2395. if strippable:
  2396. key = key.strip()
  2397. oldkey = oldkey.strip()
  2398. oldvalue = self.unescape(oldvalue)
  2399. value = self.unescape(value)
  2400. self._props[key] = None if value is None else value.strip()
  2401. if self._keymap.has_key(key):
  2402. oldkey = self._keymap.get(key)
  2403. self._origprops[oldkey] = None if oldvalue is None else oldvalue.strip()
  2404. else:
  2405. self._origprops[oldkey] = None if oldvalue is None else oldvalue.strip()
  2406. self._keymap[key] = oldkey
  2407. def unescape(self, value):
  2408. newvalue = value
  2409. if not value is None:
  2410. newvalue = value.replace('\:', ':')
  2411. newvalue = newvalue.replace('\=', '=')
  2412. return newvalue
  2413. def removeOldProp(self, key):
  2414. if self._origprops.has_key(key):
  2415. del self._origprops[key]
  2416. pass
  2417. def load(self, stream):
  2418. if type(stream) is not file:
  2419. raise TypeError, 'Argument should be a file object!'
  2420. if stream.mode != 'r':
  2421. raise ValueError, 'Stream should be opened in read-only mode!'
  2422. try:
  2423. self.fileName = os.path.abspath(stream.name)
  2424. lines = stream.readlines()
  2425. self.__parse(lines)
  2426. except IOError, e:
  2427. raise
  2428. def get_property(self, key):
  2429. return self._props.get(key, '')
  2430. def propertyNames(self):
  2431. return self._props.keys()
  2432. def getPropertyDict(self):
  2433. return self._props
  2434. def __getitem__(self, name):
  2435. return self.get_property(name)
  2436. def __getattr__(self, name):
  2437. try:
  2438. return self.__dict__[name]
  2439. except KeyError:
  2440. if hasattr(self._props, name):
  2441. return getattr(self._props, name)
  2442. def store(self, out, header=""):
  2443. """ Write the properties list to the stream 'out' along
  2444. with the optional 'header' """
  2445. if out.mode[0] != 'w':
  2446. raise ValueError,'Steam should be opened in write mode!'
  2447. try:
  2448. out.write(''.join(('#', ASF_LICENSE_HEADER, '\n')))
  2449. out.write(''.join(('#',header,'\n')))
  2450. # Write timestamp
  2451. tstamp = time.strftime('%a %b %d %H:%M:%S %Z %Y', time.localtime())
  2452. out.write(''.join(('#',tstamp,'\n')))
  2453. # Write properties from the pristine dictionary
  2454. for prop, val in self._origprops.items():
  2455. if val is not None:
  2456. out.write(''.join((prop,'=',val,'\n')))
  2457. out.close()
  2458. except IOError, e:
  2459. raise
  2460. if __name__ == "__main__":
  2461. main()