ambari-server.py 100 KB

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