ambari-server.py 149 KB

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