ambari-server.py 157 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481
  1. #!/usr/bin/env python
  2. '''
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. '''
  17. import optparse
  18. import shlex
  19. import sys
  20. import os
  21. import signal
  22. import subprocess
  23. import re
  24. import string
  25. import glob
  26. import platform
  27. import shutil
  28. import stat
  29. import fileinput
  30. import urllib2
  31. import time
  32. import getpass
  33. import socket
  34. import datetime
  35. import tempfile
  36. import random
  37. import pwd
  38. # debug settings
  39. VERBOSE = False
  40. SILENT = False
  41. SERVER_START_DEBUG = False
  42. # OS info
  43. OS, OS_VERSION, _ = platform.linux_distribution()
  44. OS = OS.lower().strip()
  45. OS_UBUNTU = 'ubuntu'
  46. OS_FEDORA = 'fedora'
  47. OS_OPENSUSE = 'opensuse'
  48. # action commands
  49. SETUP_ACTION = "setup"
  50. START_ACTION = "start"
  51. STOP_ACTION = "stop"
  52. RESET_ACTION = "reset"
  53. UPGRADE_ACTION = "upgrade"
  54. UPGRADE_STACK_ACTION = "upgradestack"
  55. STATUS_ACTION = "status"
  56. SETUP_HTTPS_ACTION = "setup-https"
  57. LDAP_SETUP_ACTION = "setup-ldap"
  58. SETUP_GANGLIA_HTTPS_ACTION = "setup-ganglia-https"
  59. SETUP_NAGIOS_HTTPS_ACTION = "setup-nagios-https"
  60. ENCRYPT_PASSWORDS_ACTION = "encrypt-passwords"
  61. SETUP_SECURITY_ACTION = "setup-security"
  62. ACTION_REQUIRE_RESTART = [RESET_ACTION, UPGRADE_ACTION, UPGRADE_STACK_ACTION,
  63. SETUP_SECURITY_ACTION, LDAP_SETUP_ACTION]
  64. # selinux commands
  65. GET_SE_LINUX_ST_CMD = "/usr/sbin/sestatus"
  66. SE_SETENFORCE_CMD = "setenforce 0"
  67. SE_STATUS_DISABLED = "disabled"
  68. SE_STATUS_ENABLED = "enabled"
  69. SE_MODE_ENFORCING = "enforcing"
  70. SE_MODE_PERMISSIVE = "permissive"
  71. # server commands
  72. ambari_provider_module_option = ""
  73. ambari_provider_module = os.environ.get('AMBARI_PROVIDER_MODULE')
  74. # Non-root user setup commands
  75. NR_USER_PROPERTY = "ambari-server.user"
  76. NR_USER_COMMENT = "Ambari user"
  77. NR_GET_OWNER_CMD = 'stat -c "%U" {0}'
  78. NR_USERADD_CMD = 'useradd -M --comment "{1}" ' \
  79. '--shell /sbin/nologin -d /var/lib/ambari-server/keys/ {0}'
  80. NR_SET_USER_COMMENT_CMD = 'usermod -c "{0}" {1}'
  81. NR_CHMOD_CMD = 'chmod {0} {1} {2}'
  82. NR_CHOWN_CMD = 'chown {0} {1} {2}'
  83. RECURSIVE_RM_CMD = 'rm -rf {0}'
  84. SSL_PASSWORD_FILE = "pass.txt"
  85. SSL_PASSIN_FILE = "passin.txt"
  86. # openssl command
  87. VALIDATE_KEYSTORE_CMD = "openssl pkcs12 -info -in '{0}' -password file:'{1}' -passout file:'{2}'"
  88. EXPRT_KSTR_CMD = "openssl pkcs12 -export -in '{0}' -inkey '{1}' -certfile '{0}' -out '{4}' -password file:'{2}' -passin file:'{3}'"
  89. CHANGE_KEY_PWD_CND = 'openssl rsa -in {0} -des3 -out {0}.secured -passout pass:{1}'
  90. GET_CRT_INFO_CMD = 'openssl x509 -dates -subject -in {0}'
  91. #keytool commands
  92. KEYTOOL_IMPORT_CERT_CMD="{0}" + os.sep + "bin" + os.sep + "keytool -import -alias '{1}' -storetype '{2}' -file '{3}' -storepass '{4}' -noprompt"
  93. KEYTOOL_DELETE_CERT_CMD="{0}" + os.sep + "bin" + os.sep + "keytool -delete -alias '{1}' -storepass '{2}' -noprompt"
  94. KEYTOOL_KEYSTORE=" -keystore '{0}'"
  95. # constants
  96. STACK_NAME_VER_SEP = "-"
  97. JAVA_SHARE_PATH="/usr/share/java"
  98. SERVER_OUT_FILE="/var/log/ambari-server/ambari-server.out"
  99. SERVER_LOG_FILE="/var/log/ambari-server/ambari-server.log"
  100. BLIND_PASSWORD="*****"
  101. # terminal styles
  102. BOLD_ON='\033[1m'
  103. BOLD_OFF='\033[0m'
  104. #Common messages
  105. PRESS_ENTER_MSG="Press <enter> to continue."
  106. #Common setup or upgrade message
  107. SETUP_OR_UPGRADE_MSG = "- If this is a new setup, then run the \"ambari-server setup\" command to create the user\n" \
  108. "- If this is an upgrade of an existing setup, run the \"ambari-server upgrade\" command.\n" \
  109. "Refer to the Ambari documentation for more information on setup and upgrade."
  110. #SSL certificate metainfo
  111. COMMON_NAME_ATTR='CN'
  112. NOT_BEFORE_ATTR='notBefore'
  113. NOT_AFTER_ATTR='notAfter'
  114. if ambari_provider_module is not None:
  115. ambari_provider_module_option = "-Dprovider.module.class=" +\
  116. ambari_provider_module + " "
  117. SERVER_START_CMD="{0}" + os.sep + "bin" + os.sep +\
  118. "java -server -XX:NewRatio=3 "\
  119. "-XX:+UseConcMarkSweepGC " +\
  120. "-XX:-UseGCOverheadLimit -XX:CMSInitiatingOccupancyFraction=60 " +\
  121. ambari_provider_module_option +\
  122. os.getenv('AMBARI_JVM_ARGS','-Xms512m -Xmx2048m') +\
  123. " -cp {1}"+ os.pathsep + "{2}" +\
  124. " org.apache.ambari.server.controller.AmbariServer "\
  125. ">" + SERVER_OUT_FILE + " 2>&1 &" \
  126. " echo $! > {3}" # Writing pidfile
  127. SERVER_START_CMD_DEBUG="{0}" + os.sep + "bin" + os.sep +\
  128. "java -server -XX:NewRatio=2 -XX:+UseConcMarkSweepGC " +\
  129. ambari_provider_module_option +\
  130. os.getenv('AMBARI_JVM_ARGS','-Xms512m -Xmx2048m') +\
  131. " -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,"\
  132. "server=y,suspend=n -cp {1}"+ os.pathsep + "{2}" +\
  133. " org.apache.ambari.server.controller.AmbariServer &" \
  134. " echo $! > {3}" # Writing pidfile
  135. SECURITY_PROVIDER_GET_CMD="{0}" + os.sep + "bin" + os.sep + "java -cp {1}" +\
  136. os.pathsep + "{2} " +\
  137. "org.apache.ambari.server.security.encryption" +\
  138. ".CredentialProvider GET {3} {4} {5} " +\
  139. "> " + SERVER_OUT_FILE + " 2>&1"
  140. SECURITY_PROVIDER_PUT_CMD="{0}" + os.sep + "bin" + os.sep + "java -cp {1}" +\
  141. os.pathsep + "{2} " +\
  142. "org.apache.ambari.server.security.encryption" +\
  143. ".CredentialProvider PUT {3} {4} {5} " +\
  144. "> " + SERVER_OUT_FILE + " 2>&1"
  145. SECURITY_PROVIDER_KEY_CMD="{0}" + os.sep + "bin" + os.sep + "java -cp {1}" +\
  146. os.pathsep + "{2} " +\
  147. "org.apache.ambari.server.security.encryption" +\
  148. ".MasterKeyServiceImpl {3} {4} {5} " +\
  149. "> " + SERVER_OUT_FILE + " 2>&1"
  150. SECURITY_KEYS_DIR = "security.server.keys_dir"
  151. SECURITY_MASTER_KEY_LOCATION = "security.master.key.location"
  152. SECURITY_KEY_IS_PERSISTED = "security.master.key.ispersisted"
  153. SECURITY_KEY_ENV_VAR_NAME = "AMBARI_SECURITY_MASTER_KEY"
  154. SECURITY_MASTER_KEY_FILENAME = "master"
  155. SECURITY_IS_ENCRYPTION_ENABLED = "security.passwords.encryption.enabled"
  156. SECURITY_KERBEROS_JASS_FILENAME = "krb5JAASLogin.conf"
  157. SSL_KEY_DIR = 'security.server.keys_dir'
  158. SSL_API_PORT = 'client.api.ssl.port'
  159. SSL_API = 'api.ssl'
  160. SSL_SERVER_CERT_NAME = 'client.api.ssl.cert_name'
  161. SSL_SERVER_KEY_NAME = 'client.api.ssl.key_name'
  162. SSL_CERT_FILE_NAME = "https.crt"
  163. SSL_KEY_FILE_NAME = "https.key"
  164. SSL_KEYSTORE_FILE_NAME = "https.keystore.p12"
  165. SSL_KEY_PASSWORD_FILE_NAME = "https.pass.txt"
  166. SSL_KEY_PASSWORD_LENGTH = 50
  167. DEFAULT_SSL_API_PORT = 8443
  168. SSL_DATE_FORMAT = '%b %d %H:%M:%S %Y GMT'
  169. GANGLIA_HTTPS = 'ganglia.https'
  170. NAGIOS_HTTPS = 'nagios.https'
  171. JDBC_RCA_PASSWORD_ALIAS = "ambari.db.password"
  172. CLIENT_SECURITY_KEY = "client.security"
  173. LDAP_MGR_PASSWORD_ALIAS = "ambari.ldap.manager.password"
  174. LDAP_MGR_PASSWORD_PROPERTY = "authentication.ldap.managerPassword"
  175. LDAP_MGR_USERNAME_PROPERTY = "authentication.ldap.managerDn"
  176. SSL_TRUSTSTORE_PASSWORD_ALIAS="ambari.ssl.trustStore.password"
  177. SSL_TRUSTSTORE_PATH_PROPERTY = "ssl.trustStore.path"
  178. SSL_TRUSTSTORE_PASSWORD_PROPERTY = "ssl.trustStore.password"
  179. SSL_TRUSTSTORE_TYPE_PROPERTY = "ssl.trustStore.type"
  180. AMBARI_CONF_VAR="AMBARI_CONF_DIR"
  181. AMBARI_SERVER_LIB="AMBARI_SERVER_LIB"
  182. JAVA_HOME="JAVA_HOME"
  183. PID_DIR="/var/run/ambari-server"
  184. BOOTSTRAP_DIR_PROPERTY="bootstrap.dir"
  185. PID_NAME="ambari-server.pid"
  186. AMBARI_PROPERTIES_FILE="ambari.properties"
  187. AMBARI_PROPERTIES_RPMSAVE_FILE="ambari.properties.rpmsave"
  188. RESOURCES_DIR_PROPERTY="resources.dir"
  189. SETUP_DB_CONNECT_TIMEOUT = 5
  190. SETUP_DB_CONNECT_ATTEMPTS = 3
  191. SETUP_DB_CMD = ['su', '-', 'postgres',
  192. '--command=psql -f {0} -v username=\'"{1}"\' -v password="\'{2}\'" -v dbname="{3}"']
  193. UPGRADE_STACK_CMD = ['su', 'postgres',
  194. '--command=psql -f {0} -v stack_name="\'{1}\'" -v stack_version="\'{2}\'" -v dbname="{3}"']
  195. PG_ERROR_BLOCKED = "is being accessed by other users"
  196. PG_STATUS_RUNNING = "running"
  197. PG_DEFAULT_PASSWORD = "bigdata"
  198. SERVICE_CMD = "/sbin/service"
  199. PG_SERVICE_NAME = "postgresql"
  200. PG_HBA_DIR = "/var/lib/pgsql/data"
  201. PG_ST_CMD = "%s %s status" % (SERVICE_CMD, PG_SERVICE_NAME)
  202. if os.path.isfile("/usr/bin/postgresql-setup"):
  203. PG_INITDB_CMD = "/usr/bin/postgresql-setup initdb"
  204. else:
  205. PG_INITDB_CMD = "%s %s initdb" % (SERVICE_CMD, PG_SERVICE_NAME)
  206. PG_START_CMD = "%s %s start" % (SERVICE_CMD, PG_SERVICE_NAME)
  207. PG_RESTART_CMD = "%s %s restart" % (SERVICE_CMD, PG_SERVICE_NAME)
  208. PG_HBA_RELOAD_CMD = "%s %s reload" % (SERVICE_CMD, PG_SERVICE_NAME)
  209. PG_HBA_CONF_FILE = os.path.join(PG_HBA_DIR, "pg_hba.conf")
  210. PG_HBA_CONF_FILE_BACKUP = os.path.join(PG_HBA_DIR, "pg_hba_bak.conf.old")
  211. POSTGRESQL_CONF_FILE = os.path.join(PG_HBA_DIR, "postgresql.conf")
  212. JDBC_DATABASE_PROPERTY = "server.jdbc.database"
  213. JDBC_HOSTNAME_PROPERTY = "server.jdbc.hostname"
  214. JDBC_PORT_PROPERTY = "server.jdbc.port"
  215. JDBC_SCHEMA_PROPERTY = "server.jdbc.schema"
  216. JDBC_USER_NAME_PROPERTY = "server.jdbc.user.name"
  217. JDBC_PASSWORD_PROPERTY = "server.jdbc.user.passwd"
  218. JDBC_PASSWORD_FILENAME = "password.dat"
  219. JDBC_RCA_PASSWORD_FILENAME = "rca_password.dat"
  220. CLIENT_API_PORT_PROPERTY = "client.api.port"
  221. CLIENT_API_PORT = "8080"
  222. SRVR_TWO_WAY_SSL_PORT_PROPERTY = "security.server.two_way_ssl.port"
  223. SRVR_TWO_WAY_SSL_PORT = "8441"
  224. SRVR_ONE_WAY_SSL_PORT_PROPERTY = "security.server.one_way_ssl.port"
  225. SRVR_ONE_WAY_SSL_PORT = "8440"
  226. PERSISTENCE_TYPE_PROPERTY = "server.persistence.type"
  227. JDBC_DRIVER_PROPERTY = "server.jdbc.driver"
  228. JDBC_URL_PROPERTY = "server.jdbc.url"
  229. JDBC_RCA_DATABASE_PROPERTY = "server.jdbc.database"
  230. JDBC_RCA_HOSTNAME_PROPERTY = "server.jdbc.hostname"
  231. JDBC_RCA_PORT_PROPERTY = "server.jdbc.port"
  232. JDBC_RCA_SCHEMA_PROPERTY = "server.jdbc.schema"
  233. JDBC_RCA_DRIVER_PROPERTY = "server.jdbc.rca.driver"
  234. JDBC_RCA_URL_PROPERTY = "server.jdbc.rca.url"
  235. JDBC_RCA_USER_NAME_PROPERTY = "server.jdbc.rca.user.name"
  236. JDBC_RCA_PASSWORD_FILE_PROPERTY = "server.jdbc.rca.user.passwd"
  237. CHECK_COMMAND_EXIST_CMD = "type {0}"
  238. DATABASE_INDEX = 0
  239. PROMPT_DATABASE_OPTIONS = False
  240. USERNAME_PATTERN = "^[a-zA-Z_][a-zA-Z0-9_\-]*$"
  241. PASSWORD_PATTERN = "^[a-zA-Z0-9_-]*$"
  242. DATABASE_NAMES =["postgres", "oracle", "mysql"]
  243. DATABASE_STORAGE_NAMES =["Database","Service","Database"]
  244. DATABASE_PORTS =["5432", "1521", "3306"]
  245. DATABASE_DRIVER_NAMES = ["org.postgresql.Driver", "oracle.jdbc.driver.OracleDriver", "com.mysql.jdbc.Driver"]
  246. DATABASE_CONNECTION_STRINGS = [
  247. "jdbc:postgresql://{0}:{1}/{2}",
  248. "jdbc:oracle:thin:@{0}:{1}/{2}",
  249. "jdbc:mysql://{0}:{1}/{2}"]
  250. DATABASE_CONNECTION_STRINGS_ALT = [
  251. "jdbc:postgresql://{0}:{1}/{2}",
  252. "jdbc:oracle:thin:@{0}:{1}:{2}",
  253. "jdbc:mysql://{0}:{1}/{2}"]
  254. ORACLE_SID_PATTERN = "jdbc:oracle:thin:@.+:.+/.+"
  255. ORACLE_SNAME_PATTERN = "jdbc:oracle:thin:@.+:.+:.+"
  256. DATABASE_CLI_TOOLS = [["psql"], ["sqlplus", "sqlplus64"], ["mysql"]]
  257. DATABASE_CLI_TOOLS_DESC = ["psql", "sqlplus", "mysql"]
  258. DATABASE_CLI_TOOLS_USAGE = ['su -postgres --command=psql -f {0} -v username=\'"{1}"\' -v password="\'{2}\'"',
  259. 'sqlplus {1}/{2} < {0} ',
  260. 'mysql --user={1} --password={2} {3}<{0}']
  261. MYSQL_INIT_SCRIPT = '/var/lib/ambari-server/resources/Ambari-DDL-MySQL-CREATE.sql'
  262. DATABASE_INIT_SCRIPTS = ['/var/lib/ambari-server/resources/Ambari-DDL-Postgres-REMOTE-CREATE.sql',
  263. '/var/lib/ambari-server/resources/Ambari-DDL-Oracle-CREATE.sql',
  264. MYSQL_INIT_SCRIPT]
  265. DATABASE_DROP_SCRIPTS = ['/var/lib/ambari-server/resources/Ambari-DDL-Postgres-REMOTE-DROP.sql',
  266. '/var/lib/ambari-server/resources/Ambari-DDL-Oracle-DROP.sql',
  267. '/var/lib/ambari-server/resources/Ambari-DDL-MySQL-DROP.sql']
  268. DATABASE_UPGRADE_SCRIPTS = ['/var/lib/ambari-server/resources/upgrade/ddl/Ambari-DDL-Postgres-REMOTE-UPGRADE.sql',
  269. '/var/lib/ambari-server/resources/upgrade/ddl/Ambari-DDL-Oracle-UPGRADE.sql',
  270. '/var/lib/ambari-server/resources/upgrade/ddl/Ambari-DDL-MySQL-UPGRADE.sql']
  271. DATABASE_STACK_UPGRADE_SCRIPTS = ['/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-Postgres-REMOTE-UPGRADE_STACK.sql',
  272. '/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-Oracle-UPGRADE_STACK.sql',
  273. '/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-MySQL-UPGRADE_STACK.sql']
  274. JDBC_PROPERTIES_PREFIX = "server.jdbc.properties."
  275. DATABASE_JDBC_PROPERTIES = [
  276. [ ],
  277. [
  278. ["oracle.net.CONNECT_TIMEOUT", "2000"], # socket level timeout
  279. ["oracle.net.READ_TIMEOUT", "2000"], # socket level timeout
  280. ["oracle.jdbc.ReadTimeout", "8000"] # query fetch timeout
  281. ],
  282. [ ]
  283. ]
  284. 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])$"
  285. 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])$"
  286. REGEX_HOSTNAME_PORT = "^(.*:[0-9]{1,5}$)"
  287. REGEX_TRUE_FALSE = "^(true|false)?$"
  288. REGEX_ANYTHING = ".*"
  289. POSTGRES_EXEC_ARGS = "-h {0} -p {1} -d {2} -U {3} -f {4} -v username='\"{3}\"'"
  290. ORACLE_EXEC_ARGS = "-S -L '{0}/{1}@(description=(address=(protocol=TCP)(host={2})(port={3}))(connect_data=({6}={4})))' @{5} {0}"
  291. MYSQL_EXEC_ARGS_WITH_USER_VARS = "--host={0} --port={1} --user={2} --password={3} {4} " \
  292. "-e\"set @schema=\'{4}\'; set @username=\'{2}\'; source {5};\""
  293. MYSQL_EXEC_ARGS_WO_USER_VARS = "--force --host={0} --port={1} --user={2} --password={3} --database={4} < {5} 2> /dev/null"
  294. MYSQL_UPGRADE_STACK_ARGS = "--host={0} --port={1} --user={2} --password={3} --database={4} " \
  295. "-e\"set @stackName=\'{6}\'; set @stackVersion=\'{7}\'; source {5};\""
  296. ORACLE_UPGRADE_STACK_ARGS = "-S -L '{0}/{1}@(description=(address=(protocol=TCP)(host={2})(port={3}))(connect_data=({6}={4})))' @{5} {7} {8}"
  297. JDBC_PATTERNS = {"oracle":"*ojdbc*.jar", "mysql":"*mysql*.jar"}
  298. DATABASE_FULL_NAMES = {"oracle":"Oracle", "mysql":"MySQL", "postgres":"PostgreSQL"}
  299. ORACLE_DB_ID_TYPES = ["Service Name", "SID"]
  300. # jdk commands
  301. JDK_NAMES = ["jdk-7u45-linux-x64.tar.gz" , "jdk-6u31-linux-x64.bin"]
  302. JDK_URL_PROPERTIES = ["jdk1.7.url", "jdk1.6.url"]
  303. JCE_URL_PROPERTIES = ["jce_policy1.7.url", "jce_policy1.6.url"]
  304. JDK_INDEX = 0
  305. JDK_VERSION_REs = ["(jdk.*)/jre" , "Creating (jdk.*)/jre"]
  306. CUSTOM_JDK_NUMBER = "3"
  307. JDK_MIN_FILESIZE = 5000
  308. JDK_INSTALL_DIR = "/usr/jdk64"
  309. CREATE_JDK_DIR_CMD = "/bin/mkdir -p " + JDK_INSTALL_DIR
  310. MAKE_FILE_EXECUTABLE_CMD = "chmod a+x {0}"
  311. JAVA_HOME_PROPERTY = "java.home"
  312. JDK_NAME_PROPERTY = "jdk.name"
  313. JCE_NAME_PROPERTY = "jce.name"
  314. OS_TYPE_PROPERTY = "server.os_type"
  315. GET_FQDN_SERVICE_URL="server.fqdn.service.url"
  316. JDK_DOWNLOAD_CMD = "curl --create-dirs -o {0} {1}"
  317. JDK_DOWNLOAD_SIZE_CMD = "curl -I {0}"
  318. UNTAR_JDK_ARVHIVE = "tar -xvf {0}"
  319. #JCE Policy files
  320. JCE_POLICY_FILENAMES = ["UnlimitedJCEPolicyJDK7.zip" , "jce_policy-6.zip"]
  321. JCE_DOWNLOAD_CMD = "curl -o {0} {1}"
  322. JCE_MIN_FILESIZE = 5000
  323. DEFAULT_DB_NAME = "ambari"
  324. # stack repo upgrade
  325. STACK_LOCATION_KEY = 'metadata.path'
  326. STACK_LOCATION_DEFAULT = '/var/lib/ambari-server/resources/stacks'
  327. DATABASE_INSERT_METAINFO_SCRIPTS = ['/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-Postgres-INSERT_METAINFO.sql',
  328. '/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-Oracle-INSERT_METAINFO.sql',
  329. '/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-MySQL-INSERT_METAINFO.sql']
  330. DATABASE_FIX_LOCAL_REPO_SCRIPTS = ['/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-Postgres-FIX_LOCAL_REPO.sql',
  331. '/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-Oracle-FIX_LOCAL_REPO.sql',
  332. '/var/lib/ambari-server/resources/upgrade/dml/Ambari-DML-MySQL-FIX_LOCAL_REPO.sql']
  333. INSERT_METAINFO_CMD = ['su', 'postgres',
  334. '--command=psql -f {0} -v metainfo_key="\'{1}\'" -v metainfo_value="\'{2}\'" -v dbname="{3}"']
  335. FIX_LOCAL_REPO_CMD = ['su', 'postgres', '--command=psql -f {0} -v dbname="{1}"']
  336. #Apache License Header
  337. ASF_LICENSE_HEADER = '''
  338. # Copyright 2011 The Apache Software Foundation
  339. #
  340. # Licensed to the Apache Software Foundation (ASF) under one
  341. # or more contributor license agreements. See the NOTICE file
  342. # distributed with this work for additional information
  343. # regarding copyright ownership. The ASF licenses this file
  344. # to you under the Apache License, Version 2.0 (the
  345. # "License"); you may not use this file except in compliance
  346. # with the License. You may obtain a copy of the License at
  347. #
  348. # http://www.apache.org/licenses/LICENSE-2.0
  349. #
  350. # Unless required by applicable law or agreed to in writing, software
  351. # distributed under the License is distributed on an "AS IS" BASIS,
  352. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  353. # See the License for the specific language governing permissions and
  354. # limitations under the License.
  355. '''
  356. if OS == OS_UBUNTU:
  357. PG_HBA_DIR = '/etc/postgresql/8.4/main'
  358. class FirewallChecks(object):
  359. def __init__(self):
  360. self.FIREWALL_SERVICE_NAME = "iptables"
  361. self.SERVICE_CMD = SERVICE_CMD
  362. self.SERVICE_SUBCMD = "status"
  363. def get_command(self):
  364. return "%s %s %s" % (self.SERVICE_CMD, self.FIREWALL_SERVICE_NAME, self.SERVICE_SUBCMD)
  365. def check_result(self, retcode, out, err):
  366. return retcode == 0
  367. def check_iptables(self):
  368. retcode, out, err = run_os_command(self.get_command())
  369. if err and len(err) > 0:
  370. print err
  371. if self.check_result(retcode, out, err):
  372. print_warning_msg("%s is running. Confirm the necessary Ambari ports are accessible. " %
  373. self.FIREWALL_SERVICE_NAME +
  374. "Refer to the Ambari documentation for more details on ports.")
  375. ok = get_YN_input("OK to continue [y/n] (y)? ", True)
  376. if not ok:
  377. raise FatalException(1, None)
  378. def get_running_result(self):
  379. # To support test code. Expected ouput from run_os_command.
  380. return (0, "", "")
  381. def get_stopped_result(self):
  382. # To support test code. Expected output from run_os_command.
  383. return (3, "", "")
  384. class UbuntuFirewallChecks(FirewallChecks):
  385. def __init__(self):
  386. super(UbuntuFirewallChecks, self).__init__()
  387. self.FIREWALL_SERVICE_NAME = "ufw"
  388. self.SERVICE_CMD = "/usr/sbin/service"
  389. def check_result(self, retcode, out, err):
  390. # On ubuntu, the status command returns 0 whether running or not
  391. return out and len(out) > 0 and out.strip() != "ufw stop/waiting"
  392. def get_running_result(self):
  393. # To support test code. Expected ouput from run_os_command.
  394. return (0, "ufw start/running", "")
  395. def get_stopped_result(self):
  396. # To support test code. Expected output from run_os_command.
  397. return (0, "ufw stop/waiting", "")
  398. class Fedora18FirewallChecks(FirewallChecks):
  399. def __init__(self):
  400. self.FIREWALL_SERVICE_NAME = "firewalld.service"
  401. def get_command(self):
  402. return "systemctl is-active firewalld.service"
  403. class OpenSuseFirewallChecks(FirewallChecks):
  404. def __init__(self):
  405. self.FIREWALL_SERVICE_NAME = "SuSEfirewall2"
  406. def get_command(self):
  407. return "/sbin/SuSEfirewall2 status"
  408. def get_firewall_object():
  409. if OS == OS_UBUNTU:
  410. return UbuntuFirewallChecks()
  411. elif OS == OS_FEDORA and int(OS_VERSION) >= 18:
  412. return Fedora18FirewallChecks()
  413. elif OS == OS_OPENSUSE:
  414. return OpenSuseFirewallChecks()
  415. else:
  416. return FirewallChecks()
  417. def get_firewall_object_types():
  418. # To support test code, so tests can loop through the types
  419. return (FirewallChecks,
  420. UbuntuFirewallChecks,
  421. Fedora18FirewallChecks,
  422. OpenSuseFirewallChecks)
  423. def check_iptables():
  424. return get_firewall_object().check_iptables()
  425. def get_conf_dir():
  426. try:
  427. conf_dir = os.environ[AMBARI_CONF_VAR]
  428. return conf_dir
  429. except KeyError:
  430. default_conf_dir = "/etc/ambari-server/conf"
  431. print AMBARI_CONF_VAR + " is not set, using default " + default_conf_dir
  432. return default_conf_dir
  433. def find_properties_file():
  434. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  435. if conf_file is None:
  436. err = 'File %s not found in search path $%s: %s' % (AMBARI_PROPERTIES_FILE,
  437. AMBARI_CONF_VAR, get_conf_dir())
  438. print err
  439. raise FatalException(1, err)
  440. else:
  441. print_info_msg ('Loading properties from ' + conf_file)
  442. return conf_file
  443. def update_ambari_properties():
  444. prev_conf_file = search_file(AMBARI_PROPERTIES_RPMSAVE_FILE, get_conf_dir())
  445. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  446. # Previous config file does not exist
  447. if (not prev_conf_file) or (prev_conf_file is None):
  448. print_warning_msg("Can not find ambari.properties.rpmsave file from previous version, skipping import of settings")
  449. return 0
  450. try:
  451. old_properties = Properties()
  452. old_properties.load(open(prev_conf_file))
  453. except Exception, e:
  454. print 'Could not read "%s": %s' % (prev_conf_file, e)
  455. return -1
  456. try:
  457. new_properties = Properties()
  458. new_properties.load(open(conf_file))
  459. for prop_key, prop_value in old_properties.getPropertyDict().items():
  460. if ("agent.fqdn.service.url" == prop_key):
  461. #BUG-7179 what is agent.fqdn property in ambari.props?
  462. new_properties.process_pair(GET_FQDN_SERVICE_URL,prop_value)
  463. else:
  464. new_properties.process_pair(prop_key,prop_value)
  465. # Adding custom user name property if it is absent
  466. # In previous versions without custom user support server was started as
  467. # "root" anyway so it's a reasonable default
  468. if not NR_USER_PROPERTY in new_properties.keys():
  469. new_properties.process_pair(NR_USER_PROPERTY, "root")
  470. new_properties.store(open(conf_file,'w'))
  471. except Exception, e:
  472. print 'Could not write "%s": %s' % (conf_file, e)
  473. return -1
  474. timestamp = datetime.datetime.now()
  475. format = '%Y%m%d%H%M%S'
  476. os.rename(prev_conf_file, prev_conf_file + '.' + timestamp.strftime(format))
  477. return 0
  478. NR_CONF_DIR = get_conf_dir()
  479. # ownership/permissions mapping
  480. # path - permissions - user - group - recursive
  481. # Rules are executed in the same order as they are listed
  482. # {0} in user/group will be replaced by customized ambari-server username
  483. NR_ADJUST_OWNERSHIP_LIST =[
  484. ( "/var/log/ambari-server", "644", "{0}", True ),
  485. ( "/var/log/ambari-server", "755", "{0}", False ),
  486. ( "/var/run/ambari-server", "644", "{0}", True),
  487. ( "/var/run/ambari-server", "755", "{0}", False),
  488. ( "/var/run/ambari-server/bootstrap", "755", "{0}", False ),
  489. ( "/var/lib/ambari-server/ambari-env.sh", "700", "{0}", False ),
  490. ( "/var/lib/ambari-server/keys", "600", "{0}", True ),
  491. ( "/var/lib/ambari-server/keys", "700", "{0}", False ),
  492. ( "/var/lib/ambari-server/keys/db", "700", "{0}", False ),
  493. ( "/var/lib/ambari-server/keys/db/newcerts", "700", "{0}", False ),
  494. ( "/var/lib/ambari-server/keys/.ssh", "700", "{0}", False ),
  495. ( "/etc/ambari-server/conf", "644", "{0}", True ),
  496. ( "/etc/ambari-server/conf", "755", "{0}", False ),
  497. ( "/etc/ambari-server/conf/password.dat", "640", "{0}", False ),
  498. # Also, /etc/ambari-server/conf/password.dat
  499. # is generated later at store_password_file
  500. ]
  501. ### System interaction ###
  502. class FatalException(Exception):
  503. def __init__(self, code, reason):
  504. self.code = code
  505. self.reason = reason
  506. def __str__(self):
  507. return repr("Fatal exception: %s, exit code %s" % (self.reason, self.code))
  508. def _get_message(self):
  509. return str(self)
  510. class NonFatalException(Exception):
  511. def __init__(self, reason):
  512. self.reason = reason
  513. def __str__(self):
  514. return repr("NonFatal exception: %s" % self.reason)
  515. def _get_message(self):
  516. return str(self)
  517. def is_root():
  518. '''
  519. Checks effective UUID
  520. Returns True if a program is running under root-level privileges.
  521. '''
  522. return os.geteuid() == 0
  523. def get_exec_path(cmd):
  524. cmd = 'which {0}'.format(cmd)
  525. ret, out, err = run_in_shell(cmd)
  526. if ret == 0:
  527. return out.strip()
  528. else:
  529. return None
  530. def run_in_shell(cmd):
  531. print_info_msg('about to run command: ' + str(cmd))
  532. process = subprocess.Popen(cmd,
  533. stdout=subprocess.PIPE,
  534. stdin=subprocess.PIPE,
  535. stderr=subprocess.PIPE,
  536. shell=True
  537. )
  538. (stdoutdata, stderrdata) = process.communicate()
  539. return process.returncode, stdoutdata, stderrdata
  540. def run_os_command(cmd):
  541. print_info_msg('about to run command: ' + str(cmd))
  542. if type(cmd) == str:
  543. cmd = shlex.split(cmd)
  544. process = subprocess.Popen(cmd,
  545. stdout=subprocess.PIPE,
  546. stdin=subprocess.PIPE,
  547. stderr=subprocess.PIPE
  548. )
  549. (stdoutdata, stderrdata) = process.communicate()
  550. return process.returncode, stdoutdata, stderrdata
  551. #
  552. # Checks SELinux
  553. #
  554. def check_selinux():
  555. try:
  556. retcode, out, err = run_os_command(GET_SE_LINUX_ST_CMD)
  557. se_status = re.search('(disabled|enabled)', out).group(0)
  558. print "SELinux status is '" + se_status + "'"
  559. if se_status == SE_STATUS_DISABLED:
  560. return 0
  561. else:
  562. try:
  563. se_mode = re.search('(enforcing|permissive)', out).group(0)
  564. except AttributeError:
  565. err = "Error determining SELinux mode. Exiting."
  566. raise FatalException(1, err)
  567. print "SELinux mode is '" + se_mode + "'"
  568. if se_mode == SE_MODE_ENFORCING:
  569. print "Temporarily disabling SELinux"
  570. run_os_command(SE_SETENFORCE_CMD)
  571. print_warning_msg(
  572. "SELinux is set to 'permissive' mode and temporarily disabled.")
  573. ok = get_YN_input("OK to continue [y/n] (y)? ", True)
  574. if not ok:
  575. raise FatalException(1, None)
  576. return 0
  577. except OSError:
  578. print_warning_msg("Could not run {0}: OK".format(GET_SE_LINUX_ST_CMD))
  579. return 0
  580. def read_ambari_user():
  581. '''
  582. Reads ambari user from properties file
  583. '''
  584. conf_file = find_properties_file()
  585. try:
  586. properties = Properties()
  587. properties.load(open(conf_file))
  588. user = properties[NR_USER_PROPERTY]
  589. if user:
  590. return user
  591. else:
  592. return None
  593. except Exception, e:
  594. print_error_msg('Could not read "%s": %s' % (conf_file, e))
  595. return None
  596. def adjust_directory_permissions(ambari_user):
  597. properties = get_ambari_properties()
  598. bootstrap_dir = get_value_from_properties(properties, BOOTSTRAP_DIR_PROPERTY)
  599. print_info_msg("Cleaning bootstrap directory ({0}) contents...".format(bootstrap_dir))
  600. cmd = RECURSIVE_RM_CMD.format(bootstrap_dir)
  601. run_os_command(cmd)
  602. os.mkdir(bootstrap_dir)
  603. # Add master key and credential store if exists
  604. keyLocation = get_master_key_location(properties)
  605. masterKeyFile = search_file(SECURITY_MASTER_KEY_FILENAME, keyLocation)
  606. if masterKeyFile:
  607. NR_ADJUST_OWNERSHIP_LIST.append((masterKeyFile, "600", "{0}", "{0}", False))
  608. credStoreFile = get_credential_store_location(properties)
  609. if os.path.exists(credStoreFile):
  610. NR_ADJUST_OWNERSHIP_LIST.append((credStoreFile, "600", "{0}", "{0}", False))
  611. trust_store_location = properties[SSL_TRUSTSTORE_PATH_PROPERTY]
  612. if trust_store_location:
  613. NR_ADJUST_OWNERSHIP_LIST.append((trust_store_location, "600", "{0}", "{0}", False))
  614. print "Adjusting ambari-server permissions and ownership..."
  615. for pack in NR_ADJUST_OWNERSHIP_LIST:
  616. file = pack[0]
  617. mod = pack[1]
  618. user = pack[2].format(ambari_user)
  619. recursive = pack[3]
  620. set_file_permissions(file, mod, user, recursive)
  621. def set_file_permissions(file, mod, user, recursive):
  622. WARN_MSG = "Command {0} returned exit code {1} with message: {2}"
  623. if recursive:
  624. params = " -R "
  625. else:
  626. params = ""
  627. if os.path.exists(file):
  628. command = NR_CHMOD_CMD.format(params, mod, file)
  629. retcode, out, err = run_os_command(command)
  630. if retcode != 0 :
  631. print_warning_msg(WARN_MSG.format(command, file, err))
  632. command = NR_CHOWN_CMD.format(params, user, file)
  633. retcode, out, err = run_os_command(command)
  634. if retcode != 0 :
  635. print_warning_msg(WARN_MSG.format(command, file, err))
  636. else:
  637. print_info_msg("File %s does not exist" % file)
  638. def create_custom_user():
  639. user = get_validated_string_input(
  640. "Enter user account for ambari-server daemon (root):",
  641. "root",
  642. "^[a-z_][a-z0-9_-]{1,31}$",
  643. "Invalid username.",
  644. False
  645. )
  646. print_info_msg("Trying to create user {0}".format(user))
  647. command = NR_USERADD_CMD.format(user, NR_USER_COMMENT)
  648. retcode, out, err = run_os_command(command)
  649. if retcode == 9: # 9 = username already in use
  650. print_info_msg("User {0} already exists, "
  651. "skipping user creation".format(user))
  652. elif retcode != 0: # fail
  653. print_warning_msg("Can't create user {0}. Command {1} "
  654. "finished with {2}: \n{3}".format(user, command, retcode, err))
  655. return retcode, None
  656. print_info_msg("User configuration is done.")
  657. return 0, user
  658. def check_ambari_user():
  659. try:
  660. user = read_ambari_user()
  661. create_user = False
  662. update_user_setting = False
  663. if user is not None:
  664. create_user = get_YN_input("Ambari-server daemon is configured to run under user '{0}'."
  665. " Change this setting [y/n] (n)? ".format(user), False)
  666. update_user_setting = create_user # Only if we will create another user
  667. else: # user is not configured yet
  668. update_user_setting = True # Write configuration anyway
  669. create_user = get_YN_input("Customize user account for ambari-server "
  670. "daemon [y/n] (n)? ", False)
  671. if not create_user:
  672. user = "root"
  673. if create_user:
  674. (retcode, user) = create_custom_user()
  675. if retcode != 0:
  676. return retcode
  677. if update_user_setting:
  678. write_property(NR_USER_PROPERTY, user)
  679. adjust_directory_permissions(user)
  680. except OSError:
  681. print_error_msg("Failed: %s" % OSError.message)
  682. return 4
  683. except Exception as e:
  684. print_error_msg("Unexpected error %s" % e.message)
  685. return 1
  686. return 0
  687. ### Postgres ###
  688. def configure_pg_hba_ambaridb_users():
  689. args = optparse.Values()
  690. configure_database_username_password(args)
  691. with open(PG_HBA_CONF_FILE, "a") as pgHbaConf:
  692. pgHbaConf.write("\n")
  693. pgHbaConf.write("local all " + args.database_username +
  694. ",mapred md5")
  695. pgHbaConf.write("\n")
  696. pgHbaConf.write("host all " + args.database_username +
  697. ",mapred 0.0.0.0/0 md5")
  698. pgHbaConf.write("\n")
  699. pgHbaConf.write("host all " + args.database_username +
  700. ",mapred ::/0 md5")
  701. pgHbaConf.write("\n")
  702. retcode, out, err = run_os_command(PG_HBA_RELOAD_CMD)
  703. if not retcode == 0:
  704. raise FatalException(retcode, err)
  705. def configure_pg_hba_postgres_user():
  706. postgresString = "all postgres"
  707. for line in fileinput.input(PG_HBA_CONF_FILE, inplace=1):
  708. print re.sub('all\s*all', postgresString, line),
  709. os.chmod(PG_HBA_CONF_FILE, 0644)
  710. def configure_postgresql_conf():
  711. listenAddress = "listen_addresses = '*' #"
  712. for line in fileinput.input(POSTGRESQL_CONF_FILE, inplace=1):
  713. print re.sub('#+listen_addresses.*?(#|$)', listenAddress, line),
  714. os.chmod(POSTGRESQL_CONF_FILE, 0644)
  715. def configure_postgres():
  716. if os.path.isfile(PG_HBA_CONF_FILE):
  717. if not os.path.isfile(PG_HBA_CONF_FILE_BACKUP):
  718. shutil.copyfile(PG_HBA_CONF_FILE, PG_HBA_CONF_FILE_BACKUP)
  719. else:
  720. #Postgres has been configured before, must not override backup
  721. print "Backup for pg_hba found, reconfiguration not required"
  722. return 0
  723. configure_pg_hba_postgres_user()
  724. configure_pg_hba_ambaridb_users()
  725. os.chmod(PG_HBA_CONF_FILE, 0644)
  726. configure_postgresql_conf()
  727. #restart postgresql if already running
  728. pg_status = get_postgre_status()
  729. if pg_status == PG_STATUS_RUNNING:
  730. retcode = restart_postgres()
  731. return retcode
  732. return 0
  733. def restart_postgres():
  734. print "Restarting PostgreSQL"
  735. process = subprocess.Popen(PG_RESTART_CMD.split(' '),
  736. stdout=subprocess.PIPE,
  737. stdin=subprocess.PIPE,
  738. stderr=subprocess.PIPE
  739. )
  740. time.sleep(5)
  741. result = process.poll()
  742. if result is None:
  743. print_info_msg("Killing restart PostgresSQL process")
  744. process.kill()
  745. pg_status = get_postgre_status()
  746. # SUSE linux set status of stopped postgresql proc to unused
  747. if pg_status == "unused" or pg_status == "stopped":
  748. print_info_msg("PostgreSQL is stopped. Restarting ...")
  749. retcode, out, err = run_os_command(PG_START_CMD)
  750. return retcode
  751. return 0
  752. # todo: check if the scheme is already exist
  753. def write_property(key, value):
  754. conf_file = find_properties_file()
  755. properties = Properties()
  756. try:
  757. properties.load(open(conf_file))
  758. except Exception, e:
  759. print_error_msg('Could not read ambari config file "%s": %s' % (conf_file, e))
  760. return -1
  761. properties.process_pair(key, value)
  762. try:
  763. properties.store(open(conf_file, "w"))
  764. except Exception, e:
  765. print_error_msg('Could not write ambari config file "%s": %s' % (conf_file, e))
  766. return -1
  767. return 0
  768. def remove_property(key):
  769. conf_file = find_properties_file()
  770. properties = Properties()
  771. try:
  772. properties.load(open(conf_file))
  773. except Exception, e:
  774. print_error_msg('Could not read ambari config file "%s": %s' % (conf_file, e))
  775. return -1
  776. properties.removeOldProp(key)
  777. try:
  778. properties.store(open(conf_file, "w"))
  779. except Exception, e:
  780. print_error_msg('Could not write ambari config file "%s": %s' % (conf_file, e))
  781. return -1
  782. return 0
  783. def setup_db(args):
  784. #password access to ambari-server and mapred
  785. configure_database_username_password(args)
  786. dbname = args.database_name
  787. scriptFile = args.init_script_file
  788. username = args.database_username
  789. password = args.database_password
  790. #setup DB
  791. command = SETUP_DB_CMD[:]
  792. command[-1] = command[-1].format(scriptFile, username, password, dbname)
  793. for i in range(SETUP_DB_CONNECT_ATTEMPTS):
  794. print 'Connecting to the database. Attempt %d...' % (i+1)
  795. retcode, outdata, errdata = run_os_command(command)
  796. if retcode == 0:
  797. return retcode, outdata, errdata
  798. time.sleep(SETUP_DB_CONNECT_TIMEOUT)
  799. print_error_msg(errdata)
  800. return retcode, outdata, errdata
  801. def store_password_file(password, filename):
  802. conf_file = find_properties_file()
  803. passFilePath = os.path.join(os.path.dirname(conf_file),
  804. filename)
  805. with open(passFilePath, 'w+') as passFile:
  806. passFile.write(password)
  807. print_info_msg("Adjusting filesystem permissions")
  808. ambari_user = read_ambari_user()
  809. set_file_permissions(passFilePath, "660", ambari_user, False)
  810. return passFilePath
  811. def remove_password_file(filename):
  812. conf_file = find_properties_file()
  813. passFilePath = os.path.join(os.path.dirname(conf_file),
  814. filename)
  815. if os.path.exists(passFilePath):
  816. try:
  817. os.remove(passFilePath)
  818. except Exception, e:
  819. print_warning_msg('Unable to remove password file: ' + str(e))
  820. return 1
  821. pass
  822. return 0
  823. def execute_db_script(args, file):
  824. #password access to ambari-server and mapred
  825. configure_database_username_password(args)
  826. dbname = args.database_name
  827. username = args.database_username
  828. password = args.database_password
  829. command = SETUP_DB_CMD[:]
  830. command[-1] = command[-1].format(file, username, password, dbname)
  831. retcode, outdata, errdata = run_os_command(command)
  832. if not retcode == 0:
  833. print errdata
  834. return retcode
  835. def check_db_consistency(args, file):
  836. #password access to ambari-server and mapred
  837. configure_database_username_password(args)
  838. dbname = args.database_name
  839. username = args.database_username
  840. password = args.database_password
  841. command = SETUP_DB_CMD[:]
  842. command[-1] = command[-1].format(file, username, password, dbname)
  843. retcode, outdata, errdata = run_os_command(command)
  844. if not retcode == 0:
  845. print errdata
  846. return retcode
  847. else:
  848. # Assumes that the output is of the form ...\n<count>
  849. print_info_msg("Parsing output: " + outdata)
  850. lines = outdata.splitlines()
  851. if (lines[-1] == '3' or lines[-1] == '0'):
  852. return 0
  853. return -1
  854. def get_postgre_status():
  855. retcode, out, err = run_os_command(PG_ST_CMD)
  856. try:
  857. pg_status = re.search('(stopped|running)', out, re.IGNORECASE).group(0).lower()
  858. except AttributeError:
  859. pg_status = None
  860. return pg_status
  861. def check_postgre_up():
  862. pg_status = get_postgre_status()
  863. if pg_status == PG_STATUS_RUNNING:
  864. print_info_msg ("PostgreSQL is running")
  865. return 0
  866. else:
  867. # run initdb only on non ubuntu systems as ubuntu does not have initdb cmd.
  868. if OS != OS_UBUNTU:
  869. print "Running initdb: This may take upto a minute."
  870. retcode, out, err = run_os_command(PG_INITDB_CMD)
  871. if retcode == 0:
  872. print out
  873. print "About to start PostgreSQL"
  874. try:
  875. process = subprocess.Popen(PG_START_CMD.split(' '),
  876. stdout=subprocess.PIPE,
  877. stdin=subprocess.PIPE,
  878. stderr=subprocess.PIPE
  879. )
  880. time.sleep(20)
  881. result = process.poll()
  882. print_info_msg("Result of postgres start cmd: " + str(result))
  883. if result is None:
  884. process.kill()
  885. pg_status = get_postgre_status()
  886. if pg_status == PG_STATUS_RUNNING:
  887. print_info_msg("Postgres process is running. Returning...")
  888. return 0
  889. else:
  890. retcode = result
  891. except (Exception), e:
  892. pg_status = get_postgre_status()
  893. if pg_status == PG_STATUS_RUNNING:
  894. return 0
  895. else:
  896. print_error_msg("Postgres start failed. " + str(e))
  897. return 1
  898. return retcode
  899. def get_validated_db_name(database_name):
  900. return get_validated_string_input(
  901. DATABASE_STORAGE_NAMES[DATABASE_INDEX] + " Name ("
  902. + database_name + "): ",
  903. database_name,
  904. ".*",
  905. "Invalid " + DATABASE_STORAGE_NAMES[DATABASE_INDEX] + " name.",
  906. False
  907. )
  908. def get_validated_service_name(service_name, index):
  909. return get_validated_string_input(
  910. ORACLE_DB_ID_TYPES[index] + " (" + service_name + "): ",
  911. service_name,
  912. ".*",
  913. "Invalid " + ORACLE_DB_ID_TYPES[index] + ".",
  914. False
  915. )
  916. def read_password(passwordDefault=PG_DEFAULT_PASSWORD,
  917. passwordPattern=PASSWORD_PATTERN,
  918. passwordPrompt=None,
  919. passwordDescr=None):
  920. # setup password
  921. if passwordPrompt is None:
  922. passwordPrompt = 'Password (' + passwordDefault + '): '
  923. if passwordDescr is None:
  924. passwordDescr = "Invalid characters in password. Use only alphanumeric or " \
  925. "_ or - characters"
  926. password = get_validated_string_input(passwordPrompt, passwordDefault,
  927. passwordPattern, passwordDescr, True)
  928. if not password:
  929. print 'Password cannot be blank.'
  930. return read_password(passwordDefault, passwordPattern, passwordPrompt,
  931. passwordDescr)
  932. if password != passwordDefault:
  933. password1 = get_validated_string_input("Re-enter password: ",
  934. passwordDefault, passwordPattern, passwordDescr, True)
  935. if password != password1:
  936. print "Passwords do not match"
  937. return read_password(passwordDefault, passwordPattern, passwordPrompt,
  938. passwordDescr)
  939. return password
  940. def get_pass_file_path(conf_file):
  941. return os.path.join(os.path.dirname(conf_file),
  942. JDBC_PASSWORD_FILENAME)
  943. # Set database properties to default values
  944. def load_default_db_properties(args):
  945. args.database=DATABASE_NAMES[DATABASE_INDEX]
  946. args.database_host = "localhost"
  947. args.database_port = DATABASE_PORTS[DATABASE_INDEX]
  948. args.database_name = DEFAULT_DB_NAME
  949. args.database_username = "ambari"
  950. args.database_password = "bigdata"
  951. args.sid_or_sname = "sname"
  952. pass
  953. # Ask user for database conenction properties
  954. def prompt_db_properties(args):
  955. global DATABASE_INDEX
  956. if PROMPT_DATABASE_OPTIONS:
  957. load_default_db_properties(args)
  958. ok = get_YN_input("Enter advanced database configuration [y/n] (n)? ", False)
  959. if ok:
  960. print "=============================================================================="
  961. print "Choose one of the following options:"
  962. database_num = str(DATABASE_INDEX + 1)
  963. database_num = get_validated_string_input(
  964. "[1] - PostgreSQL (Embedded)\n[2] - Oracle\n[3] - MySQL\n==============================================================================\nEnter choice (" + database_num + "): ",
  965. database_num,
  966. "^[123]$",
  967. "Invalid number.",
  968. False
  969. )
  970. DATABASE_INDEX = int(database_num) - 1
  971. args.database = DATABASE_NAMES[DATABASE_INDEX]
  972. if args.database != "postgres" :
  973. args.database_host = get_validated_string_input(
  974. "Hostname (" + args.database_host + "): ",
  975. args.database_host,
  976. "^[a-zA-Z0-9.\-]*$",
  977. "Invalid hostname.",
  978. False
  979. )
  980. args.database_port=DATABASE_PORTS[DATABASE_INDEX]
  981. args.database_port = get_validated_string_input(
  982. "Port (" + args.database_port + "): ",
  983. args.database_port,
  984. "^([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])$",
  985. "Invalid port.",
  986. False
  987. )
  988. if args.database == "oracle":
  989. # Oracle uses service name or service id
  990. idType = "1"
  991. idType = get_validated_string_input(
  992. "Select Oracle identifier type:\n1 - " + ORACLE_DB_ID_TYPES[0] +
  993. "\n2 - " + ORACLE_DB_ID_TYPES[1] + "\n(" + idType + "): ",
  994. idType,
  995. "^[12]$",
  996. "Invalid number.",
  997. False
  998. )
  999. if idType == "2":
  1000. args.sid_or_sname = "sid"
  1001. IDTYPE_INDEX = int(idType) - 1
  1002. args.database_name = get_validated_service_name(args.database_name,
  1003. IDTYPE_INDEX)
  1004. elif args.database == "mysql":
  1005. args.database_name = get_validated_db_name(args.database_name)
  1006. else:
  1007. # other DB types
  1008. pass
  1009. pass
  1010. else:
  1011. args.database_host = "localhost"
  1012. args.database_port = DATABASE_PORTS[DATABASE_INDEX]
  1013. args.database_name = get_validated_db_name(args.database_name)
  1014. pass
  1015. # Username is common for Oracle/MySQL/Postgres
  1016. args.database_username = get_validated_string_input(
  1017. 'Username (' + args.database_username + '): ',
  1018. args.database_username,
  1019. USERNAME_PATTERN,
  1020. "Invalid characters in username. Start with _ or alpha "
  1021. "followed by alphanumeric or _ or - characters",
  1022. False
  1023. )
  1024. args.database_password = configure_database_password(True)
  1025. print_info_msg('Using database options: {database},{host},{port},{schema},{user},{password}'.format(
  1026. database=args.database,
  1027. host=args.database_host,
  1028. port=args.database_port,
  1029. schema=args.database_name,
  1030. user=args.database_username,
  1031. password=args.database_password
  1032. ))
  1033. # Store set of properties for remote database connection
  1034. def store_remote_properties(args):
  1035. properties = get_ambari_properties()
  1036. if properties == -1:
  1037. print_error_msg ("Error getting ambari properties")
  1038. return -1
  1039. isSecure = get_is_secure(properties)
  1040. properties.process_pair(PERSISTENCE_TYPE_PROPERTY, "remote")
  1041. properties.process_pair(JDBC_DATABASE_PROPERTY, args.database)
  1042. properties.process_pair(JDBC_HOSTNAME_PROPERTY, args.database_host)
  1043. properties.process_pair(JDBC_PORT_PROPERTY, args.database_port)
  1044. properties.process_pair(JDBC_SCHEMA_PROPERTY, args.database_name)
  1045. properties.process_pair(JDBC_DRIVER_PROPERTY, DATABASE_DRIVER_NAMES[DATABASE_INDEX])
  1046. # fully qualify the hostname to make sure all the other hosts can connect
  1047. # to the jdbc hostname since its passed onto the agents for RCA
  1048. jdbc_hostname = args.database_host
  1049. if (args.database_host == "localhost"):
  1050. jdbc_hostname = socket.getfqdn();
  1051. connectionStringFormat = DATABASE_CONNECTION_STRINGS
  1052. if args.sid_or_sname == "sid":
  1053. connectionStringFormat = DATABASE_CONNECTION_STRINGS_ALT
  1054. properties.process_pair(JDBC_URL_PROPERTY, connectionStringFormat[DATABASE_INDEX].format(jdbc_hostname, args.database_port, args.database_name))
  1055. properties.process_pair(JDBC_USER_NAME_PROPERTY, args.database_username)
  1056. properties.process_pair(JDBC_PASSWORD_PROPERTY,
  1057. store_password_file(args.database_password, JDBC_PASSWORD_FILENAME))
  1058. # save any other defined properties to pass to JDBC
  1059. if DATABASE_INDEX < len(DATABASE_JDBC_PROPERTIES):
  1060. for pair in DATABASE_JDBC_PROPERTIES[DATABASE_INDEX]:
  1061. properties.process_pair(JDBC_PROPERTIES_PREFIX + pair[0], pair[1])
  1062. if isSecure:
  1063. encrypted_password = encrypt_password(JDBC_RCA_PASSWORD_ALIAS, args.database_password)
  1064. if encrypted_password != args.database_password:
  1065. properties.process_pair(JDBC_PASSWORD_PROPERTY, encrypted_password)
  1066. pass
  1067. properties.process_pair(JDBC_RCA_DRIVER_PROPERTY, DATABASE_DRIVER_NAMES[DATABASE_INDEX])
  1068. properties.process_pair(JDBC_RCA_URL_PROPERTY, connectionStringFormat[DATABASE_INDEX].format(jdbc_hostname, args.database_port, args.database_name))
  1069. properties.process_pair(JDBC_RCA_USER_NAME_PROPERTY, args.database_username)
  1070. properties.process_pair(JDBC_RCA_PASSWORD_FILE_PROPERTY,
  1071. store_password_file(args.database_password, JDBC_PASSWORD_FILENAME))
  1072. if isSecure:
  1073. encrypted_password = encrypt_password(JDBC_RCA_PASSWORD_ALIAS, args.database_password)
  1074. if encrypted_password != args.database_password:
  1075. properties.process_pair(JDBC_RCA_PASSWORD_FILE_PROPERTY, encrypted_password)
  1076. pass
  1077. conf_file = properties.fileName
  1078. try:
  1079. properties.store(open(conf_file, "w"))
  1080. except Exception, e:
  1081. print 'Could not write ambari config file "%s": %s' % (conf_file, e)
  1082. return -1
  1083. return 0
  1084. # Initialize remote database schema
  1085. def setup_remote_db(args):
  1086. not_found_msg = "Cannot find {0} {1} client in the path to load the Ambari Server schema.\
  1087. Before starting Ambari Server, you must run the following DDL against the database to create \
  1088. the schema ".format(DATABASE_NAMES[DATABASE_INDEX], str(DATABASE_CLI_TOOLS_DESC[DATABASE_INDEX]))
  1089. client_usage_cmd = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_INIT_SCRIPTS[DATABASE_INDEX], args.database_username,
  1090. BLIND_PASSWORD, args.database_name)
  1091. retcode, out, err = execute_remote_script(args, DATABASE_INIT_SCRIPTS[DATABASE_INDEX])
  1092. if retcode != 0:
  1093. if retcode == -1:
  1094. print_warning_msg(not_found_msg + os.linesep + client_usage_cmd)
  1095. if not SILENT:
  1096. raw_input(PRESS_ENTER_MSG)
  1097. return retcode
  1098. print err
  1099. print_error_msg('Database bootstrap failed. Please, provide correct connection properties.')
  1100. return retcode
  1101. return 0
  1102. # Get database client executable path
  1103. def get_db_cli_tool(args):
  1104. for tool in DATABASE_CLI_TOOLS[DATABASE_INDEX]:
  1105. cmd =CHECK_COMMAND_EXIST_CMD.format(tool)
  1106. ret, out, err = run_in_shell(cmd)
  1107. if ret == 0:
  1108. return get_exec_path(tool)
  1109. return None
  1110. def remote_stack_upgrade(args, scriptPath, stackId):
  1111. tool = get_db_cli_tool(args)
  1112. if not tool:
  1113. args.warnings.append('{0} not found. Please, run DDL script manually'.format(DATABASE_CLI_TOOLS[DATABASE_INDEX]))
  1114. if VERBOSE:
  1115. print_warning_msg('{0} not found'.format(DATABASE_CLI_TOOLS[DATABASE_INDEX]))
  1116. return -1, "Client wasn't found", "Client wasn't found"
  1117. #TODO add support of other databases with scripts
  1118. stack_name, stack_version = stackId.split(STACK_NAME_VER_SEP)
  1119. if args.database == "oracle":
  1120. sid_or_sname = "sid"
  1121. if (hasattr(args, 'sid_or_sname') and args.sid_or_sname == "sname") or \
  1122. (hasattr(args, 'jdbc_url') and args.jdbc_url and re.match(ORACLE_SNAME_PATTERN, args.jdbc_url)):
  1123. print_info_msg("using SERVICE_NAME instead of SID for Oracle")
  1124. sid_or_sname = "service_name"
  1125. retcode, out, err = run_in_shell('{0} {1}'.format(tool, ORACLE_UPGRADE_STACK_ARGS.format(
  1126. args.database_username,
  1127. args.database_password,
  1128. args.database_host,
  1129. args.database_port,
  1130. args.database_name,
  1131. scriptPath,
  1132. sid_or_sname,
  1133. stack_name,
  1134. stack_version
  1135. )))
  1136. return retcode, out, err
  1137. elif args.database == "mysql":
  1138. retcode, out, err = run_in_shell('{0} {1}'.format(tool, MYSQL_UPGRADE_STACK_ARGS.format(
  1139. args.database_host,
  1140. args.database_port,
  1141. args.database_username,
  1142. args.database_password,
  1143. args.database_name,
  1144. scriptPath,
  1145. stack_name,
  1146. stack_version
  1147. )))
  1148. return retcode, out, err
  1149. return -2, "Wrong database", "Wrong database"
  1150. pass
  1151. #execute SQL script on remote database
  1152. def execute_remote_script(args, scriptPath):
  1153. tool = get_db_cli_tool(args)
  1154. if not tool:
  1155. # args.warnings.append('{0} not found. Please, run DDL script manually'.format(DATABASE_CLI_TOOLS[DATABASE_INDEX]))
  1156. if VERBOSE:
  1157. print_warning_msg('{0} not found'.format(DATABASE_CLI_TOOLS[DATABASE_INDEX]))
  1158. return -1, "Client wasn't found", "Client wasn't found"
  1159. if args.database == "postgres":
  1160. os.environ["PGPASSWORD"] = args.database_password
  1161. retcode, out, err = run_in_shell('{0} {1}'.format(tool, POSTGRES_EXEC_ARGS.format(
  1162. args.database_host,
  1163. args.database_port,
  1164. args.database_name,
  1165. args.database_username,
  1166. scriptPath
  1167. )))
  1168. return retcode, out, err
  1169. elif args.database == "oracle":
  1170. sid_or_sname = "sid"
  1171. if (hasattr(args, 'sid_or_sname') and args.sid_or_sname == "sname") or \
  1172. (hasattr(args, 'jdbc_url') and args.jdbc_url and re.match(ORACLE_SNAME_PATTERN, args.jdbc_url)):
  1173. print_info_msg("using SERVICE_NAME instead of SID for Oracle")
  1174. sid_or_sname = "service_name"
  1175. retcode, out, err = run_in_shell('{0} {1}'.format(tool, ORACLE_EXEC_ARGS.format(
  1176. args.database_username,
  1177. args.database_password,
  1178. args.database_host,
  1179. args.database_port,
  1180. args.database_name,
  1181. scriptPath,
  1182. sid_or_sname
  1183. )))
  1184. return retcode, out, err
  1185. elif args.database == "mysql":
  1186. MYSQL_EXEC_ARGS = MYSQL_EXEC_ARGS_WO_USER_VARS if MYSQL_INIT_SCRIPT == scriptPath else MYSQL_EXEC_ARGS_WITH_USER_VARS
  1187. retcode, out, err = run_in_shell('{0} {1}'.format(tool, MYSQL_EXEC_ARGS.format(
  1188. args.database_host,
  1189. args.database_port,
  1190. args.database_username,
  1191. args.database_password,
  1192. args.database_name,
  1193. scriptPath
  1194. )))
  1195. return retcode, out, err
  1196. return -2, "Wrong database", "Wrong database"
  1197. def prepare_stack_upgrade_command(args, stackId):
  1198. db_index = DATABASE_NAMES.index(args.database)
  1199. tool = DATABASE_CLI_TOOLS_DESC[db_index]
  1200. scriptPath = DATABASE_STACK_UPGRADE_SCRIPTS[db_index]
  1201. stack_name, stack_version = stackId.split(STACK_NAME_VER_SEP)
  1202. if args.database == "oracle":
  1203. sid_or_sname = "sid"
  1204. if (hasattr(args, 'sid_or_sname') and args.sid_or_sname == "sname") or \
  1205. (hasattr(args, 'jdbc_url') and args.jdbc_url and re.match(ORACLE_SNAME_PATTERN, args.jdbc_url)):
  1206. print_info_msg("using SERVICE_NAME instead of SID for Oracle")
  1207. sid_or_sname = "service_name"
  1208. command = '{0} {1}'.format(tool, ORACLE_UPGRADE_STACK_ARGS.format(
  1209. args.database_username,
  1210. args.database_password,
  1211. args.database_host,
  1212. args.database_port,
  1213. args.database_name,
  1214. scriptPath,
  1215. sid_or_sname,
  1216. stack_name,
  1217. stack_version
  1218. )).strip()
  1219. return command
  1220. elif args.database == "mysql":
  1221. command = '{0} {1}'.format(tool, MYSQL_UPGRADE_STACK_ARGS.format(
  1222. args.database_host,
  1223. args.database_port,
  1224. args.database_username,
  1225. args.database_password,
  1226. args.database_name,
  1227. scriptPath,
  1228. stack_name,
  1229. stack_version
  1230. )).strip()
  1231. return command
  1232. pass
  1233. def prepare_schema_upgrade_command(args):
  1234. db_index = DATABASE_NAMES.index(args.database)
  1235. tool = DATABASE_CLI_TOOLS_DESC[db_index]
  1236. scriptPath = DATABASE_UPGRADE_SCRIPTS[db_index]
  1237. if args.database == "postgres":
  1238. os.environ["PGPASSWORD"] = args.database_password
  1239. command = '{0} {1}'.format(tool, POSTGRES_EXEC_ARGS.format(
  1240. args.database_host,
  1241. args.database_port,
  1242. args.database_name,
  1243. args.database_username,
  1244. scriptPath
  1245. )).strip()
  1246. return command
  1247. elif args.database == "oracle":
  1248. sid_or_sname = "sid"
  1249. if (hasattr(args, 'sid_or_sname') and args.sid_or_sname == "sname") or \
  1250. (hasattr(args, 'jdbc_url') and args.jdbc_url and re.match(ORACLE_SNAME_PATTERN, args.jdbc_url)):
  1251. print_info_msg("using SERVICE_NAME instead of SID for Oracle")
  1252. sid_or_sname = "service_name"
  1253. command = '{0} {1}'.format(tool, ORACLE_EXEC_ARGS.format(
  1254. args.database_username,
  1255. args.database_password,
  1256. args.database_host,
  1257. args.database_port,
  1258. args.database_name,
  1259. scriptPath,
  1260. sid_or_sname
  1261. )).strip()
  1262. return command
  1263. elif args.database == "mysql":
  1264. MYSQL_EXEC_ARGS = MYSQL_EXEC_ARGS_WO_USER_VARS if MYSQL_INIT_SCRIPT == scriptPath else MYSQL_EXEC_ARGS_WITH_USER_VARS
  1265. command = '{0} {1}'.format(tool, MYSQL_EXEC_ARGS.format(
  1266. args.database_host,
  1267. args.database_port,
  1268. args.database_username,
  1269. args.database_password,
  1270. args.database_name,
  1271. scriptPath
  1272. )).strip()
  1273. return command
  1274. pass
  1275. def prepare_local_repo_upgrade_commands(args, dbkey, dbvalue):
  1276. db_index = DATABASE_NAMES.index(args.database)
  1277. tool = DATABASE_CLI_TOOLS_DESC[db_index]
  1278. scriptPath = DATABASE_INSERT_METAINFO_SCRIPTS[db_index]
  1279. command_list = []
  1280. if args.database == "oracle":
  1281. sid_or_sname = "sid"
  1282. if (hasattr(args, 'sid_or_sname') and args.sid_or_sname == "sname") or \
  1283. (hasattr(args, 'jdbc_url') and args.jdbc_url and re.match(ORACLE_SNAME_PATTERN, args.jdbc_url)):
  1284. print_info_msg("using SERVICE_NAME instead of SID for Oracle")
  1285. sid_or_sname = "service_name"
  1286. command_list.append('{0} {1}'.format(tool, ORACLE_UPGRADE_STACK_ARGS.format(
  1287. args.database_username,
  1288. args.database_password,
  1289. args.database_host,
  1290. args.database_port,
  1291. args.database_name,
  1292. scriptPath,
  1293. sid_or_sname,
  1294. dbkey,
  1295. dbvalue
  1296. )).strip())
  1297. command_list.append('{0} {1}'.format(tool, ORACLE_UPGRADE_STACK_ARGS.format(
  1298. args.database_username,
  1299. args.database_password,
  1300. args.database_host,
  1301. args.database_port,
  1302. args.database_name,
  1303. DATABASE_FIX_LOCAL_REPO_SCRIPTS[db_index],
  1304. sid_or_sname,
  1305. '',
  1306. ''
  1307. )).strip())
  1308. return command_list
  1309. def configure_database_password(showDefault=True):
  1310. passwordDefault = PG_DEFAULT_PASSWORD
  1311. if showDefault:
  1312. passwordPrompt = 'Enter Database Password (' + passwordDefault + '): '
  1313. else:
  1314. passwordPrompt = 'Enter Database Password: '
  1315. passwordPattern = "^[a-zA-Z0-9_-]*$"
  1316. passwordDescr = "Invalid characters in password. Use only alphanumeric or "\
  1317. "_ or - characters"
  1318. password = read_password(passwordDefault, passwordPattern, passwordPrompt,
  1319. passwordDescr)
  1320. return password
  1321. def check_database_name_property():
  1322. properties = get_ambari_properties()
  1323. if properties == -1:
  1324. print_error_msg ("Error getting ambari properties")
  1325. return -1
  1326. dbname = properties[JDBC_DATABASE_PROPERTY]
  1327. if dbname is None or dbname == "":
  1328. err = "DB Name property not set in config file.\n" + SETUP_OR_UPGRADE_MSG
  1329. raise FatalException(-1, err)
  1330. def configure_database_username_password(args):
  1331. properties = get_ambari_properties()
  1332. if properties == -1:
  1333. print_error_msg ("Error getting ambari properties")
  1334. return -1
  1335. username = properties[JDBC_USER_NAME_PROPERTY]
  1336. passwordProp = properties[JDBC_PASSWORD_PROPERTY]
  1337. dbname = properties[JDBC_DATABASE_PROPERTY]
  1338. if username and passwordProp and dbname:
  1339. print_info_msg("Database username + password already configured")
  1340. args.database_username=username
  1341. args.database_name = dbname
  1342. if is_alias_string(passwordProp):
  1343. args.database_password = decrypt_password_for_alias(JDBC_RCA_PASSWORD_ALIAS)
  1344. else:
  1345. if os.path.exists(passwordProp):
  1346. with open(passwordProp, 'r') as file:
  1347. args.database_password = file.read()
  1348. return 1
  1349. else:
  1350. print_error_msg("Connection properties not set in config file.")
  1351. # Check if jdbc user is changed
  1352. def is_jdbc_user_changed(args):
  1353. properties = get_ambari_properties()
  1354. if properties == -1:
  1355. print_error_msg ("Error getting ambari properties")
  1356. return None
  1357. previos_user = properties[JDBC_USER_NAME_PROPERTY]
  1358. new_user = args.database_username
  1359. if previos_user and new_user:
  1360. if previos_user != new_user:
  1361. return True
  1362. else:
  1363. return False
  1364. return None
  1365. # Store local database connection properties
  1366. def store_local_properties(args):
  1367. properties = get_ambari_properties()
  1368. if properties == -1:
  1369. print_error_msg ("Error getting ambari properties")
  1370. return -1
  1371. isSecure = get_is_secure(properties)
  1372. properties.removeOldProp(JDBC_SCHEMA_PROPERTY)
  1373. properties.removeOldProp(JDBC_HOSTNAME_PROPERTY)
  1374. properties.removeOldProp(JDBC_RCA_DRIVER_PROPERTY)
  1375. properties.removeOldProp(JDBC_RCA_URL_PROPERTY)
  1376. properties.removeOldProp(JDBC_PORT_PROPERTY)
  1377. properties.removeOldProp(JDBC_DRIVER_PROPERTY)
  1378. properties.removeOldProp(JDBC_URL_PROPERTY)
  1379. properties.process_pair(PERSISTENCE_TYPE_PROPERTY, "local")
  1380. properties.process_pair(JDBC_DATABASE_PROPERTY, args.database_name)
  1381. properties.process_pair(JDBC_USER_NAME_PROPERTY, args.database_username)
  1382. properties.process_pair(JDBC_PASSWORD_PROPERTY,
  1383. store_password_file(args.database_password, JDBC_PASSWORD_FILENAME))
  1384. if isSecure:
  1385. encrypted_password = encrypt_password(JDBC_RCA_PASSWORD_ALIAS, args.database_password)
  1386. if args.database_password != encrypted_password:
  1387. properties.process_pair(JDBC_PASSWORD_PROPERTY, encrypted_password)
  1388. pass
  1389. pass
  1390. conf_file = properties.fileName
  1391. try:
  1392. properties.store(open(conf_file, "w"))
  1393. except Exception, e:
  1394. print 'Unable to write ambari.properties configuration file "%s": %s' % (conf_file, e)
  1395. return -1
  1396. return 0
  1397. # Load ambari properties and return dict with values
  1398. def get_ambari_properties():
  1399. conf_file = find_properties_file()
  1400. properties = None
  1401. try:
  1402. properties = Properties()
  1403. properties.load(open(conf_file))
  1404. except (Exception), e:
  1405. print 'Could not read "%s": %s' % (conf_file, e)
  1406. return -1
  1407. return properties
  1408. # Load database connection properties from conf file
  1409. def parse_properties_file(args):
  1410. properties = get_ambari_properties()
  1411. if properties == -1:
  1412. print_error_msg ("Error getting ambari properties")
  1413. return -1
  1414. args.persistence_type = properties[PERSISTENCE_TYPE_PROPERTY]
  1415. args.jdbc_url = properties[JDBC_URL_PROPERTY]
  1416. if not args.persistence_type:
  1417. args.persistence_type = "local"
  1418. if args.persistence_type == 'remote':
  1419. args.database = properties[JDBC_DATABASE_PROPERTY]
  1420. args.database_host = properties[JDBC_HOSTNAME_PROPERTY]
  1421. args.database_port = properties[JDBC_PORT_PROPERTY]
  1422. args.database_name = properties[JDBC_SCHEMA_PROPERTY]
  1423. global DATABASE_INDEX
  1424. try:
  1425. DATABASE_INDEX = DATABASE_NAMES.index(args.database)
  1426. except ValueError:
  1427. pass
  1428. else:
  1429. #TODO incorrect property used!! leads to bunch of troubles. Workaround for now
  1430. args.database_name = properties[JDBC_DATABASE_PROPERTY]
  1431. args.database_username = properties[JDBC_USER_NAME_PROPERTY]
  1432. args.database_password_file = properties[JDBC_PASSWORD_PROPERTY]
  1433. if args.database_password_file:
  1434. if not is_alias_string(args.database_password_file):
  1435. args.database_password = open(properties[JDBC_PASSWORD_PROPERTY]).read()
  1436. else:
  1437. args.database_password = args.database_password_file
  1438. return 0
  1439. ### JDK ###
  1440. def get_ambari_jars():
  1441. try:
  1442. conf_dir = os.environ[AMBARI_SERVER_LIB]
  1443. return conf_dir
  1444. except KeyError:
  1445. default_jar_location = "/usr/lib/ambari-server"
  1446. print_info_msg(AMBARI_SERVER_LIB + " is not set, using default "
  1447. + default_jar_location)
  1448. return default_jar_location
  1449. def get_share_jars():
  1450. share_jars = ""
  1451. file_list = []
  1452. file_list.extend(glob.glob(JAVA_SHARE_PATH + os.sep + "*mysql*"))
  1453. file_list.extend(glob.glob(JAVA_SHARE_PATH + os.sep + "*ojdbc*"))
  1454. if len(file_list) > 0:
  1455. share_jars = string.join(file_list, os.pathsep)
  1456. return share_jars
  1457. def get_ambari_classpath():
  1458. ambari_cp = get_ambari_jars() + os.sep + "*"
  1459. share_cp = get_share_jars()
  1460. if len(share_cp) > 0:
  1461. ambari_cp = ambari_cp + os.pathsep + share_cp
  1462. return ambari_cp
  1463. def search_file(filename, search_path, pathsep=os.pathsep):
  1464. """ Given a search path, find file with requested name """
  1465. for path in string.split(search_path, pathsep):
  1466. candidate = os.path.join(path, filename)
  1467. if os.path.exists(candidate): return os.path.abspath(candidate)
  1468. return None
  1469. def dlprogress(base_name, count, blockSize, totalSize):
  1470. percent = int(count * blockSize * 100 / totalSize)
  1471. if (totalSize < blockSize):
  1472. sys.stdout.write("\r" + base_name + "... %d%%" % (100))
  1473. else:
  1474. sys.stdout.write("\r" + base_name + "... %d%% (%.1f MB of %.1f MB)" % (
  1475. percent, count * blockSize / 1024 / 1024.0, totalSize / 1024 / 1024.0))
  1476. if (percent == 100 or totalSize < blockSize):
  1477. sys.stdout.write("\n")
  1478. sys.stdout.flush()
  1479. def track_jdk(base_name, url, local_name):
  1480. u = urllib2.urlopen(url)
  1481. h = u.info()
  1482. totalSize = int(h["Content-Length"])
  1483. fp = open(local_name, "wb")
  1484. blockSize = 8192
  1485. count = 0
  1486. percent = 0
  1487. while True:
  1488. chunk = u.read(blockSize)
  1489. if not chunk:
  1490. break
  1491. fp.write(chunk)
  1492. count += 1
  1493. dlprogress(base_name, count, blockSize, totalSize)
  1494. fp.flush()
  1495. fp.close()
  1496. def install_jce_manualy(args):
  1497. properties = get_ambari_properties()
  1498. if properties == -1:
  1499. err = "Error getting ambari properties"
  1500. raise FatalException(-1, err)
  1501. if args.jce_policy:
  1502. if os.path.exists(args.jce_policy):
  1503. if os.path.isdir(args.jce_policy):
  1504. err = "JCE Policy path is a directory: " + args.jce_policy
  1505. raise FatalException(-1, err)
  1506. jce_destination = os.path.join(properties[RESOURCES_DIR_PROPERTY], JCE_POLICY_FILENAMES[JDK_INDEX])
  1507. try:
  1508. shutil.copy(args.jce_policy, jce_destination)
  1509. except Exception, e:
  1510. err = "Can not copy file {0} to {1} due to: {2}. Please check file " \
  1511. "permissions and free disk space.".format(args.jce_policy, jce_destination, e.message)
  1512. raise FatalException(-1, err)
  1513. print "JCE policy copied from " + args.jce_policy + " to " + jce_destination
  1514. return 0
  1515. else:
  1516. err = "JCE Policy path " + args.jce_policy + " doesn't exists."
  1517. raise FatalException(-1, err)
  1518. else:
  1519. return 1
  1520. #
  1521. # Downloads the JDK
  1522. #
  1523. def download_jdk(args):
  1524. global JDK_INDEX
  1525. ambari_setup_with_jdk_location = False
  1526. properties = get_ambari_properties()
  1527. if properties == -1:
  1528. err = "Error getting ambari properties"
  1529. raise FatalException(-1, err)
  1530. conf_file = properties.fileName
  1531. ok = False
  1532. jcePolicyWarn = "JCE Policy files are required for configuring Kerberos security. If you plan to use Kerberos," \
  1533. "please make sure JCE Unlimited Strength Jurisdiction Policy Files are valid on all hosts."
  1534. if args.java_home:
  1535. if not os.path.exists(args.java_home):
  1536. err = "Path to java home " + args.java_home + " does not exists"
  1537. raise FatalException(1, err)
  1538. jce_policy_paths = []
  1539. for jce_file in JCE_POLICY_FILENAMES:
  1540. jce_policy_path = os.path.join(properties[RESOURCES_DIR_PROPERTY], jce_file)
  1541. if os.path.exists(jce_policy_path):
  1542. jce_policy_paths.append(jce_policy_path)
  1543. if len(jce_policy_paths) > 0:
  1544. err = "Command failed to execute. Please remove or move " + str(jce_policy_paths).strip('[]') + " and retry again"
  1545. raise FatalException(1, err)
  1546. print_warning_msg("JAVA_HOME " + args.java_home + " must be valid on ALL hosts")
  1547. print_warning_msg(jcePolicyWarn)
  1548. write_property(JAVA_HOME_PROPERTY, args.java_home)
  1549. remove_property(JDK_NAME_PROPERTY)
  1550. remove_property(JCE_NAME_PROPERTY)
  1551. return 0
  1552. else:
  1553. if get_JAVA_HOME() and not args.jdk_location:
  1554. change_jdk = get_YN_input("Do you want to change Oracle JDK [y/n] (n)? ", False)
  1555. if not change_jdk:
  1556. return 0
  1557. try:
  1558. resources_dir = properties[RESOURCES_DIR_PROPERTY]
  1559. except (KeyError), e:
  1560. err = 'Property ' + str(e) + ' is not defined at ' + conf_file
  1561. raise FatalException(1, err)
  1562. ##JDK location was set by user with --jdk-location key
  1563. if args.jdk_location:
  1564. if not os.path.exists(args.jdk_location):
  1565. err = "Path to jdk " + args.jdk_location + " does not exists"
  1566. raise FatalException(1, err)
  1567. path, custom_jdk_name = os.path.split(args.jdk_location)
  1568. dest_file = resources_dir + os.sep + custom_jdk_name
  1569. print_warning_msg("JDK must be installed on all agent hosts and JAVA_HOME must be valid on all agent hosts.")
  1570. print_warning_msg(jcePolicyWarn)
  1571. print "Copying local JDK file {0} to {1}".format(args.jdk_location, dest_file)
  1572. try:
  1573. shutil.copyfile(args.jdk_location, dest_file)
  1574. except Exception, e:
  1575. err = "Can not copy file {0} to {1} due to: {2} . Please check file " \
  1576. "permissions and free disk space.".format(args.jdk_location, dest_file, e.message)
  1577. raise FatalException(1, err)
  1578. ambari_setup_with_jdk_location = True
  1579. remove_property(JDK_NAME_PROPERTY)
  1580. remove_property(JCE_NAME_PROPERTY)
  1581. else:
  1582. jdk_num = str(JDK_INDEX + 1)
  1583. jdk_num = get_validated_string_input(
  1584. "[1] - Oracle JDK 1.7\n[2] - Oracle JDK 1.6\n[3] - Custom JDK\n==============================================================================\nEnter choice (" + jdk_num + "): ",
  1585. jdk_num,
  1586. "^[123]$",
  1587. "Invalid number.",
  1588. False
  1589. )
  1590. if jdk_num == CUSTOM_JDK_NUMBER:
  1591. print_warning_msg("JDK must be installed on all hosts and JAVA_HOME must be valid on all hosts.")
  1592. print_warning_msg(jcePolicyWarn)
  1593. args.java_home = get_validated_string_input("Path to JAVA_HOME: ", None, None, None, False, False)
  1594. if not os.path.exists(args.java_home):
  1595. err = "Java home path is unavailable. Please put correct path to java home."
  1596. raise FatalException(1, err)
  1597. print "Validating JDK on Ambari Server...done."
  1598. write_property(JAVA_HOME_PROPERTY, args.java_home)
  1599. remove_property(JDK_NAME_PROPERTY)
  1600. remove_property(JCE_NAME_PROPERTY)
  1601. return 0
  1602. JDK_INDEX = int(jdk_num) -1
  1603. JDK_FILENAME = JDK_NAMES[JDK_INDEX]
  1604. JDK_URL_PROPERTY = JDK_URL_PROPERTIES[JDK_INDEX]
  1605. try:
  1606. jdk_url = properties[JDK_URL_PROPERTY]
  1607. except (KeyError), e:
  1608. err = 'Property ' + str(e) + ' is not defined at ' + conf_file
  1609. raise FatalException(1, err)
  1610. dest_file = resources_dir + os.sep + JDK_FILENAME
  1611. if os.path.exists(dest_file):
  1612. print "JDK already exists, using " + dest_file
  1613. else:
  1614. ok = get_YN_input("To download the Oracle JDK you must accept the "
  1615. "license terms found at "
  1616. "http://www.oracle.com/technetwork/java/javase/"
  1617. "terms/license/index.html and not accepting will "
  1618. "cancel the Ambari Server setup.\nDo you accept the "
  1619. "Oracle Binary Code License Agreement [y/n] (y)? ", True)
  1620. if not ok:
  1621. print 'Exiting...'
  1622. sys.exit(1)
  1623. print 'Downloading JDK from ' + jdk_url + ' to ' + dest_file
  1624. jdk_download_fail_msg = " Failed to download JDK: {0}. Please check that Oracle " \
  1625. "JDK is available at {1}. Also you may specify JDK file " \
  1626. "location in local filesystem using --jdk-location command " \
  1627. "line argument.".format("{0}", jdk_url)
  1628. try:
  1629. size_command = JDK_DOWNLOAD_SIZE_CMD.format(jdk_url);
  1630. #Get Header from url,to get file size then
  1631. retcode, out, err = run_os_command(size_command)
  1632. if out.find("Content-Length") == -1:
  1633. err = jdk_download_fail_msg.format("Request header doesn't contain Content-Length")
  1634. raise FatalException(1, err)
  1635. start_with = int(out.find("Content-Length") + len("Content-Length") + 2)
  1636. end_with = out.find("\r\n", start_with)
  1637. src_size = int(out[start_with:end_with])
  1638. print 'JDK distribution size is ' + str(src_size) + ' bytes'
  1639. file_exists = os.path.isfile(dest_file)
  1640. file_size = -1
  1641. if file_exists:
  1642. file_size = os.stat(dest_file).st_size
  1643. if file_exists and file_size == src_size:
  1644. print_info_msg("File already exists")
  1645. else:
  1646. track_jdk(JDK_FILENAME, jdk_url, dest_file)
  1647. print 'Successfully downloaded JDK distribution to ' + dest_file
  1648. except FatalException:
  1649. raise
  1650. except Exception, e:
  1651. err = jdk_download_fail_msg.format(str(e))
  1652. raise FatalException(1, err)
  1653. downloaded_size = os.stat(dest_file).st_size
  1654. if downloaded_size != src_size or downloaded_size < JDK_MIN_FILESIZE:
  1655. err = 'Size of downloaded JDK distribution file is ' \
  1656. + str(downloaded_size) + ' bytes, it is probably \
  1657. damaged or incomplete'
  1658. raise FatalException(1, err)
  1659. try:
  1660. out = install_jdk(dest_file)
  1661. jdk_version = re.search(JDK_VERSION_REs[JDK_INDEX], out).group(1)
  1662. if not ambari_setup_with_jdk_location:
  1663. write_property(JDK_NAME_PROPERTY, JDK_FILENAME)
  1664. except Exception, e:
  1665. print "Installation of JDK has failed: %s\n" % e.message
  1666. file_exists = os.path.isfile(dest_file)
  1667. if file_exists:
  1668. ok = get_YN_input("JDK found at "+dest_file+". "
  1669. "Would you like to re-download the JDK [y/n] (y)? ", True)
  1670. if not ok:
  1671. err = "Unable to install JDK. Please remove JDK file found at "+ \
  1672. dest_file +" and re-run Ambari Server setup"
  1673. raise FatalException(1, err)
  1674. else:
  1675. track_jdk(JDK_FILENAME, jdk_url, dest_file)
  1676. print 'Successfully re-downloaded JDK distribution to ' + dest_file
  1677. try:
  1678. out = install_jdk(dest_file)
  1679. jdk_version = re.search(JDK_VERSION_REs[JDK_INDEX], out).group(1)
  1680. if not ambari_setup_with_jdk_location:
  1681. write_property(JDK_NAME_PROPERTY, JDK_FILENAME)
  1682. except Exception, e:
  1683. print "Installation of JDK was failed: %s\n" % e.message
  1684. err = "Unable to install JDK. Please remove JDK, file found at "+ \
  1685. dest_file +" and re-run Ambari Server setup"
  1686. raise FatalException(1, err)
  1687. else:
  1688. err = "Unable to install JDK. File "+ dest_file +" does not exist, " \
  1689. "please re-run Ambari Server setup"
  1690. raise FatalException(1, err)
  1691. print "Successfully installed JDK to {0}/{1}".\
  1692. format(JDK_INSTALL_DIR, jdk_version)
  1693. write_property(JAVA_HOME_PROPERTY, "{0}/{1}".
  1694. format(JDK_INSTALL_DIR, jdk_version))
  1695. try:
  1696. if not ambari_setup_with_jdk_location:
  1697. download_jce_policy(properties, ok)
  1698. except FatalException as e:
  1699. print "JCE Policy files are required for secure HDP setup. Please ensure " \
  1700. " all hosts have the JCE unlimited strength policy 6, files."
  1701. print_error_msg("Failed to download JCE policy files:")
  1702. if e.reason is not None:
  1703. print_error_msg("\nREASON: {0}".format(e.reason))
  1704. # TODO: We don't fail installation if download_jce_policy fails. Is it OK?
  1705. return 0
  1706. def download_jce_policy(properties, accpeted_bcl):
  1707. JCE_URL_PROPERTY = JCE_URL_PROPERTIES[JDK_INDEX]
  1708. JCE_POLICY_FILENAME = JCE_POLICY_FILENAMES[JDK_INDEX]
  1709. try:
  1710. jce_url = properties[JCE_URL_PROPERTY]
  1711. resources_dir = properties[RESOURCES_DIR_PROPERTY]
  1712. except KeyError, e:
  1713. err = 'Property ' + str(e) + ' is not defined in properties file'
  1714. raise FatalException(1, err)
  1715. dest_file = resources_dir + os.sep + JCE_POLICY_FILENAME
  1716. if not os.path.exists(dest_file):
  1717. print 'Downloading JCE Policy archive from ' + jce_url + ' to ' + dest_file
  1718. jce_download_fail_msg = " Failed to download JCE Policy archive : {0}. " \
  1719. "Please check that JCE Policy archive is available at {1} . "
  1720. try:
  1721. size_command = JDK_DOWNLOAD_SIZE_CMD.format(jce_url);
  1722. #Get Header from url,to get file size then
  1723. retcode, out, err = run_os_command(size_command)
  1724. if out.find("Content-Length") == -1:
  1725. err = jce_download_fail_msg.format(
  1726. "Request header doesn't contain Content-Length")
  1727. raise FatalException(1, err)
  1728. start_with = int(out.find("Content-Length") + len("Content-Length") + 2)
  1729. end_with = out.find("\r\n", start_with)
  1730. src_size = int(out[start_with:end_with])
  1731. print_info_msg('JCE zip distribution size is ' + str(src_size) + ' bytes')
  1732. file_exists = os.path.isfile(dest_file)
  1733. file_size = -1
  1734. if file_exists:
  1735. file_size = os.stat(dest_file).st_size
  1736. if file_exists and file_size == src_size:
  1737. print_info_msg("File already exists")
  1738. else:
  1739. #BCL license before download
  1740. jce_download_cmd = JCE_DOWNLOAD_CMD.format(dest_file, jce_url)
  1741. print_info_msg("JCE download cmd: " + jce_download_cmd)
  1742. if accpeted_bcl:
  1743. retcode, out, err = run_os_command(jce_download_cmd)
  1744. if retcode == 0:
  1745. write_property(JCE_NAME_PROPERTY, JCE_POLICY_FILENAME)
  1746. print 'Successfully downloaded JCE Policy archive to ' + dest_file
  1747. else:
  1748. raise FatalException(1, err)
  1749. else:
  1750. ok = get_YN_input("To download the JCE Policy files you must "
  1751. "accept the license terms found at "
  1752. "http://www.oracle.com/technetwork/java/javase"
  1753. "/terms/license/index.html"
  1754. "Not accepting will result in errors when "
  1755. "configuring Kerberos security. \nDo you accept the "
  1756. "Oracle Binary Code License Agreement [y/n] (y)? ", True)
  1757. if ok:
  1758. retcode, out, err = run_os_command(jce_download_cmd)
  1759. if retcode == 0:
  1760. write_property(JCE_NAME_PROPERTY, JCE_POLICY_FILENAME)
  1761. print 'Successfully downloaded JCE Policy archive to ' + dest_file
  1762. else:
  1763. raise FatalException(1, None)
  1764. except FatalException:
  1765. raise
  1766. except Exception, e:
  1767. err = 'Failed to download JCE Policy archive: ' + str(e)
  1768. raise FatalException(1, err)
  1769. downloaded_size = os.stat(dest_file).st_size
  1770. if downloaded_size != src_size or downloaded_size < JCE_MIN_FILESIZE:
  1771. err = 'Size of downloaded JCE Policy archive is ' \
  1772. + str(downloaded_size) + ' bytes, it is probably \
  1773. damaged or incomplete'
  1774. raise FatalException(1, err)
  1775. else:
  1776. write_property(JCE_NAME_PROPERTY, JCE_POLICY_FILENAME)
  1777. print "JCE Policy archive already exists, using " + dest_file
  1778. class RetCodeException(Exception): pass
  1779. def install_jdk(dest_file):
  1780. print "Installing JDK to {0}".format(JDK_INSTALL_DIR)
  1781. retcode, out, err = run_os_command(CREATE_JDK_DIR_CMD)
  1782. savedPath = os.getcwd()
  1783. os.chdir(JDK_INSTALL_DIR)
  1784. if dest_file.endswith(".bin"):
  1785. retcode, out, err = run_os_command(MAKE_FILE_EXECUTABLE_CMD.format(dest_file))
  1786. retcode, out, err = run_os_command(dest_file + ' -noregister')
  1787. elif dest_file.endswith(".gz"):
  1788. retcode, out, err = run_os_command(UNTAR_JDK_ARVHIVE.format(dest_file))
  1789. else:
  1790. err = "JDK installation failed.Unknown file mask."
  1791. raise FatalException(1, err)
  1792. os.chdir(savedPath)
  1793. if retcode != 0:
  1794. err = "Installation of JDK returned exit code %s" % retcode
  1795. raise FatalException(retcode, err)
  1796. return out
  1797. #
  1798. # Configures the OS settings in ambari properties.
  1799. #
  1800. def configure_os_settings():
  1801. properties = get_ambari_properties()
  1802. if properties == -1:
  1803. print_error_msg ("Error getting ambari properties")
  1804. return -1
  1805. try:
  1806. conf_os_type = properties[OS_TYPE_PROPERTY]
  1807. if conf_os_type != '':
  1808. print_info_msg ("os_type already setting in properties file")
  1809. return 0
  1810. except (KeyError), e:
  1811. print_error_msg ("os_type is not set in properties file")
  1812. os_system = platform.system()
  1813. if os_system != 'Linux':
  1814. print_error_msg ("Non-Linux systems are not supported")
  1815. return -1
  1816. os_info = platform.linux_distribution(
  1817. None, None, None, ['SuSE', 'redhat' ], 0
  1818. )
  1819. os_name = os_info[0].lower()
  1820. if os_name == 'suse':
  1821. os_name = 'sles'
  1822. os_version = os_info[1].split('.', 1)[0]
  1823. master_os_type = os_name + os_version
  1824. write_property(OS_TYPE_PROPERTY, master_os_type)
  1825. return 0
  1826. def get_JAVA_HOME():
  1827. properties = get_ambari_properties()
  1828. if properties == -1:
  1829. print_error_msg ("Error getting ambari properties")
  1830. return None
  1831. java_home = properties[JAVA_HOME_PROPERTY]
  1832. if (not 0 == len(java_home)) and (os.path.exists(java_home)):
  1833. return java_home
  1834. return None
  1835. #
  1836. # Finds the available JDKs.
  1837. #
  1838. def find_jdk():
  1839. if get_JAVA_HOME():
  1840. return get_JAVA_HOME()
  1841. print "Looking for available JDKs at " + JDK_INSTALL_DIR
  1842. jdks = glob.glob(JDK_INSTALL_DIR + os.sep + "jdk*")
  1843. jdks.sort()
  1844. print "Found: " + str(jdks)
  1845. count = len(jdks)
  1846. if count == 0:
  1847. return
  1848. jdkPath = jdks[count - 1]
  1849. print "Selected JDK {0}".format(jdkPath)
  1850. return jdkPath
  1851. #
  1852. # Checks if options determine local DB configuration
  1853. #
  1854. def is_local_database(options):
  1855. if options.database == DATABASE_NAMES[0] \
  1856. and options.database_host == "localhost" \
  1857. and options.database_port == DATABASE_PORTS[0]:
  1858. return True
  1859. return False
  1860. #Check if required jdbc drivers present
  1861. def find_jdbc_driver(args):
  1862. if args.database in JDBC_PATTERNS.keys():
  1863. drivers = []
  1864. drivers.extend(glob.glob(JAVA_SHARE_PATH + os.sep + JDBC_PATTERNS[args.database]))
  1865. if drivers:
  1866. return drivers
  1867. return -1
  1868. return 0
  1869. def copy_file(src, dest_file):
  1870. try:
  1871. shutil.copyfile(src, dest_file)
  1872. except Exception, e:
  1873. err = "Can not copy file {0} to {1} due to: {2} . Please check file " \
  1874. "permissions and free disk space.".format(src, dest_file, e.message)
  1875. raise FatalException(1, err)
  1876. def remove_file(filePath):
  1877. if os.path.exists(filePath):
  1878. try:
  1879. os.remove(filePath)
  1880. except Exception, e:
  1881. print_warning_msg('Unable to remove file: ' + str(e))
  1882. return 1
  1883. pass
  1884. return 0
  1885. def copy_files(files, dest_dir):
  1886. if os.path.isdir(dest_dir):
  1887. for filepath in files:
  1888. shutil.copy(filepath, dest_dir)
  1889. return 0
  1890. else:
  1891. return -1
  1892. def check_jdbc_drivers(args):
  1893. properties = get_ambari_properties()
  1894. if properties == -1:
  1895. print_error_msg ("Error getting ambari properties")
  1896. return -1
  1897. result = find_jdbc_driver(args)
  1898. msg = 'Before starting Ambari Server, ' \
  1899. 'you must copy the {0} JDBC driver JAR file to {1}.'.format(
  1900. DATABASE_FULL_NAMES[args.database],
  1901. JAVA_SHARE_PATH)
  1902. if result == -1:
  1903. if SILENT:
  1904. print_error_msg(msg)
  1905. raise FatalException(-1, msg)
  1906. else:
  1907. print_warning_msg(msg)
  1908. raw_input(PRESS_ENTER_MSG)
  1909. result = find_jdbc_driver(args)
  1910. if result == -1:
  1911. print_error_msg(msg)
  1912. raise FatalException(-1, msg)
  1913. # Check if selected RDBMS requires drivers to copy
  1914. if type(result) is not int:
  1915. print 'Copying JDBC drivers to server resources...'
  1916. try:
  1917. resources_dir = properties[RESOURCES_DIR_PROPERTY]
  1918. except KeyError:
  1919. print_error_msg("There is no value for " + RESOURCES_DIR_PROPERTY + "in " + AMBARI_PROPERTIES_FILE)
  1920. return -1
  1921. copy_status = copy_files(result, resources_dir)
  1922. if not copy_status == 0:
  1923. raise FatalException(-1, "Failed to copy JDBC drivers to server resources")
  1924. return 0
  1925. def verify_setup_allowed():
  1926. properties = get_ambari_properties()
  1927. if properties == -1:
  1928. print_error_msg ("Error getting ambari properties")
  1929. return -1
  1930. isSecure = get_is_secure(properties)
  1931. (isPersisted, masterKeyFile) = get_is_persisted(properties)
  1932. if isSecure and not isPersisted and SILENT:
  1933. print "ERROR: Cannot run silent 'setup' with password encryption enabled " \
  1934. "and Master Key not persisted."
  1935. print "Ambari Server 'setup' exiting."
  1936. return 1
  1937. return 0
  1938. #
  1939. # Setup the Ambari Server.
  1940. #
  1941. def setup(args):
  1942. retcode = verify_setup_allowed()
  1943. if not retcode == 0:
  1944. raise FatalException(1, None)
  1945. if not is_root():
  1946. err = 'Ambari-server setup should be run with '\
  1947. 'root-level privileges'
  1948. raise FatalException(4, err)
  1949. print 'Checking SELinux...'
  1950. retcode = check_selinux()
  1951. if not retcode == 0:
  1952. err = 'Failed to disable SELinux. Exiting.'
  1953. raise FatalException(retcode, err)
  1954. # Create ambari user, if needed
  1955. retcode = check_ambari_user()
  1956. if not retcode == 0:
  1957. err = 'Failed to create user. Exiting.'
  1958. raise FatalException(retcode, err)
  1959. print 'Checking iptables...'
  1960. check_iptables()
  1961. print 'Checking JDK...'
  1962. try:
  1963. download_jdk(args)
  1964. except FatalException as e:
  1965. err = 'Downloading or installing JDK failed: {0}. Exiting.'.format(e)
  1966. raise FatalException(e.code, err)
  1967. print 'Completing setup...'
  1968. retcode = configure_os_settings()
  1969. if not retcode == 0:
  1970. err = 'Configure of OS settings in ambari.properties failed. Exiting.'
  1971. raise FatalException(retcode, err)
  1972. print 'Configuring database...'
  1973. prompt_db_properties(args)
  1974. #DB setup should be done last after doing any setup.
  1975. if is_local_database(args):
  1976. #check if jdbc user is changed
  1977. is_user_changed = is_jdbc_user_changed(args)
  1978. print 'Default properties detected. Using built-in database.'
  1979. store_local_properties(args)
  1980. print 'Checking PostgreSQL...'
  1981. retcode = check_postgre_up()
  1982. if not retcode == 0:
  1983. err = 'Unable to start PostgreSQL server. Exiting'
  1984. raise FatalException(retcode, err)
  1985. print 'Configuring local database...'
  1986. retcode, outdata, errdata = setup_db(args)
  1987. if not retcode == 0:
  1988. err = 'Running database init script was failed. Exiting.'
  1989. raise FatalException(retcode, err)
  1990. if is_user_changed:
  1991. #remove backup for pg_hba in order to reconfigure postgres
  1992. remove_file(PG_HBA_CONF_FILE_BACKUP)
  1993. print 'Configuring PostgreSQL...'
  1994. retcode = configure_postgres()
  1995. if not retcode == 0:
  1996. err = 'Unable to configure PostgreSQL server. Exiting'
  1997. raise FatalException(retcode, err)
  1998. else:
  1999. retcode = store_remote_properties(args)
  2000. if retcode != 0:
  2001. err = 'Unable to save config file'
  2002. raise FatalException(retcode, err)
  2003. check_jdbc_drivers(args)
  2004. print 'Configuring remote database connection properties...'
  2005. retcode = setup_remote_db(args)
  2006. if retcode == -1:
  2007. err = "The cli was not found"
  2008. raise NonFatalException(err)
  2009. if not retcode == 0:
  2010. err = 'Error while configuring connection properties. Exiting'
  2011. raise FatalException(retcode, err)
  2012. check_jdbc_drivers(args)
  2013. #
  2014. # Resets the Ambari Server.
  2015. #
  2016. def reset(args):
  2017. #force reset if silent option provided
  2018. global SILENT
  2019. if SILENT:
  2020. default = "yes"
  2021. else:
  2022. default = "no"
  2023. if not is_root():
  2024. err = 'Ambari-server reset should be run with ' \
  2025. 'root-level privileges'
  2026. raise FatalException(4, err)
  2027. status, pid = is_server_runing()
  2028. if status:
  2029. err = 'Ambari-server must be stopped to reset'
  2030. raise FatalException(1, err)
  2031. choice = get_YN_input("**** WARNING **** You are about to reset and clear the "
  2032. "Ambari Server database. This will remove all cluster "
  2033. "host and configuration information from the database. "
  2034. "You will be required to re-configure the Ambari server "
  2035. "and re-run the cluster wizard. \n"
  2036. "Are you SURE you want to perform the reset "
  2037. "[yes/no] ({0})? ".format(default), SILENT)
  2038. okToRun = choice
  2039. if not okToRun:
  2040. err = "Ambari Server 'reset' cancelled"
  2041. raise FatalException(1, err)
  2042. okToRun = get_YN_input("Confirm server reset [yes/no]({0})? ".format(default), SILENT)
  2043. if not okToRun:
  2044. err = "Ambari Server 'reset' cancelled"
  2045. raise FatalException(1, err)
  2046. print "Resetting the Server database..."
  2047. check_database_name_property()
  2048. parse_properties_file(args)
  2049. # configure_database_username_password(args)
  2050. if args.persistence_type=="remote":
  2051. client_desc = DATABASE_NAMES[DATABASE_INDEX] + ' ' + DATABASE_CLI_TOOLS_DESC[DATABASE_INDEX]
  2052. client_usage_cmd_drop = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_DROP_SCRIPTS[DATABASE_INDEX], args.database_username,
  2053. BLIND_PASSWORD, args.database_name)
  2054. client_usage_cmd_init = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_INIT_SCRIPTS[DATABASE_INDEX], args.database_username,
  2055. BLIND_PASSWORD, args.database_name)
  2056. if get_db_cli_tool(args) != -1:
  2057. retcode, out, err = execute_remote_script(args, DATABASE_DROP_SCRIPTS[DATABASE_INDEX])
  2058. if not retcode == 0:
  2059. if retcode == -1:
  2060. print_warning_msg('Cannot find ' + client_desc +
  2061. ' client in the path to reset the Ambari Server ' +
  2062. 'schema. To reset Ambari Server schema ' +
  2063. 'you must run the following DDL against the database ' +
  2064. 'to drop the schema:' + os.linesep + client_usage_cmd_drop
  2065. + os.linesep + 'Then you must run the following DDL '
  2066. + 'against the database to create the schema: ' + os.linesep
  2067. + client_usage_cmd_init + os.linesep )
  2068. raise NonFatalException(err)
  2069. if err:
  2070. print_warning_msg(err)
  2071. retcode, out, err = execute_remote_script(args, DATABASE_INIT_SCRIPTS[DATABASE_INDEX])
  2072. if not retcode == 0:
  2073. if retcode == -1:
  2074. print_warning_msg('Cannot find ' + client_desc + ' client in the path to ' +
  2075. 'reset the Ambari Server schema. To reset Ambari Server schema ' +
  2076. 'you must run the following DDL against the database to '
  2077. + 'drop the schema:' + os.linesep + client_usage_cmd_drop
  2078. + os.linesep + 'Then you must run the following DDL ' +
  2079. 'against the database to create the schema: ' + os.linesep +
  2080. client_usage_cmd_init + os.linesep )
  2081. raise NonFatalException(err)
  2082. if err:
  2083. print_warning_msg(err)
  2084. else:
  2085. err = 'Cannot find ' + client_desc + ' client in the path to reset the Ambari ' +\
  2086. 'Server schema. To reset Ambari Server schema ' + \
  2087. 'you must run the following DDL against the database to drop the schema:' + \
  2088. os.linesep + client_usage_cmd_drop + os.linesep + \
  2089. 'Then you must run the following DDL against the database to create the ' + \
  2090. 'schema: ' + os.linesep + client_usage_cmd_init + os.linesep
  2091. raise NonFatalException(err)
  2092. else:
  2093. dbname = args.database_name
  2094. filename = args.drop_script_file
  2095. username = args.database_username
  2096. password = args.database_password
  2097. command = SETUP_DB_CMD[:]
  2098. command[-1] = command[-1].format(filename, username, password, dbname)
  2099. drop_retcode, drop_outdata, drop_errdata = run_os_command(command)
  2100. if not drop_retcode == 0:
  2101. raise FatalException(1, drop_errdata)
  2102. if drop_errdata and PG_ERROR_BLOCKED in drop_errdata:
  2103. raise FatalException(1, "Database is in use. Please, make sure all connections to the database are closed")
  2104. if drop_errdata and VERBOSE:
  2105. print_warning_msg(drop_errdata)
  2106. print_info_msg ("About to run database setup")
  2107. retcode, outdata, errdata = setup_db(args)
  2108. if errdata and VERBOSE:
  2109. print_warning_msg(errdata)
  2110. if (errdata and 'ERROR' in errdata.upper()) or (drop_errdata and 'ERROR' in drop_errdata.upper()):
  2111. if not VERBOSE:
  2112. raise NonFatalException("Non critical error in DDL, use --verbose for more information")
  2113. else:
  2114. raise NonFatalException("Non critical error in DDL")
  2115. #
  2116. # Starts the Ambari Server.
  2117. #
  2118. def start(args):
  2119. current_user = getpass.getuser()
  2120. ambari_user = read_ambari_user()
  2121. if ambari_user is None:
  2122. err = "Unable to detect a system user for Ambari Server.\n" + SETUP_OR_UPGRADE_MSG
  2123. raise FatalException(1, err)
  2124. if current_user != ambari_user and not is_root():
  2125. err = "Unable to start Ambari Server as user {0}. Please either run \"ambari-server start\" " \
  2126. "command as root, as sudo or as user \"{1}\"".format(current_user, ambari_user)
  2127. raise FatalException(1, err)
  2128. check_database_name_property()
  2129. parse_properties_file(args)
  2130. status, pid = is_server_runing()
  2131. if status:
  2132. err = "Ambari Server is already running."
  2133. raise FatalException(1, err)
  2134. print_info_msg("Ambari Server is not running...")
  2135. conf_dir = get_conf_dir()
  2136. jdk_path = find_jdk()
  2137. if jdk_path is None:
  2138. err = "No JDK found, please run the \"ambari-server setup\" " \
  2139. "command to install a JDK automatically or install any " \
  2140. "JDK manually to " + JDK_INSTALL_DIR
  2141. raise FatalException(1, err)
  2142. if args.persistence_type == 'remote':
  2143. result = find_jdbc_driver(args)
  2144. msg = 'Before starting Ambari Server, ' \
  2145. 'you must copy the {0} JDBC driver JAR file to {1}.'.format(
  2146. DATABASE_FULL_NAMES[args.database],
  2147. JAVA_SHARE_PATH)
  2148. if result == -1:
  2149. raise FatalException(-1, msg)
  2150. # Preparations
  2151. if is_root():
  2152. print "Ambari Server running with 'root' privileges."
  2153. if args.persistence_type == "local":
  2154. retcode = check_postgre_up()
  2155. if not retcode == 0:
  2156. err = "Unable to start PostgreSQL server. Exiting"
  2157. raise FatalException(retcode, err)
  2158. else: # Skipping actions that require root permissions
  2159. print "Unable to check iptables status when starting "\
  2160. "without root privileges."
  2161. print "Please do not forget to disable or adjust iptables if needed"
  2162. if args.persistence_type == "local":
  2163. print "Unable to check PostgreSQL server status when starting " \
  2164. "without root privileges."
  2165. print "Please do not forget to start PostgreSQL server."
  2166. properties = get_ambari_properties()
  2167. isSecure = get_is_secure(properties)
  2168. (isPersisted, masterKeyFile) = get_is_persisted(properties)
  2169. environ = os.environ.copy()
  2170. # Need to handle master key not persisted scenario
  2171. if isSecure and not masterKeyFile:
  2172. prompt = False
  2173. masterKey = environ.get(SECURITY_KEY_ENV_VAR_NAME)
  2174. if masterKey is not None and masterKey != "":
  2175. pass
  2176. else:
  2177. keyLocation = environ.get(SECURITY_MASTER_KEY_LOCATION)
  2178. if keyLocation is not None:
  2179. try:
  2180. # Verify master key can be read by the java process
  2181. with open(keyLocation, 'r') : pass
  2182. except IOError:
  2183. print_warning_msg("Cannot read Master key from path specified in "
  2184. "environemnt.")
  2185. prompt = True
  2186. else:
  2187. # Key not provided in the environment
  2188. prompt = True
  2189. if prompt:
  2190. masterKey = get_original_master_key(properties)
  2191. tempDir = tempfile.gettempdir()
  2192. tempFilePath = tempDir + os.sep + "masterkey"
  2193. save_master_key(masterKey, tempFilePath, True)
  2194. if ambari_user != current_user:
  2195. uid = pwd.getpwnam(ambari_user).pw_uid
  2196. gid = pwd.getpwnam(ambari_user).pw_gid
  2197. os.chown(tempFilePath, uid, gid)
  2198. else:
  2199. os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)
  2200. if tempFilePath is not None:
  2201. environ[SECURITY_MASTER_KEY_LOCATION] = tempFilePath
  2202. pidfile = PID_DIR + os.sep + PID_NAME
  2203. command_base = SERVER_START_CMD_DEBUG if (SERVER_DEBUG_MODE or SERVER_START_DEBUG) else SERVER_START_CMD
  2204. command = command_base.format(jdk_path, conf_dir, get_ambari_classpath(), pidfile)
  2205. if is_root() and ambari_user != "root":
  2206. # To inherit exported environment variables (especially AMBARI_PASSPHRASE),
  2207. # from subprocess, we have to skip --login option of su command. That's why
  2208. # we change dir to / (otherwise subprocess can face with 'permission denied'
  2209. # errors while trying to list current directory
  2210. os.chdir("/")
  2211. param_list = ["/bin/su", ambari_user, "-s", "/bin/sh", "-c", command]
  2212. else:
  2213. param_list = ["/bin/sh", "-c", command]
  2214. print_info_msg ("Running server: " + str(param_list))
  2215. server_process = subprocess.Popen(param_list, env=environ)
  2216. print "Server PID at: "+pidfile
  2217. print "Server out at: "+SERVER_OUT_FILE
  2218. print "Server log at: "+SERVER_LOG_FILE
  2219. #
  2220. # Stops the Ambari Server.
  2221. #
  2222. def stop(args):
  2223. if (args != None):
  2224. args.exit_message = None
  2225. status, pid = is_server_runing()
  2226. if status:
  2227. try:
  2228. os.killpg(os.getpgid(pid), signal.SIGKILL)
  2229. except OSError, e:
  2230. print_info_msg( "Unable to stop Ambari Server - " + str(e) )
  2231. return
  2232. pid_file_path = PID_DIR + os.sep + PID_NAME
  2233. os.remove(pid_file_path)
  2234. print "Ambari Server stopped"
  2235. else:
  2236. print "Ambari Server is not running"
  2237. ### Stack upgrade ###
  2238. def upgrade_stack(args, stack_id):
  2239. if not is_root():
  2240. err = 'Ambari-server upgradestack should be run with ' \
  2241. 'root-level privileges'
  2242. raise FatalException(4, err)
  2243. check_database_name_property()
  2244. parse_properties_file(args)
  2245. if args.persistence_type == "remote":
  2246. client_desc = DATABASE_NAMES[DATABASE_INDEX] + ' ' + DATABASE_CLI_TOOLS_DESC[DATABASE_INDEX]
  2247. client_usage_cmd = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_STACK_UPGRADE_SCRIPTS[DATABASE_INDEX], args.database_username,
  2248. BLIND_PASSWORD, args.database_name)
  2249. #TODO temporarty code
  2250. if not args.database in ["oracle", "mysql"]:
  2251. raise FatalException(-20, "Upgrade for remote database only supports Oracle.")
  2252. if get_db_cli_tool(args):
  2253. retcode, out, err = remote_stack_upgrade(args, DATABASE_STACK_UPGRADE_SCRIPTS[DATABASE_INDEX], stack_id)
  2254. if not retcode == 0:
  2255. raise NonFatalException(err)
  2256. else:
  2257. command = prepare_stack_upgrade_command(args, stack_id)
  2258. err = 'Cannot find ' + client_desc + ' client in the path to upgrade the Ambari ' + \
  2259. 'Server stack. To upgrade stack of Ambari Server ' + \
  2260. 'you must run the following command:' + \
  2261. os.linesep + command
  2262. args.warnings.append(err)
  2263. pass
  2264. else:
  2265. #password access to ambari-server and mapred
  2266. configure_database_username_password(args)
  2267. dbname = args.database_name
  2268. file = args.upgrade_stack_script_file
  2269. stack_name, stack_version = stack_id.split(STACK_NAME_VER_SEP)
  2270. command = UPGRADE_STACK_CMD[:]
  2271. command[-1] = command[-1].format(file, stack_name, stack_version, dbname)
  2272. retcode, outdata, errdata = run_os_command(command)
  2273. if not retcode == 0:
  2274. raise FatalException(retcode, errdata)
  2275. if errdata:
  2276. print_warning_msg(errdata)
  2277. return retcode
  2278. def load_stack_values(version, filename):
  2279. import xml.etree.ElementTree as ET
  2280. values = {}
  2281. root = ET.parse(filename).getroot()
  2282. for ostag in root:
  2283. ostype = ostag.attrib['type']
  2284. for repotag in ostag:
  2285. reponametag = repotag.find('reponame')
  2286. repoidtag = repotag.find('repoid')
  2287. baseurltag = repotag.find('baseurl')
  2288. if reponametag is not None and repoidtag is not None and baseurltag is not None:
  2289. key = "repo:/" + reponametag.text
  2290. key += "/" + version
  2291. key += "/" + ostype
  2292. key += "/" + repoidtag.text
  2293. key += ":baseurl"
  2294. values[key] = baseurltag.text
  2295. return values
  2296. def upgrade_local_repo_remote_db(args, sqlfile, dbkey, dbvalue):
  2297. tool = get_db_cli_tool(args)
  2298. if not tool:
  2299. # args.warnings.append('{0} not found. Please, run DDL script manually'.format(DATABASE_CLI_TOOLS[DATABASE_INDEX]))
  2300. if VERBOSE:
  2301. print_warning_msg('{0} not found'.format(DATABASE_CLI_TOOLS[DATABASE_INDEX]))
  2302. return -1, "Client wasn't found", "Client wasn't found"
  2303. #TODO add support of other databases with scripts
  2304. if args.database == "oracle":
  2305. sid_or_sname = "sid"
  2306. if (hasattr(args, 'sid_or_sname') and args.sid_or_sname == "sname") or \
  2307. (hasattr(args, 'jdbc_url') and args.jdbc_url and re.match(ORACLE_SNAME_PATTERN, args.jdbc_url)):
  2308. print_info_msg("using SERVICE_NAME instead of SID for Oracle")
  2309. sid_or_sname = "service_name"
  2310. retcode, out, err = run_in_shell('{0} {1}'.format(tool, ORACLE_UPGRADE_STACK_ARGS.format(
  2311. args.database_username,
  2312. args.database_password,
  2313. args.database_host,
  2314. args.database_port,
  2315. args.database_name,
  2316. sqlfile,
  2317. sid_or_sname,
  2318. dbkey,
  2319. dbvalue
  2320. )))
  2321. retcode, out, err = run_in_shell('{0} {1}'.format(tool, ORACLE_UPGRADE_STACK_ARGS.format(
  2322. args.database_username,
  2323. args.database_password,
  2324. args.database_host,
  2325. args.database_port,
  2326. args.database_name,
  2327. DATABASE_FIX_LOCAL_REPO_SCRIPTS[DATABASE_INDEX],
  2328. sid_or_sname,
  2329. '',
  2330. ''
  2331. )))
  2332. return retcode, out, err
  2333. return -2, "Wrong database", "Wrong database"
  2334. pass
  2335. def upgrade_local_repo_db(args, dbkey, dbvalue):
  2336. if not is_root():
  2337. err = 'Ambari-server upgrade_local_repo_db should be run with ' \
  2338. 'root-level privileges'
  2339. raise FatalException(4, err)
  2340. check_database_name_property()
  2341. parse_properties_file(args)
  2342. if args.persistence_type == "remote":
  2343. client_desc = DATABASE_NAMES[DATABASE_INDEX] + ' ' + DATABASE_CLI_TOOLS_DESC[DATABASE_INDEX]
  2344. client_usage_cmd = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_INSERT_METAINFO_SCRIPTS[DATABASE_INDEX], args.database_username,
  2345. BLIND_PASSWORD, args.database_name)
  2346. #TODO temporary code
  2347. if not args.database == "oracle":
  2348. raise FatalException(-20, "Upgrade for remote database only supports Oracle.")
  2349. if get_db_cli_tool(args):
  2350. retcode, out, err = upgrade_local_repo_remote_db(args, DATABASE_INSERT_METAINFO_SCRIPTS[DATABASE_INDEX],
  2351. dbkey, dbvalue)
  2352. if not retcode == 0:
  2353. raise NonFatalException(err)
  2354. else:
  2355. commands = prepare_local_repo_upgrade_commands(args, dbkey, dbvalue)
  2356. err = 'Cannot find ' + client_desc + ' client in the path to upgrade the local ' + \
  2357. 'repo information. To upgrade local repo information. ' + \
  2358. 'you must run the following commands:'
  2359. for command in commands:
  2360. err = err + os.linesep + command
  2361. pass
  2362. args.warnings.append(err)
  2363. pass
  2364. else:
  2365. #password access to ambari-server and mapred
  2366. configure_database_username_password(args)
  2367. dbname = args.database_name
  2368. sqlfile = DATABASE_INSERT_METAINFO_SCRIPTS[0]
  2369. command = INSERT_METAINFO_CMD[:]
  2370. command[-1] = command[-1].format(sqlfile, dbkey, dbvalue, dbname)
  2371. retcode, outdata, errdata = run_os_command(command)
  2372. if not retcode == 0:
  2373. raise FatalException(retcode, errdata)
  2374. if errdata:
  2375. print_warning_msg(errdata)
  2376. sqlfile = DATABASE_FIX_LOCAL_REPO_SCRIPTS[0]
  2377. command = FIX_LOCAL_REPO_CMD[:]
  2378. command[-1] = command[-1].format(sqlfile, dbname)
  2379. retcode, outdata, errdata = run_os_command(command)
  2380. if not retcode == 0:
  2381. raise FatalException(retcode, errdata)
  2382. if errdata:
  2383. print_warning_msg(errdata)
  2384. return retcode
  2385. pass
  2386. def upgrade_local_repo(args):
  2387. properties = get_ambari_properties()
  2388. if properties == -1:
  2389. print_error_msg ("Error getting ambari properties")
  2390. return -1
  2391. stack_location = properties[STACK_LOCATION_KEY]
  2392. if stack_location is None:
  2393. stack_location = STACK_LOCATION_DEFAULT
  2394. stack_root_local = os.path.join(stack_location, "HDPLocal")
  2395. if not os.path.exists(stack_root_local):
  2396. print_info_msg("HDPLocal stack directory does not exist, skipping")
  2397. return
  2398. stack_root = os.path.join(stack_location, "HDP")
  2399. if not os.path.exists(stack_root):
  2400. print_info_msg("HDP stack directory does not exist, skipping")
  2401. return
  2402. for stack_version_local in os.listdir(stack_root_local):
  2403. repo_file_local = os.path.join(stack_root_local, stack_version_local, "repos", "repoinfo.xml.rpmsave")
  2404. if not os.path.exists(repo_file_local):
  2405. repo_file_local = os.path.join(stack_root_local, stack_version_local, "repos", "repoinfo.xml")
  2406. repo_file = os.path.join(stack_root, stack_version_local, "repos", "repoinfo.xml")
  2407. print_info_msg("Local repo file: " + repo_file_local)
  2408. print_info_msg("Repo file: " + repo_file_local)
  2409. if os.path.exists(repo_file_local) and os.path.exists(repo_file):
  2410. local_values = load_stack_values(stack_version_local, repo_file_local)
  2411. repo_values = load_stack_values(stack_version_local, repo_file)
  2412. for k, v in local_values.iteritems():
  2413. if repo_values.has_key(k):
  2414. local_url = local_values[k]
  2415. repo_url = repo_values[k]
  2416. if repo_url != local_url:
  2417. upgrade_local_repo_db(args, k, local_url)
  2418. #
  2419. # Upgrades the Ambari Server.
  2420. #
  2421. def upgrade(args):
  2422. if not is_root():
  2423. err = 'Ambari-server upgrade should be run with ' \
  2424. 'root-level privileges'
  2425. raise FatalException(4, err)
  2426. print 'Updating properties in ' + AMBARI_PROPERTIES_FILE + ' ...'
  2427. retcode = update_ambari_properties()
  2428. if not retcode == 0:
  2429. err = AMBARI_PROPERTIES_FILE + ' file can\'t be updated. Exiting'
  2430. raise FatalException(retcode, err)
  2431. try:
  2432. check_database_name_property()
  2433. except FatalException:
  2434. properties = get_ambari_properties()
  2435. if properties == -1:
  2436. print_error_msg ("Error getting ambari properties")
  2437. return -1
  2438. print_warning_msg(JDBC_DATABASE_PROPERTY + " property isn't set in " +
  2439. AMBARI_PROPERTIES_FILE + ". Setting it to default value - " + DEFAULT_DB_NAME)
  2440. properties.process_pair(JDBC_DATABASE_PROPERTY, DEFAULT_DB_NAME)
  2441. conf_file = find_properties_file()
  2442. try:
  2443. properties.store(open(conf_file, "w"))
  2444. except Exception, e:
  2445. print_error_msg('Could not write ambari config file "%s": %s' % (conf_file, e))
  2446. return -1
  2447. parse_properties_file(args)
  2448. if args.persistence_type == "remote":
  2449. client_desc = DATABASE_NAMES[DATABASE_INDEX] + ' ' + DATABASE_CLI_TOOLS_DESC[DATABASE_INDEX]
  2450. client_usage_cmd = DATABASE_CLI_TOOLS_USAGE[DATABASE_INDEX].format(DATABASE_UPGRADE_SCRIPTS[DATABASE_INDEX], args.database_username,
  2451. BLIND_PASSWORD, args.database_name)
  2452. #TODO temporarty code
  2453. if not args.database in ["oracle", "mysql"]:
  2454. raise FatalException(-20, "Upgrade for remote database only supports Oracle.")
  2455. if get_db_cli_tool(args):
  2456. retcode, out, err = execute_remote_script(args, DATABASE_UPGRADE_SCRIPTS[DATABASE_INDEX])
  2457. if not retcode == 0:
  2458. raise NonFatalException(err)
  2459. else:
  2460. command = prepare_schema_upgrade_command(args)
  2461. err = 'Cannot find ' + client_desc + ' client in the path to upgrade the Ambari ' + \
  2462. 'Server schema. To upgrade Ambari Server schema ' + \
  2463. 'you must run the following command:' + \
  2464. os.linesep + command
  2465. args.warnings.append(err)
  2466. pass
  2467. else:
  2468. print 'Checking PostgreSQL...'
  2469. retcode = check_postgre_up()
  2470. if not retcode == 0:
  2471. err = 'PostgreSQL server not running. Exiting'
  2472. raise FatalException(retcode, err)
  2473. file = args.upgrade_script_file
  2474. print 'Upgrading database...'
  2475. retcode = execute_db_script(args, file)
  2476. if not retcode == 0:
  2477. err = 'Database upgrade script has failed. Exiting.'
  2478. raise FatalException(retcode, err)
  2479. print 'Checking database integrity...'
  2480. check_file = file[:-3] + "Check" + file[-4:]
  2481. retcode = check_db_consistency(args, check_file)
  2482. if not retcode == 0:
  2483. print 'Found inconsistency. Trying to fix...'
  2484. fix_file = file[:-3] + "Fix" + file[-4:]
  2485. retcode = execute_db_script(args, fix_file)
  2486. if not retcode == 0:
  2487. err = 'Database cannot be fixed. Exiting.'
  2488. raise FatalException(retcode, err)
  2489. else:
  2490. print 'Database is consistent.'
  2491. user = read_ambari_user()
  2492. if user is None:
  2493. warn = "Can not determine custom ambari user.\n" + SETUP_OR_UPGRADE_MSG
  2494. print_warning_msg(warn)
  2495. else:
  2496. adjust_directory_permissions(user)
  2497. # local repo
  2498. upgrade_local_repo(args)
  2499. #
  2500. # The Ambari Server status.
  2501. #
  2502. def status(args):
  2503. args.exit_message = None
  2504. status, pid = is_server_runing()
  2505. if status:
  2506. print "Ambari Server running"
  2507. print "Found Ambari Server PID: '" + str(pid) + " at: " + PID_DIR + os.sep + PID_NAME
  2508. else:
  2509. print "Ambari Server not running. Stale PID File at: " + PID_DIR + os.sep + PID_NAME
  2510. #
  2511. # Prints an "info" messsage.
  2512. #
  2513. def print_info_msg(msg):
  2514. if VERBOSE:
  2515. print("INFO: " + msg)
  2516. #
  2517. # Prints an "error" messsage.
  2518. #
  2519. def print_error_msg(msg):
  2520. print("ERROR: " + msg)
  2521. #
  2522. # Prints a "warning" messsage.
  2523. #
  2524. def print_warning_msg(msg, bold=False):
  2525. if bold:
  2526. print(BOLD_ON + "WARNING: " + msg + BOLD_OFF)
  2527. else:
  2528. print("WARNING: " + msg)
  2529. #
  2530. # Gets the y/n input.
  2531. #
  2532. # return True if 'y' or False if 'n'
  2533. #
  2534. def get_YN_input(prompt,default):
  2535. yes = set(['yes','ye', 'y'])
  2536. no = set(['no','n'])
  2537. return get_choice_string_input(prompt,default,yes,no)
  2538. def get_choice_string_input(prompt,default,firstChoice,secondChoice):
  2539. if SILENT:
  2540. print(prompt)
  2541. return default
  2542. choice = raw_input(prompt).lower()
  2543. if choice in firstChoice:
  2544. return True
  2545. elif choice in secondChoice:
  2546. return False
  2547. elif choice is "": # Just enter pressed
  2548. return default
  2549. else:
  2550. print "input not recognized, please try again: "
  2551. return get_choice_string_input(prompt,default,firstChoice,secondChoice)
  2552. def get_validated_string_input(prompt, default, pattern, description,
  2553. is_pass, allowEmpty=True, validatorFunction=None):
  2554. input = ""
  2555. while not input:
  2556. if SILENT:
  2557. print (prompt)
  2558. input = default
  2559. elif is_pass:
  2560. input = getpass.getpass(prompt)
  2561. else:
  2562. input = raw_input(prompt)
  2563. if not input.strip():
  2564. # Empty input - if default available use default
  2565. if not allowEmpty and not default:
  2566. print 'Property cannot be blank.'
  2567. input = ""
  2568. continue
  2569. else:
  2570. input = default
  2571. if validatorFunction:
  2572. if not validatorFunction(input):
  2573. input = ""
  2574. continue
  2575. break #done here and picking up default
  2576. else:
  2577. if not pattern==None and not re.search(pattern,input.strip()):
  2578. print description
  2579. input= ""
  2580. if validatorFunction:
  2581. if not validatorFunction(input):
  2582. input = ""
  2583. continue
  2584. return input
  2585. def get_value_from_properties(properties, key, default=""):
  2586. try:
  2587. value = properties.get_property(key)
  2588. if not value:
  2589. value = default
  2590. except:
  2591. return default
  2592. return value
  2593. def get_prompt_default(defaultStr=None):
  2594. if not defaultStr or defaultStr == "":
  2595. return ""
  2596. else:
  2597. return '(' + defaultStr + ')'
  2598. def setup_ldap():
  2599. if not is_root():
  2600. err = 'Ambari-server setup-ldap should be run with ' \
  2601. 'root-level privileges'
  2602. raise FatalException(4, err)
  2603. properties = get_ambari_properties()
  2604. isSecure = get_is_secure(properties)
  2605. # python2.x dict is not ordered
  2606. ldap_property_list_reqd = ["authentication.ldap.primaryUrl",
  2607. "authentication.ldap.secondaryUrl",
  2608. "authentication.ldap.useSSL",
  2609. "authentication.ldap.usernameAttribute",
  2610. "authentication.ldap.baseDn",
  2611. "authentication.ldap.bindAnonymously" ]
  2612. ldap_property_list_opt = [ "authentication.ldap.managerDn",
  2613. LDAP_MGR_PASSWORD_PROPERTY,
  2614. SSL_TRUSTSTORE_TYPE_PROPERTY,
  2615. SSL_TRUSTSTORE_PATH_PROPERTY,
  2616. SSL_TRUSTSTORE_PASSWORD_PROPERTY]
  2617. ldap_property_list_truststore=[SSL_TRUSTSTORE_TYPE_PROPERTY,
  2618. SSL_TRUSTSTORE_PATH_PROPERTY,
  2619. SSL_TRUSTSTORE_PASSWORD_PROPERTY]
  2620. ldap_property_list_passwords=[LDAP_MGR_PASSWORD_PROPERTY,
  2621. SSL_TRUSTSTORE_PASSWORD_PROPERTY]
  2622. LDAP_PRIMARY_URL_DEFAULT = get_value_from_properties(properties, ldap_property_list_reqd[0])
  2623. LDAP_SECONDARY_URL_DEFAULT = get_value_from_properties(properties, ldap_property_list_reqd[1])
  2624. LDAP_USE_SSL_DEFAULT = get_value_from_properties(properties, ldap_property_list_reqd[2], "false")
  2625. LDAP_USER_ATT_DEFAULT = get_value_from_properties(properties, ldap_property_list_reqd[3], "uid")
  2626. LDAP_BASE_DN_DEFAULT = get_value_from_properties(properties, ldap_property_list_reqd[4])
  2627. LDAP_BIND_DEFAULT = get_value_from_properties(properties, ldap_property_list_reqd[5], "false")
  2628. LDAP_MGR_DN_DEFAULT = get_value_from_properties(properties, ldap_property_list_opt[0])
  2629. SSL_TRUSTSTORE_TYPE_DEFAULT = get_value_from_properties(properties, SSL_TRUSTSTORE_TYPE_PROPERTY, "jks")
  2630. SSL_TRUSTSTORE_PATH_DEFAULT = get_value_from_properties(properties, SSL_TRUSTSTORE_PATH_PROPERTY)
  2631. ldap_properties_map_reqd =\
  2632. {
  2633. ldap_property_list_reqd[0]:(LDAP_PRIMARY_URL_DEFAULT, "Primary URL* {{host:port}} {0}: ".format(get_prompt_default(LDAP_PRIMARY_URL_DEFAULT)), False),\
  2634. ldap_property_list_reqd[1]:(LDAP_SECONDARY_URL_DEFAULT, "Secondary URL {{host:port}} {0}: ".format(get_prompt_default(LDAP_SECONDARY_URL_DEFAULT)), True),\
  2635. ldap_property_list_reqd[2]:(LDAP_USE_SSL_DEFAULT, "Use SSL* [true/false] {0}: ".format(get_prompt_default(LDAP_USE_SSL_DEFAULT)), False),\
  2636. ldap_property_list_reqd[3]:(LDAP_USER_ATT_DEFAULT, "User name attribute* {0}: ".format(get_prompt_default(LDAP_USER_ATT_DEFAULT)), False),\
  2637. ldap_property_list_reqd[4]:(LDAP_BASE_DN_DEFAULT, "Base DN* {0}: ".format(get_prompt_default(LDAP_BASE_DN_DEFAULT)), False),\
  2638. ldap_property_list_reqd[5]:(LDAP_BIND_DEFAULT, "Bind anonymously* [true/false] {0}: ".format(get_prompt_default(LDAP_BIND_DEFAULT)), False)\
  2639. }
  2640. ldap_property_value_map = {}
  2641. for idx, key in enumerate(ldap_property_list_reqd):
  2642. if idx in [0, 1]:
  2643. pattern = REGEX_HOSTNAME_PORT
  2644. elif idx in [2, 5]:
  2645. pattern = REGEX_TRUE_FALSE
  2646. else:
  2647. pattern = REGEX_ANYTHING
  2648. input = get_validated_string_input(ldap_properties_map_reqd[key][1],
  2649. ldap_properties_map_reqd[key][0], pattern,
  2650. "Invalid characters in the input!", False, ldap_properties_map_reqd[key][2])
  2651. if input is not None and input != "":
  2652. ldap_property_value_map[key] = input
  2653. bindAnonymously = ldap_property_value_map["authentication.ldap.bindAnonymously"]
  2654. anonymous = (bindAnonymously and bindAnonymously.lower() == 'true')
  2655. mgr_password = None
  2656. # Ask for manager credentials only if bindAnonymously is false
  2657. if not anonymous:
  2658. username = get_validated_string_input("Manager DN* {0}: ".format(
  2659. get_prompt_default(LDAP_MGR_DN_DEFAULT)), LDAP_MGR_DN_DEFAULT, ".*",
  2660. "Invalid characters in the input!", False, False)
  2661. ldap_property_value_map[LDAP_MGR_USERNAME_PROPERTY] = username
  2662. mgr_password = configure_ldap_password()
  2663. ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] = mgr_password
  2664. useSSL = ldap_property_value_map["authentication.ldap.useSSL"]
  2665. ldaps = (useSSL and useSSL.lower() == 'true')
  2666. ts_password = None
  2667. if ldaps:
  2668. truststore_default = "n"
  2669. truststore_set = bool(SSL_TRUSTSTORE_PATH_DEFAULT)
  2670. if truststore_set:
  2671. truststore_default = "y"
  2672. custom_trust_store = get_YN_input("Do you want to provide custom TrustStore for Ambari [y/n] ({0})?".
  2673. format(truststore_default),
  2674. truststore_set)
  2675. if custom_trust_store:
  2676. ts_type = get_validated_string_input(
  2677. "TrustStore type [jks/jceks/pkcs12] {0}:".format(get_prompt_default(SSL_TRUSTSTORE_TYPE_DEFAULT)),
  2678. SSL_TRUSTSTORE_TYPE_DEFAULT,
  2679. "^(jks|jceks|pkcs12)?$", "Wrong type", False)
  2680. ts_path = None
  2681. while True:
  2682. ts_path = get_validated_string_input(
  2683. "Path to TrustStore file {0}:".format(get_prompt_default(SSL_TRUSTSTORE_PATH_DEFAULT)),
  2684. SSL_TRUSTSTORE_PATH_DEFAULT,
  2685. ".*", False, False)
  2686. if os.path.exists(ts_path):
  2687. break
  2688. else:
  2689. print 'File not found.'
  2690. ts_password = read_password("", ".*", "Password for TrustStore:", "Invalid characters in password")
  2691. ldap_property_value_map[SSL_TRUSTSTORE_TYPE_PROPERTY] = ts_type
  2692. ldap_property_value_map[SSL_TRUSTSTORE_PATH_PROPERTY] = ts_path
  2693. ldap_property_value_map[SSL_TRUSTSTORE_PASSWORD_PROPERTY] = ts_password
  2694. pass
  2695. else:
  2696. properties.removeOldProp(SSL_TRUSTSTORE_TYPE_PROPERTY)
  2697. properties.removeOldProp(SSL_TRUSTSTORE_PATH_PROPERTY)
  2698. properties.removeOldProp(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
  2699. pass
  2700. pass
  2701. print '=' * 20
  2702. print 'Review Settings'
  2703. print '=' * 20
  2704. for property in ldap_property_list_reqd:
  2705. if property in ldap_property_value_map:
  2706. print("%s: %s" % (property, ldap_property_value_map[property]))
  2707. for property in ldap_property_list_opt:
  2708. if ldap_property_value_map.has_key(property):
  2709. if property not in ldap_property_list_passwords:
  2710. print("%s: %s" % (property, ldap_property_value_map[property]))
  2711. else:
  2712. print("%s: %s" % (property, BLIND_PASSWORD))
  2713. save_settings = get_YN_input("Save settings [y/n] (y)? ", True)
  2714. if save_settings:
  2715. ldap_property_value_map[CLIENT_SECURITY_KEY] = 'ldap'
  2716. if isSecure:
  2717. if mgr_password:
  2718. encrypted_passwd = encrypt_password(LDAP_MGR_PASSWORD_ALIAS, mgr_password)
  2719. if mgr_password != encrypted_passwd:
  2720. ldap_property_value_map[LDAP_MGR_PASSWORD_PROPERTY] = encrypted_passwd
  2721. pass
  2722. if ts_password:
  2723. encrypted_passwd = encrypt_password(SSL_TRUSTSTORE_PASSWORD_ALIAS, ts_password)
  2724. if ts_password != encrypted_passwd:
  2725. ldap_property_value_map[SSL_TRUSTSTORE_PASSWORD_PROPERTY] = encrypted_passwd
  2726. pass
  2727. pass
  2728. # Persisting values
  2729. update_properties(properties, ldap_property_value_map)
  2730. print 'Saving...done'
  2731. return 0
  2732. def read_master_key(isReset=False):
  2733. passwordPattern = ".*"
  2734. passwordPrompt = "Please provide master key for locking the credential store: "
  2735. passwordDescr = "Invalid characters in password. Use only alphanumeric or "\
  2736. "_ or - characters"
  2737. passwordDefault = ""
  2738. if isReset:
  2739. passwordPrompt = "Enter new Master Key: "
  2740. masterKey = get_validated_string_input(passwordPrompt, passwordDefault,
  2741. passwordPattern, passwordDescr, True, True)
  2742. if not masterKey:
  2743. print "Master Key cannot be empty!"
  2744. return read_master_key()
  2745. masterKey2 = get_validated_string_input( "Re-enter master key: ",
  2746. passwordDefault, passwordPattern, passwordDescr, True, True)
  2747. if masterKey != masterKey2:
  2748. print "Master key did not match!"
  2749. return read_master_key()
  2750. return masterKey
  2751. def encrypt_password(alias, password):
  2752. properties = get_ambari_properties()
  2753. if properties == -1:
  2754. raise FatalException(1, None)
  2755. return get_encrypted_password(alias, password, properties)
  2756. def get_encrypted_password(alias, password, properties):
  2757. isSecure = get_is_secure(properties)
  2758. (isPersisted, masterKeyFile) = get_is_persisted(properties)
  2759. if isSecure:
  2760. masterKey = None
  2761. if not masterKeyFile:
  2762. # Encryption enabled but no master key file found
  2763. masterKey = get_original_master_key(properties)
  2764. retCode = save_passwd_for_alias(alias, password, masterKey)
  2765. if retCode != 0:
  2766. print 'Failed to save secure password!'
  2767. return password
  2768. else:
  2769. return get_alias_string(alias)
  2770. return password
  2771. def decrypt_password_for_alias(alias):
  2772. properties = get_ambari_properties()
  2773. if properties == -1:
  2774. raise FatalException(1, None)
  2775. isSecure = get_is_secure(properties)
  2776. (isPersisted, masterKeyFile) = get_is_persisted(properties)
  2777. if isSecure:
  2778. masterKey = None
  2779. if not masterKeyFile:
  2780. # Encryption enabled but no master key file found
  2781. masterKey = get_original_master_key(properties)
  2782. return read_passwd_for_alias(alias, masterKey)
  2783. else:
  2784. return alias
  2785. def get_original_master_key(properties):
  2786. try:
  2787. masterKey = get_validated_string_input('Enter current Master Key: ',
  2788. "", ".*", "", True, False)
  2789. except KeyboardInterrupt:
  2790. print 'Exiting...'
  2791. sys.exit(1)
  2792. # Find an alias that exists
  2793. alias = None
  2794. property = properties.get_property(JDBC_PASSWORD_PROPERTY)
  2795. if property and is_alias_string(property):
  2796. alias = JDBC_RCA_PASSWORD_ALIAS
  2797. if not alias:
  2798. property = properties.get_property(LDAP_MGR_PASSWORD_PROPERTY)
  2799. if property and is_alias_string(property):
  2800. alias = LDAP_MGR_PASSWORD_ALIAS
  2801. if not alias:
  2802. property = properties.get_property(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
  2803. if property and is_alias_string(property):
  2804. alias = SSL_TRUSTSTORE_PASSWORD_ALIAS
  2805. # Decrypt alias with master to validate it, if no master return
  2806. if alias and masterKey:
  2807. password = read_passwd_for_alias(alias, masterKey)
  2808. if not password:
  2809. print "ERROR: Master key does not match."
  2810. return get_original_master_key(properties)
  2811. return masterKey
  2812. def get_is_secure(properties):
  2813. isSecure = properties.get_property(SECURITY_IS_ENCRYPTION_ENABLED)
  2814. isSecure = True if isSecure and isSecure.lower() == 'true' else False
  2815. return isSecure
  2816. def get_is_persisted(properties):
  2817. keyLocation = get_master_key_location(properties)
  2818. masterKeyFile = search_file(SECURITY_MASTER_KEY_FILENAME, keyLocation)
  2819. isPersisted = True if masterKeyFile else False
  2820. return (isPersisted, masterKeyFile)
  2821. def setup_master_key():
  2822. if not is_root():
  2823. err = 'Ambari-server setup should be run with '\
  2824. 'root-level privileges'
  2825. raise FatalException(4, err)
  2826. properties = get_ambari_properties()
  2827. if properties == -1:
  2828. raise FatalException(1, "Failed to read properties file.")
  2829. db_password = properties.get_property(JDBC_PASSWORD_PROPERTY)
  2830. # Encrypt passwords cannot be called before setup
  2831. if not db_password:
  2832. print 'Please call "setup" before "encrypt-passwords". Exiting...'
  2833. return 1
  2834. # Check configuration for location of master key
  2835. isSecure = get_is_secure(properties)
  2836. (isPersisted, masterKeyFile) = get_is_persisted(properties)
  2837. # Read clear text password from file
  2838. if not is_alias_string(db_password) and os.path.isfile(db_password):
  2839. with open(db_password, 'r') as passwdfile:
  2840. db_password = passwdfile.read()
  2841. ldap_password = properties.get_property(LDAP_MGR_PASSWORD_PROPERTY)
  2842. ts_password = properties.get_property(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
  2843. resetKey = False
  2844. masterKey = None
  2845. if isSecure:
  2846. print "Password encryption is enabled."
  2847. resetKey = get_YN_input("Do you want to reset Master Key? [y/n] (n): ", False)
  2848. # For encrypting of only unencrypted passwords without resetting the key ask
  2849. # for master key if not persisted.
  2850. if isSecure and not isPersisted and not resetKey:
  2851. print "Master Key not persisted."
  2852. masterKey = get_original_master_key(properties)
  2853. pass
  2854. # Make sure both passwords are clear-text if master key is lost
  2855. if resetKey:
  2856. if not isPersisted:
  2857. print "Master Key not persisted."
  2858. masterKey = get_original_master_key(properties)
  2859. # Unable get the right master key or skipped question <enter>
  2860. if not masterKey:
  2861. print "To disable encryption, do the following:"
  2862. print "- Edit " + find_properties_file() + \
  2863. " and set " + SECURITY_IS_ENCRYPTION_ENABLED + " = " + "false."
  2864. err = "{0} is already encrypted. Please call {1} to store unencrypted" \
  2865. " password and call 'encrypt-passwords' again."
  2866. if db_password and is_alias_string(db_password):
  2867. print err.format('- Database password', "'" + SETUP_ACTION + "'")
  2868. if ldap_password and is_alias_string(ldap_password):
  2869. print err.format('- LDAP manager password', "'" + LDAP_SETUP_ACTION + "'")
  2870. if ts_password and is_alias_string(ts_password):
  2871. print err.format('TrustStore password', "'" + LDAP_SETUP_ACTION + "'")
  2872. return 1
  2873. pass
  2874. pass
  2875. pass
  2876. # Read back any encrypted passwords
  2877. if db_password and is_alias_string(db_password):
  2878. db_password = read_passwd_for_alias(JDBC_RCA_PASSWORD_ALIAS, masterKey)
  2879. if ldap_password and is_alias_string(ldap_password):
  2880. ldap_password = read_passwd_for_alias(LDAP_MGR_PASSWORD_ALIAS, masterKey)
  2881. if ts_password and is_alias_string(ts_password):
  2882. ts_password = read_passwd_for_alias(SSL_TRUSTSTORE_PASSWORD_ALIAS, masterKey)
  2883. # Read master key, if non-secure or reset is true
  2884. if resetKey or not isSecure:
  2885. masterKey = read_master_key(resetKey)
  2886. persist = get_YN_input("Do you want to persist master key. If you choose "\
  2887. "not to persist, you need to provide the Master "\
  2888. "Key while starting the ambari server as an env "\
  2889. "variable named " + SECURITY_KEY_ENV_VAR_NAME +\
  2890. " or the start will prompt for the master key."
  2891. " Persist [y/n] (y)? ", True)
  2892. if persist:
  2893. save_master_key(masterKey, get_master_key_location(properties) + os.sep +
  2894. SECURITY_MASTER_KEY_FILENAME, persist)
  2895. elif not persist and masterKeyFile:
  2896. try:
  2897. os.remove(masterKeyFile)
  2898. print_info_msg("Deleting master key file at location: " + str(
  2899. masterKeyFile))
  2900. except Exception, e:
  2901. print 'ERROR: Could not remove master key file. %s' % e
  2902. # Blow up the credential store made with previous key, if any
  2903. store_file = get_credential_store_location(properties)
  2904. if os.path.exists(store_file):
  2905. try:
  2906. os.remove(store_file)
  2907. except:
  2908. print_warning_msg("Failed to remove credential store file.")
  2909. pass
  2910. pass
  2911. pass
  2912. propertyMap = {SECURITY_IS_ENCRYPTION_ENABLED : 'true'}
  2913. # Encrypt only un-encrypted passwords
  2914. if db_password and not is_alias_string(db_password):
  2915. retCode = save_passwd_for_alias(JDBC_RCA_PASSWORD_ALIAS, db_password, masterKey)
  2916. if retCode != 0:
  2917. print 'Failed to save secure database password.'
  2918. else:
  2919. propertyMap[JDBC_PASSWORD_PROPERTY] = get_alias_string(JDBC_RCA_PASSWORD_ALIAS)
  2920. remove_password_file(JDBC_PASSWORD_FILENAME)
  2921. if properties.get_property(JDBC_RCA_PASSWORD_FILE_PROPERTY):
  2922. propertyMap[JDBC_RCA_PASSWORD_FILE_PROPERTY] = get_alias_string(JDBC_RCA_PASSWORD_ALIAS)
  2923. pass
  2924. if ldap_password and not is_alias_string(ldap_password):
  2925. retCode = save_passwd_for_alias(LDAP_MGR_PASSWORD_ALIAS, ldap_password, masterKey)
  2926. if retCode != 0:
  2927. print 'Failed to save secure LDAP password.'
  2928. else:
  2929. propertyMap[LDAP_MGR_PASSWORD_PROPERTY] = get_alias_string(LDAP_MGR_PASSWORD_ALIAS)
  2930. pass
  2931. if ts_password and not is_alias_string(ts_password):
  2932. retCode = save_passwd_for_alias(SSL_TRUSTSTORE_PASSWORD_ALIAS, ts_password, masterKey)
  2933. if retCode != 0:
  2934. print 'Failed to save secure TrustStore password.'
  2935. else:
  2936. propertyMap[SSL_TRUSTSTORE_PASSWORD_PROPERTY] = get_alias_string(SSL_TRUSTSTORE_PASSWORD_ALIAS)
  2937. pass
  2938. update_properties(properties, propertyMap)
  2939. # Since files for store and master are created we need to ensure correct
  2940. # permissions
  2941. ambari_user = read_ambari_user()
  2942. if ambari_user:
  2943. adjust_directory_permissions(ambari_user)
  2944. return 0
  2945. def get_credential_store_location(properties):
  2946. store_loc = properties[SECURITY_KEYS_DIR]
  2947. if store_loc is None or store_loc == "":
  2948. store_loc = "/var/lib/ambari-server/keys/credentials.jceks"
  2949. else:
  2950. store_loc += os.sep + "credentials.jceks"
  2951. return store_loc
  2952. def get_master_key_location(properties):
  2953. keyLocation = properties[SECURITY_MASTER_KEY_LOCATION]
  2954. if keyLocation is None or keyLocation == "":
  2955. keyLocation = properties[SECURITY_KEYS_DIR]
  2956. return keyLocation
  2957. def is_alias_string(passwdStr):
  2958. regex = re.compile("\$\{alias=[\w\.]+\}")
  2959. # Match implies string at beginning of word
  2960. r = regex.match(passwdStr)
  2961. if r is not None:
  2962. return True
  2963. else:
  2964. return False
  2965. def get_alias_string(alias):
  2966. return "${alias=" + alias + "}"
  2967. def get_alias_from_alias_string(aliasStr):
  2968. return aliasStr[8:-1]
  2969. def read_passwd_for_alias(alias, masterKey=""):
  2970. if alias:
  2971. jdk_path = find_jdk()
  2972. if jdk_path is None:
  2973. print_error_msg("No JDK found, please run the \"setup\" "
  2974. "command to install a JDK automatically or install any "
  2975. "JDK manually to " + JDK_INSTALL_DIR)
  2976. return 1
  2977. tempFileName = "ambari.passwd"
  2978. passwd = ""
  2979. tempDir = tempfile.gettempdir()
  2980. #create temporary file for writing
  2981. tempFilePath = tempDir + os.sep + tempFileName
  2982. file = open(tempFilePath, 'w+')
  2983. os.chmod(tempFilePath, stat.S_IREAD | stat.S_IWRITE)
  2984. file.close()
  2985. if masterKey is None or masterKey == "":
  2986. masterKey = "None"
  2987. command = SECURITY_PROVIDER_GET_CMD.format(jdk_path,
  2988. get_conf_dir(), get_ambari_classpath(), alias, tempFilePath, masterKey)
  2989. (retcode, stdout, stderr) = run_os_command(command)
  2990. print_info_msg("Return code from credential provider get passwd: " +
  2991. str(retcode))
  2992. if retcode != 0:
  2993. print 'ERROR: Unable to read password from store. alias = ' + alias
  2994. else:
  2995. passwd = open(tempFilePath, 'r').read()
  2996. # Remove temporary file
  2997. os.remove(tempFilePath)
  2998. return passwd
  2999. else:
  3000. print_error_msg("Alias is unreadable.")
  3001. def save_passwd_for_alias(alias, passwd, masterKey=""):
  3002. if alias and passwd:
  3003. jdk_path = find_jdk()
  3004. if jdk_path is None:
  3005. print_error_msg("No JDK found, please run the \"setup\" "
  3006. "command to install a JDK automatically or install any "
  3007. "JDK manually to " + JDK_INSTALL_DIR)
  3008. return 1
  3009. if masterKey is None or masterKey == "":
  3010. masterKey = "None"
  3011. command = SECURITY_PROVIDER_PUT_CMD.format(jdk_path, get_conf_dir(),
  3012. get_ambari_classpath(), alias, passwd, masterKey)
  3013. (retcode, stdout, stderr) = run_os_command(command)
  3014. print_info_msg("Return code from credential provider save passwd: " +
  3015. str(retcode))
  3016. return retcode
  3017. else:
  3018. print_error_msg("Alias or password is unreadable.")
  3019. def save_master_key(master_key, key_location, persist=True):
  3020. if master_key:
  3021. jdk_path = find_jdk()
  3022. if jdk_path is None:
  3023. print_error_msg("No JDK found, please run the \"setup\" "
  3024. "command to install a JDK automatically or install any "
  3025. "JDK manually to " + JDK_INSTALL_DIR)
  3026. return 1
  3027. command = SECURITY_PROVIDER_KEY_CMD.format(jdk_path,
  3028. get_ambari_classpath(), get_conf_dir(), master_key, key_location, persist)
  3029. (retcode, stdout, stderr) = run_os_command(command)
  3030. print_info_msg("Return code from credential provider save KEY: " +
  3031. str(retcode))
  3032. else:
  3033. print_error_msg("Master key cannot be None.")
  3034. def configure_ldap_password():
  3035. passwordDefault = ""
  3036. passwordPrompt = 'Enter Manager Password* : '
  3037. passwordPattern = ".*"
  3038. passwordDescr = "Invalid characters in password."
  3039. password = read_password(passwordDefault, passwordPattern, passwordPrompt,
  3040. passwordDescr)
  3041. return password
  3042. # Copy file to /tmp and save with file.# (largest # is latest file)
  3043. def backup_file_in_temp(filePath):
  3044. if filePath is not None:
  3045. tmpDir = tempfile.gettempdir()
  3046. back_up_file_count = len(glob.glob1(tmpDir, AMBARI_PROPERTIES_FILE + "*"))
  3047. try:
  3048. shutil.copyfile(filePath, tmpDir + os.sep +
  3049. AMBARI_PROPERTIES_FILE + "." + str(back_up_file_count + 1))
  3050. except (Exception), e:
  3051. print_error_msg('Could not backup file in temp "%s": %s' % (str(
  3052. back_up_file_count, e)))
  3053. return 0
  3054. # update properties in a section-less properties file
  3055. # Cannot use ConfigParser due to bugs in version 2.6
  3056. def update_properties(propertyMap):
  3057. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  3058. backup_file_in_temp(conf_file)
  3059. if propertyMap is not None and conf_file is not None:
  3060. properties = Properties()
  3061. try:
  3062. with open(conf_file, 'r') as file:
  3063. properties.load(file)
  3064. except (Exception), e:
  3065. print_error_msg ('Could not read "%s": %s' % (conf_file, e))
  3066. return -1
  3067. #for key in propertyMap.keys():
  3068. #properties[key] = propertyMap[key]
  3069. for key in propertyMap.keys():
  3070. properties.removeOldProp(key)
  3071. properties.process_pair(key, str(propertyMap[key]))
  3072. with open(conf_file, 'w') as file:
  3073. properties.store(file)
  3074. return 0
  3075. def update_properties(properties, propertyMap):
  3076. conf_file = search_file(AMBARI_PROPERTIES_FILE, get_conf_dir())
  3077. backup_file_in_temp(conf_file)
  3078. if conf_file is not None:
  3079. if propertyMap is not None:
  3080. for key in propertyMap.keys():
  3081. properties.removeOldProp(key)
  3082. properties.process_pair(key, str(propertyMap[key]))
  3083. pass
  3084. with open(conf_file, 'w') as file:
  3085. properties.store(file)
  3086. pass
  3087. pass
  3088. def setup_https(args):
  3089. if not is_root():
  3090. err = 'ambari-server setup-https should be run with ' \
  3091. 'root-level privileges'
  3092. raise FatalException(4, err)
  3093. args.exit_message = None
  3094. if not SILENT:
  3095. properties = get_ambari_properties()
  3096. try:
  3097. security_server_keys_dir = properties.get_property(SSL_KEY_DIR)
  3098. client_api_ssl_port = DEFAULT_SSL_API_PORT if properties.get_property(SSL_API_PORT) in ("")\
  3099. else properties.get_property(SSL_API_PORT)
  3100. api_ssl = properties.get_property(SSL_API) in ['true']
  3101. cert_was_imported = False
  3102. cert_must_import = True
  3103. if api_ssl:
  3104. if get_YN_input("Do you want to disable HTTPS [y/n] (n)? ", False):
  3105. properties.process_pair(SSL_API, "false")
  3106. cert_must_import=False
  3107. else:
  3108. properties.process_pair(SSL_API_PORT, \
  3109. get_validated_string_input(\
  3110. "SSL port ["+str(client_api_ssl_port)+"] ? ",\
  3111. str(client_api_ssl_port),\
  3112. "^[0-9]{1,5}$", "Invalid port.", False, validatorFunction = is_valid_https_port))
  3113. cert_was_imported = import_cert_and_key_action(security_server_keys_dir, properties)
  3114. else:
  3115. if get_YN_input("Do you want to configure HTTPS [y/n] (y)? ", True):
  3116. properties.process_pair(SSL_API_PORT,\
  3117. get_validated_string_input("SSL port ["+str(client_api_ssl_port)+"] ? ",\
  3118. str(client_api_ssl_port), "^[0-9]{1,5}$", "Invalid port.", False, validatorFunction = is_valid_https_port))
  3119. cert_was_imported = import_cert_and_key_action(security_server_keys_dir, properties)
  3120. else:
  3121. return False
  3122. if cert_must_import and not cert_was_imported:
  3123. print 'Setup of HTTPS failed. Exiting.'
  3124. return False
  3125. conf_file = find_properties_file()
  3126. f = open(conf_file, 'w')
  3127. properties.store(f, "Changed by 'ambari-server setup-https' command")
  3128. ambari_user = read_ambari_user()
  3129. if ambari_user:
  3130. adjust_directory_permissions(ambari_user)
  3131. return True
  3132. except (KeyError), e:
  3133. err = 'Property ' + str(e) + ' is not defined'
  3134. raise FatalException(1, err)
  3135. else:
  3136. warning = "setup-https is not enabled in silent mode."
  3137. raise NonFatalException(warning)
  3138. def is_server_runing():
  3139. pid_file_path = PID_DIR + os.sep + PID_NAME
  3140. if os.path.exists(pid_file_path):
  3141. try:
  3142. f = open(pid_file_path, "r")
  3143. except IOError, ex:
  3144. raise FatalException(1, str(ex))
  3145. pid = f.readline().strip()
  3146. if not pid.isdigit():
  3147. err = "%s is corrupt. Removing" % (pid_file_path)
  3148. f.close()
  3149. run_os_command("rm -f " + pid_file_path)
  3150. raise NonFatalException(err)
  3151. f.close()
  3152. retcode, out, err = run_os_command("ps -p " + pid)
  3153. if retcode == 0:
  3154. return True, int(pid)
  3155. else:
  3156. return False, None
  3157. else:
  3158. return False, None
  3159. def setup_component_https(component, command, property, alias):
  3160. if not SILENT:
  3161. jdk_path = find_jdk()
  3162. if jdk_path is None:
  3163. err = "No JDK found, please run the \"ambari-server setup\" " \
  3164. "command to install a JDK automatically or install any " \
  3165. "JDK manually to " + JDK_INSTALL_DIR
  3166. raise FatalException(1, err)
  3167. properties = get_ambari_properties()
  3168. use_https = properties.get_property(property) in ['true']
  3169. if use_https:
  3170. if get_YN_input("Do you want to disable HTTPS for " + component + " [y/n] (n)? ", False):
  3171. truststore_path = get_truststore_path(properties)
  3172. truststore_password = get_truststore_password(properties)
  3173. run_component_https_cmd(get_delete_cert_command(jdk_path, alias, truststore_path, truststore_password))
  3174. properties.process_pair(property, "false")
  3175. else:
  3176. return
  3177. else:
  3178. if get_YN_input("Do you want to configure HTTPS for " + component + " [y/n] (y)? ", True):
  3179. truststore_type = get_truststore_type(properties)
  3180. truststore_path = get_truststore_path(properties)
  3181. truststore_password = get_truststore_password(properties)
  3182. run_os_command(get_delete_cert_command(jdk_path, alias, truststore_path, truststore_password))
  3183. import_cert_path = get_validated_filepath_input(\
  3184. "Enter path to " + component + " Certificate: ",\
  3185. "Certificate not found")
  3186. run_component_https_cmd(get_import_cert_command(jdk_path, alias, truststore_type, import_cert_path, truststore_path, truststore_password))
  3187. properties.process_pair(property, "true")
  3188. else:
  3189. return
  3190. conf_file = find_properties_file()
  3191. f = open(conf_file, 'w')
  3192. properties.store(f, "Changed by 'ambari-server " + command + "' command")
  3193. else:
  3194. print command + " is not enabled in silent mode."
  3195. def get_truststore_type(properties):
  3196. truststore_type = properties.get_property(SSL_TRUSTSTORE_TYPE_PROPERTY)
  3197. if not truststore_type:
  3198. SSL_TRUSTSTORE_TYPE_DEFAULT = get_value_from_properties(properties, SSL_TRUSTSTORE_TYPE_PROPERTY, "jks")
  3199. truststore_type = get_validated_string_input(
  3200. "TrustStore type [jks/jceks/pkcs12] {0}:".format(get_prompt_default(SSL_TRUSTSTORE_TYPE_DEFAULT)),
  3201. SSL_TRUSTSTORE_TYPE_DEFAULT,
  3202. "^(jks|jceks|pkcs12)?$", "Wrong type", False)
  3203. if truststore_type:
  3204. properties.process_pair(SSL_TRUSTSTORE_TYPE_PROPERTY, truststore_type)
  3205. return truststore_type
  3206. def get_truststore_path(properties):
  3207. truststore_path = properties.get_property(SSL_TRUSTSTORE_PATH_PROPERTY)
  3208. if not truststore_path:
  3209. SSL_TRUSTSTORE_PATH_DEFAULT = get_value_from_properties(properties, SSL_TRUSTSTORE_PATH_PROPERTY)
  3210. while not truststore_path:
  3211. truststore_path = get_validated_string_input(
  3212. "Path to TrustStore file {0}:".format(get_prompt_default(SSL_TRUSTSTORE_PATH_DEFAULT)),
  3213. SSL_TRUSTSTORE_PATH_DEFAULT,
  3214. ".*", False, False)
  3215. if truststore_path:
  3216. properties.process_pair(SSL_TRUSTSTORE_PATH_PROPERTY, truststore_path)
  3217. return truststore_path
  3218. def get_truststore_password(properties):
  3219. truststore_password = properties.get_property(SSL_TRUSTSTORE_PASSWORD_PROPERTY)
  3220. isSecure = get_is_secure(properties)
  3221. if truststore_password:
  3222. if isSecure:
  3223. truststore_password = decrypt_password_for_alias(SSL_TRUSTSTORE_PASSWORD_ALIAS)
  3224. else:
  3225. truststore_password = read_password("", ".*", "Password for TrustStore:", "Invalid characters in password")
  3226. if truststore_password:
  3227. encrypted_password = get_encrypted_password(SSL_TRUSTSTORE_PASSWORD_ALIAS, truststore_password, properties)
  3228. properties.process_pair(SSL_TRUSTSTORE_PASSWORD_PROPERTY, encrypted_password)
  3229. return truststore_password
  3230. def run_component_https_cmd(cmd):
  3231. retcode, out, err = run_os_command(cmd)
  3232. if not retcode == 0:
  3233. err = 'Error occured during truststore setup ! :' + out + " : " + err
  3234. raise FatalException(1, err)
  3235. def get_delete_cert_command(jdk_path, alias, truststore_path, truststore_password):
  3236. cmd = KEYTOOL_DELETE_CERT_CMD.format(jdk_path, alias, truststore_password)
  3237. if truststore_path:
  3238. cmd += KEYTOOL_KEYSTORE.format(truststore_path)
  3239. return cmd
  3240. def get_import_cert_command(jdk_path, alias, truststore_type, import_cert_path, truststore_path, truststore_password):
  3241. cmd = KEYTOOL_IMPORT_CERT_CMD.format(jdk_path, alias, truststore_type, import_cert_path, truststore_password)
  3242. if truststore_path:
  3243. cmd += KEYTOOL_KEYSTORE.format(truststore_path)
  3244. return cmd
  3245. def import_cert_and_key_action(security_server_keys_dir, properties):
  3246. if import_cert_and_key(security_server_keys_dir):
  3247. properties.process_pair(SSL_SERVER_CERT_NAME, SSL_CERT_FILE_NAME)
  3248. properties.process_pair(SSL_SERVER_KEY_NAME, SSL_KEY_FILE_NAME)
  3249. properties.process_pair(SSL_API, "true")
  3250. return True
  3251. else:
  3252. return False
  3253. def import_cert_and_key(security_server_keys_dir):
  3254. import_cert_path = get_validated_filepath_input(\
  3255. "Enter path to Certificate: ",\
  3256. "Certificate not found")
  3257. import_key_path = get_validated_filepath_input(\
  3258. "Enter path to Private Key: ", "Private Key not found")
  3259. pem_password = get_validated_string_input("Please enter password for Private Key: ", "", None, None, True)
  3260. certInfoDict = get_cert_info(import_cert_path)
  3261. if not certInfoDict:
  3262. print_warning_msg('Unable to get Certificate information')
  3263. else:
  3264. #Validate common name of certificate
  3265. if not is_valid_cert_host(certInfoDict):
  3266. print_warning_msg('Unable to validate Certificate hostname')
  3267. #Validate issue and expirations dates of certificate
  3268. if not is_valid_cert_exp(certInfoDict):
  3269. print_warning_msg('Unable to validate Certificate issue and expiration dates')
  3270. #jetty requires private key files with non-empty key passwords
  3271. retcode = 0
  3272. err = ''
  3273. if not pem_password:
  3274. print 'Generating random password for HTTPS keystore...done.'
  3275. pem_password = generate_random_string()
  3276. retcode, out, err = run_os_command(CHANGE_KEY_PWD_CND.format(
  3277. import_key_path, pem_password))
  3278. import_key_path += '.secured'
  3279. if retcode == 0:
  3280. keystoreFilePath = os.path.join(security_server_keys_dir,\
  3281. SSL_KEYSTORE_FILE_NAME)
  3282. keystoreFilePathTmp = os.path.join(tempfile.gettempdir(),\
  3283. SSL_KEYSTORE_FILE_NAME)
  3284. passFilePath = os.path.join(security_server_keys_dir,\
  3285. SSL_KEY_PASSWORD_FILE_NAME)
  3286. passFilePathTmp = os.path.join(tempfile.gettempdir(),\
  3287. SSL_KEY_PASSWORD_FILE_NAME)
  3288. passinFilePath = os.path.join(tempfile.gettempdir(),\
  3289. SSL_PASSIN_FILE)
  3290. passwordFilePath = os.path.join(tempfile.gettempdir(),\
  3291. SSL_PASSWORD_FILE)
  3292. with open(passFilePathTmp, 'w+') as passFile:
  3293. passFile.write(pem_password)
  3294. passFile.close
  3295. pass
  3296. set_file_permissions(passFilePath, "660", read_ambari_user(), False)
  3297. copy_file(passFilePathTmp, passinFilePath)
  3298. copy_file(passFilePathTmp, passwordFilePath)
  3299. retcode, out, err = run_os_command(EXPRT_KSTR_CMD.format(import_cert_path,\
  3300. import_key_path, passwordFilePath, passinFilePath, keystoreFilePathTmp))
  3301. if retcode == 0:
  3302. print 'Importing and saving Certificate...done.'
  3303. import_file_to_keystore(keystoreFilePathTmp, keystoreFilePath)
  3304. import_file_to_keystore(passFilePathTmp, passFilePath)
  3305. import_file_to_keystore(import_cert_path, os.path.join(\
  3306. security_server_keys_dir, SSL_CERT_FILE_NAME))
  3307. import_file_to_keystore(import_key_path, os.path.join(\
  3308. security_server_keys_dir, SSL_KEY_FILE_NAME))
  3309. #Validate keystore
  3310. retcode, out, err = run_os_command(VALIDATE_KEYSTORE_CMD.format(keystoreFilePath,\
  3311. passwordFilePath, passinFilePath))
  3312. remove_file(passinFilePath)
  3313. remove_file(passwordFilePath)
  3314. if not retcode == 0:
  3315. print 'Error during keystore validation occured!:'
  3316. print err
  3317. return False
  3318. return True
  3319. else:
  3320. print_error_msg('Could not import Certificate and Private Key.')
  3321. print 'SSL error on exporting keystore: ' + err.rstrip() + \
  3322. '.\nPlease ensure that provided Private Key password is correct and ' +\
  3323. 're-import Certificate.'
  3324. return False
  3325. def import_file_to_keystore(source, destination):
  3326. shutil.copy(source, destination)
  3327. set_file_permissions(destination, "660", read_ambari_user(), False)
  3328. def generate_random_string(length=SSL_KEY_PASSWORD_LENGTH):
  3329. chars = string.digits + string.ascii_letters
  3330. return ''.join(random.choice(chars) for x in range(length))
  3331. def get_validated_filepath_input(prompt, description, default=None):
  3332. input = False
  3333. while not input:
  3334. if SILENT:
  3335. print (prompt)
  3336. return default
  3337. else:
  3338. input = raw_input(prompt)
  3339. if not input==None:
  3340. input = input.strip()
  3341. if not input==None and not ""==input and os.path.exists(input):
  3342. return input
  3343. else:
  3344. print description
  3345. input=False
  3346. def get_cert_info(path):
  3347. retcode, out, err = run_os_command(GET_CRT_INFO_CMD.format(path))
  3348. if retcode != 0:
  3349. print 'Error getting Certificate info'
  3350. print err
  3351. return None
  3352. if out:
  3353. certInfolist = out.split(os.linesep)
  3354. else:
  3355. print 'Empty Certificate info'
  3356. return None
  3357. notBefore = None
  3358. notAfter = None
  3359. subject = None
  3360. for item in range(len(certInfolist)):
  3361. if certInfolist[item].startswith('notAfter='):
  3362. notAfter = certInfolist[item].split('=')[1]
  3363. if certInfolist[item].startswith('notBefore='):
  3364. notBefore = certInfolist[item].split('=')[1]
  3365. if certInfolist[item].startswith('subject='):
  3366. subject = certInfolist[item].split('=', 1)[1]
  3367. #Convert subj to dict
  3368. pattern = re.compile(r"[A-Z]{1,2}=[\w.-]{1,}")
  3369. if subject:
  3370. subjList = pattern.findall(subject)
  3371. keys = [item.split('=')[0] for item in subjList]
  3372. values = [item.split('=')[1] for item in subjList]
  3373. subjDict = dict(zip(keys, values))
  3374. result = subjDict
  3375. result['notBefore'] = notBefore
  3376. result['notAfter'] = notAfter
  3377. result['subject'] = subject
  3378. return result
  3379. else:
  3380. return {}
  3381. def is_valid_cert_exp(certInfoDict):
  3382. if certInfoDict.has_key(NOT_BEFORE_ATTR):
  3383. notBefore = certInfoDict[NOT_BEFORE_ATTR]
  3384. else:
  3385. print_warning_msg('There is no Not Before value in Certificate')
  3386. return False
  3387. if certInfoDict.has_key(NOT_AFTER_ATTR):
  3388. notAfter = certInfoDict['notAfter']
  3389. else:
  3390. print_warning_msg('There is no Not After value in Certificate')
  3391. return False
  3392. notBeforeDate = datetime.datetime.strptime(notBefore, SSL_DATE_FORMAT)
  3393. notAfterDate = datetime.datetime.strptime(notAfter, SSL_DATE_FORMAT)
  3394. currentDate = datetime.datetime.now()
  3395. if currentDate > notAfterDate:
  3396. print_warning_msg('Certificate expired on: ' + str(notAfterDate))
  3397. return False
  3398. if currentDate < notBeforeDate:
  3399. print_warning_msg('Certificate will be active from: ' + str(notBeforeDate))
  3400. return False
  3401. return True
  3402. def is_valid_cert_host(certInfoDict):
  3403. if certInfoDict.has_key(COMMON_NAME_ATTR):
  3404. commonName = certInfoDict[COMMON_NAME_ATTR]
  3405. else:
  3406. print_warning_msg('There is no Common Name in Certificate')
  3407. return False
  3408. fqdn = get_fqdn()
  3409. if not fqdn:
  3410. print_warning_msg('Failed to get server FQDN')
  3411. return False
  3412. if commonName != fqdn:
  3413. print_warning_msg('Common Name in Certificate: ' + commonName + ' does not match the server FQDN: ' + fqdn)
  3414. return False
  3415. return True
  3416. def is_valid_https_port(port):
  3417. properties = get_ambari_properties()
  3418. if properties == -1:
  3419. print "Error getting ambari properties"
  3420. return False
  3421. one_way_port = properties[SRVR_ONE_WAY_SSL_PORT_PROPERTY]
  3422. if not one_way_port:
  3423. one_way_port = SRVR_ONE_WAY_SSL_PORT
  3424. two_way_port = properties[SRVR_TWO_WAY_SSL_PORT_PROPERTY]
  3425. if not two_way_port:
  3426. two_way_port = SRVR_TWO_WAY_SSL_PORT
  3427. if port.strip() == one_way_port.strip():
  3428. print "Port for https can't match the port for one way authentication port(" + one_way_port + ")"
  3429. return False
  3430. if port.strip() == two_way_port.strip():
  3431. print "Port for https can't match the port for two way authentication port(" + two_way_port + ")"
  3432. return False
  3433. return True
  3434. def get_fqdn():
  3435. properties = get_ambari_properties()
  3436. if properties == -1:
  3437. print "Error reading ambari properties"
  3438. return None
  3439. get_fqdn_service_url = properties[GET_FQDN_SERVICE_URL]
  3440. try:
  3441. handle = urllib2.urlopen(get_fqdn_service_url, '', 2)
  3442. str = handle.read()
  3443. handle.close()
  3444. return str
  3445. except Exception, e:
  3446. return socket.getfqdn()
  3447. def is_valid_filepath(filepath):
  3448. if not filepath or not os.path.exists(filepath) or os.path.isdir(filepath):
  3449. print 'Invalid path, please provide the absolute file path.'
  3450. return False
  3451. else:
  3452. return True
  3453. def setup_ambari_krb5_jaas():
  3454. jaas_conf_file = search_file(SECURITY_KERBEROS_JASS_FILENAME, get_conf_dir())
  3455. if os.path.exists(jaas_conf_file):
  3456. print 'Setting up Ambari kerberos JAAS configuration to access ' +\
  3457. 'secured Hadoop daemons...'
  3458. principal = get_validated_string_input('Enter ambari server\'s kerberos '
  3459. 'principal name (ambari@EXAMPLE.COM): ', 'ambari@EXAMPLE.COM', '.*', '', False,
  3460. False)
  3461. keytab = get_validated_string_input('Enter keytab path for ambari '
  3462. 'server\'s kerberos principal: ',
  3463. '/etc/security/keytabs/ambari.keytab', '.*', False, False,
  3464. validatorFunction = is_valid_filepath)
  3465. for line in fileinput.FileInput(jaas_conf_file, inplace=1):
  3466. line = re.sub('keyTab=.*$', 'keyTab="' + keytab + '"', line)
  3467. line = re.sub('principal=.*$', 'principal="' + principal + '"', line)
  3468. print line,
  3469. else:
  3470. raise NonFatalException('No jaas config file found at location: ' +
  3471. jaas_conf_file)
  3472. def setup_security(args):
  3473. need_restart = True
  3474. #Print menu options
  3475. print '=' * 75
  3476. print 'Choose one of the following options: '
  3477. print ' [1] Enable HTTPS for Ambari server.'
  3478. print ' [2] Enable HTTPS for Ganglia service.'
  3479. print ' [3] Enable HTTPS for Nagios service.'
  3480. print ' [4] Encrypt passwords stored in ambari.properties file.'
  3481. print ' [5] Setup Ambari kerberos JAAS configuration.'
  3482. print '=' * 75
  3483. choice = get_validated_string_input('Enter choice, (1-5): ', '0', '[1-5]',
  3484. 'Invalid choice', False, False)
  3485. if choice == '1':
  3486. need_restart = setup_https(args)
  3487. elif choice == '2':
  3488. setup_component_https("Ganglia", "setup-ganglia-https", GANGLIA_HTTPS,
  3489. "ganglia_cert")
  3490. elif choice == '3':
  3491. setup_component_https("Nagios", "setup-nagios-https", NAGIOS_HTTPS,
  3492. "nagios_cert")
  3493. elif choice == '4':
  3494. setup_master_key()
  3495. elif choice == '5':
  3496. setup_ambari_krb5_jaas()
  3497. else:
  3498. raise FatalException('Unknown option for setup-security command.')
  3499. return need_restart
  3500. #
  3501. # Main.
  3502. #
  3503. def main():
  3504. parser = optparse.OptionParser(usage="usage: %prog [options] action [stack_id]",)
  3505. parser.add_option('-f', '--init-script-file',
  3506. default='/var/lib/ambari-server/'
  3507. 'resources/Ambari-DDL-Postgres-CREATE.sql',
  3508. help="File with setup script")
  3509. parser.add_option('-r', '--drop-script-file', default="/var/lib/"
  3510. "ambari-server/resources/"
  3511. "Ambari-DDL-Postgres-DROP.sql",
  3512. help="File with drop script")
  3513. parser.add_option('-u', '--upgrade-script-file', default="/var/lib/"
  3514. "ambari-server/resources/upgrade/ddl/"
  3515. "Ambari-DDL-Postgres-UPGRADE-1.3.0.sql",
  3516. help="File with upgrade script")
  3517. parser.add_option('-t', '--upgrade-stack-script-file', default="/var/lib/"
  3518. "ambari-server/resources/upgrade/dml/"
  3519. "Ambari-DML-Postgres-UPGRADE_STACK.sql",
  3520. help="File with stack upgrade script")
  3521. parser.add_option('-j', '--java-home', default=None,
  3522. help="Use specified java_home. Must be valid on all hosts")
  3523. parser.add_option('-i', '--jdk-location', dest="jdk_location", default=None,
  3524. help="Use specified JDK file in local filesystem instead of downloading")
  3525. parser.add_option("-v", "--verbose",
  3526. action="store_true", dest="verbose", default=False,
  3527. help="Print verbose status messages")
  3528. parser.add_option("-s", "--silent",
  3529. action="store_true", dest="silent", default=False,
  3530. help="Silently accepts default prompt values")
  3531. parser.add_option('-g', '--debug', action="store_true", dest='debug', default=False,
  3532. help="Start ambari-server in debug mode")
  3533. parser.add_option('--database', default=None, help ="Database to use postgres|oracle", dest="database")
  3534. parser.add_option('--databasehost', default=None, help="Hostname of database server", dest="database_host")
  3535. parser.add_option('--databaseport', default=None, help="Database port", dest="database_port")
  3536. parser.add_option('--databasename', default=None, help="Database/Schema/Service name or ServiceID",
  3537. dest="database_name")
  3538. parser.add_option('--databaseusername', default=None, help="Database user login", dest="database_username")
  3539. parser.add_option('--databasepassword', default=None, help="Database user password", dest="database_password")
  3540. parser.add_option('--sidorsname', default="sname", help="Oracle database identifier type, Service ID/Service "
  3541. "Name sid|sname", dest="sid_or_sname")
  3542. (options, args) = parser.parse_args()
  3543. # set verbose
  3544. global VERBOSE
  3545. VERBOSE = options.verbose
  3546. # set silent
  3547. global SILENT
  3548. SILENT = options.silent
  3549. # debug mode
  3550. global SERVER_DEBUG_MODE
  3551. SERVER_DEBUG_MODE = options.debug
  3552. global DATABASE_INDEX
  3553. global PROMPT_DATABASE_OPTIONS
  3554. #perform checks
  3555. options.warnings = []
  3556. if options.database is None \
  3557. and options.database_host is None \
  3558. and options.database_port is None \
  3559. and options.database_name is None \
  3560. and options.database_username is None \
  3561. and options.database_password is None:
  3562. PROMPT_DATABASE_OPTIONS = True
  3563. elif not (options.database is not None
  3564. and options.database_host is not None
  3565. and options.database_port is not None
  3566. and options.database_name is not None
  3567. and options.database_username is not None
  3568. and options.database_password is not None):
  3569. parser.error('All database options should be set. Please see help for the options.')
  3570. #correct database
  3571. if options.database is not None and options.database not in DATABASE_NAMES:
  3572. parser.print_help()
  3573. parser.error("Unsupported Database " + options.database)
  3574. elif options.database is not None:
  3575. options.database = options.database.lower()
  3576. DATABASE_INDEX = DATABASE_NAMES.index(options.database)
  3577. #correct port
  3578. if options.database_port is not None:
  3579. correct=False
  3580. try:
  3581. port = int(options.database_port)
  3582. if 65536 > port > 0:
  3583. correct = True
  3584. except ValueError:
  3585. pass
  3586. if not correct:
  3587. parser.print_help()
  3588. parser.error("Incorrect database port " + options.database_port)
  3589. if options.database is not None and options.database == "postgres":
  3590. print "WARNING: HostName for postgres server " + options.database_host + \
  3591. " will be ignored: using localhost."
  3592. options.database_host = "localhost"
  3593. if options.sid_or_sname.lower() not in ["sid", "sname"]:
  3594. print "WARNING: Valid values for sid_or_sname are 'sid' or 'sname'. Use 'sid' if the db identifier type is " \
  3595. "Service ID. Use 'sname' if the db identifier type is Service Name"
  3596. parser.print_help()
  3597. exit(-1)
  3598. else:
  3599. options.sid_or_sname = options.sid_or_sname.lower()
  3600. if len(args) == 0:
  3601. print parser.print_help()
  3602. parser.error("No action entered")
  3603. action = args[0]
  3604. if action == UPGRADE_STACK_ACTION:
  3605. args_number_required = 2
  3606. else:
  3607. args_number_required = 1
  3608. if len(args) < args_number_required:
  3609. print parser.print_help()
  3610. parser.error("Invalid number of arguments. Entered: " + str(len(args)) + ", required: " + str(args_number_required))
  3611. options.exit_message = "Ambari Server '%s' completed successfully." % action
  3612. need_restart = True
  3613. try:
  3614. if action == SETUP_ACTION:
  3615. setup(options)
  3616. elif action == START_ACTION:
  3617. start(options)
  3618. elif action == STOP_ACTION:
  3619. stop(options)
  3620. elif action == RESET_ACTION:
  3621. reset(options)
  3622. elif action == STATUS_ACTION:
  3623. status(options)
  3624. elif action == UPGRADE_ACTION:
  3625. upgrade(options)
  3626. elif action == UPGRADE_STACK_ACTION:
  3627. stack_id = args[1]
  3628. upgrade_stack(options, stack_id)
  3629. elif action == LDAP_SETUP_ACTION:
  3630. setup_ldap()
  3631. elif action == SETUP_SECURITY_ACTION:
  3632. need_restart = setup_security(options)
  3633. else:
  3634. parser.error("Invalid action")
  3635. if action in ACTION_REQUIRE_RESTART and need_restart:
  3636. pstatus, pid = is_server_runing()
  3637. if pstatus:
  3638. print 'NOTE: Restart Ambari Server to apply changes'+ \
  3639. ' ("ambari-server restart|stop|start")'
  3640. if options.warnings:
  3641. for warning in options.warnings:
  3642. print_warning_msg(warning)
  3643. pass
  3644. options.exit_message = "Ambari Server '%s' completed with warnings." % action
  3645. pass
  3646. except FatalException as e:
  3647. if e.reason is not None:
  3648. print_error_msg("Exiting with exit code {0}. \nREASON: {1}".format(e.code, e.reason))
  3649. sys.exit(e.code)
  3650. except NonFatalException as e:
  3651. options.exit_message = "Ambari Server '%s' completed with warnings." % action
  3652. if e.reason is not None:
  3653. print_warning_msg(e.reason)
  3654. if options.exit_message is not None:
  3655. print options.exit_message
  3656. # A Python replacement for java.util.Properties
  3657. # Based on http://code.activestate.com/recipes
  3658. # /496795-a-python-replacement-for-javautilproperties/
  3659. class Properties(object):
  3660. def __init__(self, props=None):
  3661. self._props = {}
  3662. self._origprops = {}
  3663. self._keymap = {}
  3664. self.othercharre = re.compile(r'(?<!\\)(\s*\=)|(?<!\\)(\s*\:)')
  3665. self.othercharre2 = re.compile(r'(\s*\=)|(\s*\:)')
  3666. self.bspacere = re.compile(r'\\(?!\s$)')
  3667. def __parse(self, lines):
  3668. lineno = 0
  3669. i = iter(lines)
  3670. for line in i:
  3671. lineno += 1
  3672. line = line.strip()
  3673. if not line: continue
  3674. if line[0] == '#': continue
  3675. escaped = False
  3676. sepidx = -1
  3677. flag = 0
  3678. m = self.othercharre.search(line)
  3679. if m:
  3680. first, last = m.span()
  3681. start, end = 0, first
  3682. flag = 1
  3683. wspacere = re.compile(r'(?<![\\\=\:])(\s)')
  3684. else:
  3685. if self.othercharre2.search(line):
  3686. wspacere = re.compile(r'(?<![\\])(\s)')
  3687. start, end = 0, len(line)
  3688. m2 = wspacere.search(line, start, end)
  3689. if m2:
  3690. first, last = m2.span()
  3691. sepidx = first
  3692. elif m:
  3693. first, last = m.span()
  3694. sepidx = last - 1
  3695. while line[-1] == '\\':
  3696. nextline = i.next()
  3697. nextline = nextline.strip()
  3698. lineno += 1
  3699. line = line[:-1] + nextline
  3700. if sepidx != -1:
  3701. key, value = line[:sepidx], line[sepidx + 1:]
  3702. else:
  3703. key, value = line, ''
  3704. self.process_pair(key, value)
  3705. def process_pair(self, key, value):
  3706. oldkey = key
  3707. oldvalue = value
  3708. keyparts = self.bspacere.split(key)
  3709. strippable = False
  3710. lastpart = keyparts[-1]
  3711. if lastpart.find('\\ ') != -1:
  3712. keyparts[-1] = lastpart.replace('\\', '')
  3713. elif lastpart and lastpart[-1] == ' ':
  3714. strippable = True
  3715. key = ''.join(keyparts)
  3716. if strippable:
  3717. key = key.strip()
  3718. oldkey = oldkey.strip()
  3719. oldvalue = self.unescape(oldvalue)
  3720. value = self.unescape(value)
  3721. self._props[key] = None if value is None else value.strip()
  3722. if self._keymap.has_key(key):
  3723. oldkey = self._keymap.get(key)
  3724. self._origprops[oldkey] = None if oldvalue is None else oldvalue.strip()
  3725. else:
  3726. self._origprops[oldkey] = None if oldvalue is None else oldvalue.strip()
  3727. self._keymap[key] = oldkey
  3728. def unescape(self, value):
  3729. newvalue = value
  3730. if not value is None:
  3731. newvalue = value.replace('\:', ':')
  3732. newvalue = newvalue.replace('\=', '=')
  3733. return newvalue
  3734. def removeOldProp(self, key):
  3735. if self._origprops.has_key(key):
  3736. del self._origprops[key]
  3737. pass
  3738. def load(self, stream):
  3739. if type(stream) is not file:
  3740. raise TypeError, 'Argument should be a file object!'
  3741. if stream.mode != 'r':
  3742. raise ValueError, 'Stream should be opened in read-only mode!'
  3743. try:
  3744. self.fileName = os.path.abspath(stream.name)
  3745. lines = stream.readlines()
  3746. self.__parse(lines)
  3747. except IOError, e:
  3748. raise
  3749. def get_property(self, key):
  3750. return self._props.get(key, '')
  3751. def propertyNames(self):
  3752. return self._props.keys()
  3753. def getPropertyDict(self):
  3754. return self._props
  3755. def __getitem__(self, name):
  3756. return self.get_property(name)
  3757. def __getattr__(self, name):
  3758. try:
  3759. return self.__dict__[name]
  3760. except KeyError:
  3761. if hasattr(self._props, name):
  3762. return getattr(self._props, name)
  3763. def store(self, out, header=""):
  3764. """ Write the properties list to the stream 'out' along
  3765. with the optional 'header' """
  3766. if out.mode[0] != 'w':
  3767. raise ValueError,'Steam should be opened in write mode!'
  3768. try:
  3769. out.write(''.join(('#', ASF_LICENSE_HEADER, '\n')))
  3770. out.write(''.join(('#',header,'\n')))
  3771. # Write timestamp
  3772. tstamp = time.strftime('%a %b %d %H:%M:%S %Z %Y', time.localtime())
  3773. out.write(''.join(('#',tstamp,'\n')))
  3774. # Write properties from the pristine dictionary
  3775. for prop, val in self._origprops.items():
  3776. if val is not None:
  3777. out.write(''.join((prop,'=',val,'\n')))
  3778. out.close()
  3779. except IOError, e:
  3780. raise
  3781. if __name__ == "__main__":
  3782. try:
  3783. main()
  3784. except (KeyboardInterrupt, EOFError):
  3785. print("\nAborting ... Keyboard Interrupt.")
  3786. sys.exit(1)