run_setup.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  10. # implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. import ConfigParser
  14. import copy
  15. import datetime
  16. import getpass
  17. import logging
  18. import os
  19. import re
  20. import sys
  21. from StringIO import StringIO
  22. import traceback
  23. import types
  24. import textwrap
  25. from optparse import OptionGroup
  26. from optparse import OptionParser
  27. import basedefs
  28. import validators
  29. from . import utils
  30. import processors
  31. import output_messages
  32. from .exceptions import FlagValidationError
  33. from .exceptions import ParamValidationError
  34. from packstack.modules.common import filtered_hosts
  35. from packstack.version import version_info
  36. from setup_controller import Controller
  37. controller = Controller()
  38. commandLineValues = {}
  39. # List to hold all values to be masked in logging (i.e. passwords and sensitive data)
  40. # TODO: read default values from conf_param?
  41. masked_value_set = set()
  42. tmpfiles = []
  43. def initLogging(debug):
  44. try:
  45. logFile = os.path.join(basedefs.DIR_LOG, basedefs.FILE_LOG)
  46. # Create the log file with specific permissions, puppet has a habbit of putting
  47. # passwords in logs
  48. os.close(os.open(logFile, os.O_CREAT | os.O_EXCL, 0o600))
  49. hdlr = logging.FileHandler(filename=logFile, mode='w')
  50. if (debug):
  51. level = logging.DEBUG
  52. else:
  53. level = logging.INFO
  54. fmts = '%(asctime)s::%(levelname)s::%(module)s::%(lineno)d::%(name)s:: %(message)s'
  55. dfmt = '%Y-%m-%d %H:%M:%S'
  56. fmt = logging.Formatter(fmts, dfmt)
  57. hdlr.setFormatter(fmt)
  58. logging.root.handlers = []
  59. logging.root.addHandler(hdlr)
  60. logging.root.setLevel(level)
  61. except:
  62. logging.error(traceback.format_exc())
  63. raise Exception(output_messages.ERR_EXP_FAILED_INIT_LOGGER)
  64. return logFile
  65. def _getInputFromUser(param):
  66. """
  67. this private func reads the data from the user
  68. for the given param
  69. """
  70. loop = True
  71. userInput = None
  72. try:
  73. if param.USE_DEFAULT:
  74. logging.debug("setting default value (%s) for key (%s)" % (mask(param.DEFAULT_VALUE), param.CONF_NAME))
  75. controller.CONF[param.CONF_NAME] = param.DEFAULT_VALUE
  76. else:
  77. while loop:
  78. # If the value was not supplied by the command line flags
  79. if param.CONF_NAME not in commandLineValues:
  80. message = StringIO()
  81. message.write(param.PROMPT)
  82. val_list = param.VALIDATORS or []
  83. if(validators.validate_regexp not in val_list
  84. and param.OPTION_LIST):
  85. message.write(" [%s]" % "|".join(param.OPTION_LIST))
  86. if param.DEFAULT_VALUE:
  87. message.write(" [%s] " % (str(param.DEFAULT_VALUE)))
  88. message.write(": ")
  89. message.seek(0)
  90. # mask password or hidden fields
  91. if (param.MASK_INPUT):
  92. userInput = getpass.getpass("%s :" % (param.PROMPT))
  93. else:
  94. userInput = raw_input(message.read())
  95. else:
  96. userInput = commandLineValues[param.CONF_NAME]
  97. # If DEFAULT_VALUE is set and user did not input anything
  98. if userInput == "" and len(str(param.DEFAULT_VALUE)) > 0:
  99. userInput = param.DEFAULT_VALUE
  100. # Param processing
  101. userInput = process_param_value(param, userInput)
  102. # If param requires validation
  103. try:
  104. validate_param_value(param, userInput)
  105. controller.CONF[param.CONF_NAME] = userInput
  106. loop = False
  107. except ParamValidationError:
  108. if param.LOOSE_VALIDATION:
  109. # If validation failed but LOOSE_VALIDATION is true, ask user
  110. answer = _askYesNo("User input failed validation, "
  111. "do you still wish to use it")
  112. loop = not answer
  113. if answer:
  114. controller.CONF[param.CONF_NAME] = userInput
  115. continue
  116. else:
  117. if param.CONF_NAME in commandLineValues:
  118. del commandLineValues[param.CONF_NAME]
  119. else:
  120. # Delete value from commandLineValues so that we will prompt the user for input
  121. if param.CONF_NAME in commandLineValues:
  122. del commandLineValues[param.CONF_NAME]
  123. loop = True
  124. except KeyboardInterrupt:
  125. # add the new line so messages wont be displayed in the same line as the question
  126. print("")
  127. raise
  128. except:
  129. logging.error(traceback.format_exc())
  130. raise Exception(output_messages.ERR_EXP_READ_INPUT_PARAM % (param.CONF_NAME))
  131. def input_param(param):
  132. """
  133. this func will read input from user
  134. and ask confirmation if needed
  135. """
  136. # We need to check if a param needs confirmation, (i.e. ask user twice)
  137. # Do not validate if it was given from the command line
  138. if param.NEED_CONFIRM and param.CONF_NAME not in commandLineValues:
  139. # create a copy of the param so we can call it twice
  140. confirmedParam = copy.deepcopy(param)
  141. confirmedParamName = param.CONF_NAME + "_CONFIRMED"
  142. confirmedParam.CONF_NAME = confirmedParamName
  143. confirmedParam.PROMPT = output_messages.INFO_CONF_PARAMS_PASSWD_CONFIRM_PROMPT
  144. # Now get both values from user (with existing validations)
  145. while True:
  146. _getInputFromUser(param)
  147. _getInputFromUser(confirmedParam)
  148. if controller.CONF[param.CONF_NAME] == controller.CONF[confirmedParamName]:
  149. logging.debug("Param confirmation passed, value for both questions is identical")
  150. break
  151. else:
  152. print(output_messages.INFO_VAL_PASSWORD_DONT_MATCH)
  153. else:
  154. _getInputFromUser(param)
  155. return param
  156. def _askYesNo(question=None):
  157. message = StringIO()
  158. while True:
  159. askString = "\r%s? (yes|no): " % (question)
  160. logging.debug("asking user: %s" % askString)
  161. message.write(askString)
  162. message.seek(0)
  163. raw = raw_input(message.read())
  164. if not len(raw):
  165. continue
  166. answer = raw[0].lower()
  167. logging.debug("user answered read: %s" % (answer))
  168. if answer not in 'yn':
  169. continue
  170. return answer == 'y'
  171. def _addDefaultsToMaskedValueSet():
  172. """
  173. For every param in conf_params
  174. that has MASK_INPUT enabled keep the default value
  175. in the 'masked_value_set'
  176. """
  177. global masked_value_set
  178. for group in controller.getAllGroups():
  179. for param in group.parameters.itervalues():
  180. # Keep default password values masked, but ignore default empty values
  181. if ((param.MASK_INPUT is True) and param.DEFAULT_VALUE != ""):
  182. masked_value_set.add(param.DEFAULT_VALUE)
  183. def _updateMaskedValueSet():
  184. """
  185. For every param in conf
  186. has MASK_INPUT enabled keep the user input
  187. in the 'masked_value_set'
  188. """
  189. global masked_value_set
  190. for confName in controller.CONF:
  191. # Add all needed values to masked_value_set
  192. if (controller.getParamKeyValue(confName, "MASK_INPUT") is True):
  193. masked_value_set.add(controller.CONF[confName])
  194. def mask(input):
  195. """
  196. Gets a dict/list/str and search maksked values in them.
  197. The list of masked values in is masked_value_set and is updated
  198. via the user input
  199. If it finds, it replaces them with '********'
  200. """
  201. output = copy.deepcopy(input)
  202. if isinstance(input, types.DictType):
  203. for key in input:
  204. if isinstance(input[key], types.StringType):
  205. output[key] = utils.mask_string(input[key],
  206. masked_value_set)
  207. if isinstance(input, types.ListType):
  208. for item in input:
  209. org = item
  210. orgIndex = input.index(org)
  211. if isinstance(item, types.StringType):
  212. item = utils.mask_string(item, masked_value_set)
  213. if item != org:
  214. output.remove(org)
  215. output.insert(orgIndex, item)
  216. if isinstance(input, types.StringType):
  217. output = utils.mask_string(input, masked_value_set)
  218. return output
  219. def removeMaskString(maskedString):
  220. """
  221. remove an element from masked_value_set
  222. we need to itterate over the set since
  223. calling set.remove() on an string that does not exit
  224. will raise an exception
  225. """
  226. global masked_value_set
  227. # Since we cannot remove an item from a set during itteration over
  228. # the said set, we only mark a flag and if the flag is set to True
  229. # we remove the string from the set.
  230. found = False
  231. for item in masked_value_set:
  232. if item == maskedString:
  233. found = True
  234. if found:
  235. masked_value_set.remove(maskedString)
  236. def validate_param_value(param, value):
  237. cname = param.CONF_NAME
  238. logging.debug("Validating parameter %s." % cname)
  239. val_list = param.VALIDATORS or []
  240. opt_list = param.OPTION_LIST
  241. for val_func in val_list:
  242. try:
  243. val_func(value, opt_list)
  244. except ParamValidationError as ex:
  245. print('Parameter %s failed validation: %s' % (cname, ex))
  246. raise
  247. def process_param_value(param, value):
  248. _value = value
  249. proclist = param.PROCESSORS or []
  250. for proc_func in proclist:
  251. is_silent = getattr(proc_func, 'silent', False)
  252. logging.debug("Processing value of parameter "
  253. "%s." % param.CONF_NAME)
  254. try:
  255. new_value = proc_func(_value, param.CONF_NAME, controller.CONF)
  256. if new_value != _value:
  257. if param.MASK_INPUT is False and not is_silent:
  258. msg = output_messages.INFO_CHANGED_VALUE
  259. print(msg % (_value, new_value))
  260. _value = new_value
  261. else:
  262. logging.debug("Processor returned the original "
  263. "value: %s" % _value)
  264. except processors.ParamProcessingError as ex:
  265. print("Value processing of parameter %s "
  266. "failed.\n%s" % (param.CONF_NAME, ex))
  267. raise
  268. return _value
  269. def _handleGroupCondition(config, conditionName, conditionValue):
  270. """
  271. handle params group pre/post condition
  272. checks if a group has a pre/post condition
  273. and validates the params related to the group
  274. """
  275. # If the post condition is a function
  276. if callable(conditionName):
  277. # Call the function conditionName with conf as the arg
  278. conditionValue = conditionName(controller.CONF)
  279. # If the condition is a string - just read it to global conf
  280. # We assume that if we get a string as a member it is the name of a member of conf_params
  281. elif isinstance(conditionName, types.StringType):
  282. conditionValue = _loadParamFromFile(config, "general", conditionName)
  283. else:
  284. # Any other type is invalid
  285. raise TypeError("%s type (%s) is not supported" % (conditionName, type(conditionName)))
  286. return conditionValue
  287. def _loadParamFromFile(config, section, param_name):
  288. """
  289. read param from file
  290. validate it
  291. and load to to global conf dict
  292. """
  293. param = controller.getParamByName(param_name)
  294. # Get value from answer file
  295. try:
  296. value = config.get(section, param_name)
  297. except ConfigParser.NoOptionError:
  298. value = None
  299. # Check for deprecated parameters
  300. deprecated = param.DEPRECATES if param.DEPRECATES is not None else []
  301. for old_name in deprecated:
  302. try:
  303. val = config.get(section, old_name)
  304. except ConfigParser.NoOptionError:
  305. continue
  306. if not val:
  307. # value is empty string
  308. continue
  309. if value is None:
  310. value = val
  311. if value != val:
  312. raise ValueError('Parameter %(param_name)s deprecates '
  313. 'following parameters:\n%(deprecated)s.\n'
  314. 'Please either use parameter %(param_name)s '
  315. 'or use same value for all deprecated '
  316. 'parameters.' % locals())
  317. if deprecated and value is not None:
  318. controller.MESSAGES.append('Deprecated parameter has been used '
  319. 'in answer file. Please use parameter '
  320. '%(param_name)s next time. This '
  321. 'parameter deprecates following '
  322. 'parameters: %(deprecated)s.'
  323. % locals())
  324. if value is None:
  325. # Let's use default value if we have one
  326. value = getattr(param, 'DEFAULT_VALUE', None)
  327. if value is None:
  328. raise KeyError('Parser cannot find option %s in answer file.'
  329. % param_name)
  330. # Validate param value using its validation func
  331. value = process_param_value(param, value)
  332. validate_param_value(param, value)
  333. # Keep param value in our never ending global conf
  334. controller.CONF[param.CONF_NAME] = value
  335. # Add message to controller.MESSAGES if defined in parameter
  336. if param.MESSAGE:
  337. _handleParamMessage(param, value)
  338. return value
  339. def _handleAnswerFileParams(answerFile):
  340. """
  341. handle loading and validating
  342. params from answer file
  343. supports reading single or group params
  344. """
  345. try:
  346. logging.debug("Starting to handle config file")
  347. # Read answer file
  348. fconf = ConfigParser.ConfigParser()
  349. fconf.read(answerFile)
  350. # Iterate all the groups and check the pre/post conditions
  351. for group in controller.getAllGroups():
  352. # Get all params per group
  353. # Handle pre conditions for group
  354. preConditionValue = True
  355. if group.PRE_CONDITION:
  356. preConditionValue = _handleGroupCondition(fconf, group.PRE_CONDITION, preConditionValue)
  357. # Handle pre condition match with case insensitive values
  358. if preConditionValue == group.PRE_CONDITION_MATCH:
  359. for param in group.parameters.itervalues():
  360. _loadParamFromFile(fconf, "general", param.CONF_NAME)
  361. # Handle post conditions for group only if pre condition passed
  362. postConditionValue = True
  363. if group.POST_CONDITION:
  364. postConditionValue = _handleGroupCondition(fconf, group.POST_CONDITION, postConditionValue)
  365. # Handle post condition match for group
  366. if postConditionValue != group.POST_CONDITION_MATCH:
  367. logging.error("The group condition (%s) returned: %s, which differs from the excpeted output: %s" %
  368. (group.GROUP_NAME, postConditionValue, group.POST_CONDITION_MATCH))
  369. raise ValueError(output_messages.ERR_EXP_GROUP_VALIDATION_ANS_FILE %
  370. (group.GROUP_NAME, postConditionValue, group.POST_CONDITION_MATCH))
  371. else:
  372. logging.debug("condition (%s) passed" % group.POST_CONDITION)
  373. else:
  374. logging.debug("no post condition check for group %s" % group.GROUP_NAME)
  375. else:
  376. logging.debug("skipping params group %s since value of group validation is %s" % (group.GROUP_NAME, preConditionValue))
  377. except Exception as e:
  378. logging.error(traceback.format_exc())
  379. raise Exception(output_messages.ERR_EXP_HANDLE_ANSWER_FILE % (e))
  380. def _getanswerfilepath():
  381. path = None
  382. msg = "Could not find a suitable path on which to create the answerfile"
  383. ts = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
  384. p = os.path.expanduser("~/")
  385. if os.access(p, os.W_OK):
  386. path = os.path.abspath(os.path.join(p, "packstack-answers-%s.txt" % ts))
  387. msg = "A new answerfile was created in: %s" % path
  388. controller.MESSAGES.append(msg)
  389. return path
  390. def _gettmpanswerfilepath():
  391. path = None
  392. msg = "Could not find a suitable path on which to create the temporary answerfile"
  393. ts = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
  394. p = os.path.expanduser("~/")
  395. if os.access(p, os.W_OK):
  396. path = os.path.abspath(os.path.join(p, "tmp-packstack-answers-%s.txt" % ts))
  397. tmpfiles.append(path)
  398. return path
  399. def _handleInteractiveParams():
  400. try:
  401. logging.debug("Groups: %s" % ', '.join([x.GROUP_NAME for x in controller.getAllGroups()]))
  402. for group in controller.getAllGroups():
  403. preConditionValue = True
  404. logging.debug("going over group %s" % group.GROUP_NAME)
  405. # If pre_condition is set, get Value
  406. if group.PRE_CONDITION:
  407. preConditionValue = _getConditionValue(group.PRE_CONDITION)
  408. inputLoop = True
  409. # If we have a match, i.e. condition returned True, go over all params in the group
  410. if preConditionValue == group.PRE_CONDITION_MATCH:
  411. while inputLoop:
  412. for param in group.parameters.itervalues():
  413. if not param.CONDITION:
  414. input_param(param)
  415. # update password list, so we know to mask them
  416. _updateMaskedValueSet()
  417. postConditionValue = True
  418. # If group has a post condition, we check it after we get the input from
  419. # all the params in the group. if the condition returns False, we loop over the group again
  420. if group.POST_CONDITION:
  421. postConditionValue = _getConditionValue(group.POST_CONDITION)
  422. if postConditionValue == group.POST_CONDITION_MATCH:
  423. inputLoop = False
  424. else:
  425. # we clear the value of all params in the group
  426. # in order to re-input them by the user
  427. for param in group.parameters.itervalues():
  428. if param.CONF_NAME in controller.CONF:
  429. del controller.CONF[param.CONF_NAME]
  430. if param.CONF_NAME in commandLineValues:
  431. del commandLineValues[param.CONF_NAME]
  432. else:
  433. inputLoop = False
  434. else:
  435. logging.debug("no post condition check for group %s" % group.GROUP_NAME)
  436. _displaySummary()
  437. except KeyboardInterrupt:
  438. logging.error("keyboard interrupt caught")
  439. raise Exception(output_messages.ERR_EXP_KEYBOARD_INTERRUPT)
  440. except Exception:
  441. logging.error(traceback.format_exc())
  442. raise
  443. except:
  444. logging.error(traceback.format_exc())
  445. raise Exception(output_messages.ERR_EXP_HANDLE_PARAMS)
  446. def _handleParams(configFile):
  447. _addDefaultsToMaskedValueSet()
  448. if configFile:
  449. _handleAnswerFileParams(configFile)
  450. else:
  451. _handleInteractiveParams()
  452. def _getConditionValue(matchMember):
  453. returnValue = False
  454. if isinstance(matchMember, types.FunctionType):
  455. returnValue = matchMember(controller.CONF)
  456. elif isinstance(matchMember, types.StringType):
  457. # we assume that if we get a string as a member it is the name
  458. # of a member of conf_params
  459. if matchMember not in controller.CONF:
  460. param = controller.getParamByName(matchMember)
  461. input_param(param)
  462. returnValue = controller.CONF[matchMember]
  463. else:
  464. raise TypeError("%s type (%s) is not supported" % (matchMember, type(matchMember)))
  465. return returnValue
  466. def _displaySummary():
  467. print(output_messages.INFO_DSPLY_PARAMS)
  468. print("=" * (len(output_messages.INFO_DSPLY_PARAMS) - 1))
  469. logging.info("*** User input summary ***")
  470. for group in controller.getAllGroups():
  471. for param in group.parameters.itervalues():
  472. if not param.USE_DEFAULT and param.CONF_NAME in controller.CONF:
  473. cmdOption = param.CMD_OPTION
  474. l = 30 - len(cmdOption)
  475. maskParam = param.MASK_INPUT
  476. # Only call mask on a value if the param has MASK_INPUT set to True
  477. if maskParam:
  478. logging.info("%s: %s" % (cmdOption, mask(controller.CONF[param.CONF_NAME])))
  479. print("%s:" % (cmdOption) + " " * l + mask(controller.CONF[param.CONF_NAME]))
  480. else:
  481. # Otherwise, log & display it as it is
  482. logging.info("%s: %s" % (cmdOption, str(controller.CONF[param.CONF_NAME])))
  483. print("%s:" % (cmdOption) + " " * l + str(controller.CONF[param.CONF_NAME]))
  484. logging.info("*** User input summary ***")
  485. answer = _askYesNo(output_messages.INFO_USE_PARAMS)
  486. if not answer:
  487. logging.debug("user chose to re-enter the user parameters")
  488. for group in controller.getAllGroups():
  489. for param in group.parameters.itervalues():
  490. if param.CONF_NAME in controller.CONF:
  491. if not param.MASK_INPUT:
  492. param.DEFAULT_VALUE = controller.CONF[param.CONF_NAME]
  493. # Remove the string from mask_value_set in order
  494. # to remove values that might be over overwritten.
  495. removeMaskString(controller.CONF[param.CONF_NAME])
  496. del controller.CONF[param.CONF_NAME]
  497. if param.CONF_NAME in commandLineValues:
  498. del commandLineValues[param.CONF_NAME]
  499. print("")
  500. logging.debug("calling handleParams in interactive mode")
  501. return _handleParams(None)
  502. else:
  503. logging.debug("user chose to accept user parameters")
  504. def _printAdditionalMessages():
  505. if len(controller.MESSAGES) > 0:
  506. print(output_messages.INFO_ADDTIONAL_MSG)
  507. for msg in controller.MESSAGES:
  508. print(output_messages.INFO_ADDTIONAL_MSG_BULLET % (msg))
  509. def _addFinalInfoMsg(logFile):
  510. """
  511. add info msg to the user finalizing the
  512. successfull install of rhemv
  513. """
  514. controller.MESSAGES.append(output_messages.INFO_LOG_FILE_PATH % (logFile))
  515. controller.MESSAGES.append(
  516. output_messages.INFO_MANIFEST_PATH % (basedefs.PUPPET_MANIFEST_DIR))
  517. def _summaryParamsToLog():
  518. if len(controller.CONF) > 0:
  519. logging.debug("*** The following params were used as user input:")
  520. for group in controller.getAllGroups():
  521. for param in group.parameters.itervalues():
  522. if param.CONF_NAME in controller.CONF:
  523. maskedValue = mask(controller.CONF[param.CONF_NAME])
  524. logging.debug("%s: %s" % (param.CMD_OPTION, maskedValue))
  525. def _handleParamMessage(param, value):
  526. """
  527. add message to the information displayed at the end of the execution
  528. for parameters with MESSAGE option. if parameter has MESSAGE_VALUES
  529. option, message will be only displayed if the provided value is in
  530. MESSAGE_VALUES.
  531. """
  532. message_values = param.MESSAGE_VALUES if param.MESSAGE_VALUES is not None else None
  533. if not message_values or value in message_values:
  534. message = utils.color_text('Parameter %s: %s'
  535. % (param.CONF_NAME, param.MESSAGE), 'red')
  536. if message not in controller.MESSAGES:
  537. controller.MESSAGES.append(message)
  538. def runSequences():
  539. controller.runAllSequences()
  540. def _main(options, configFile=None, logFile=None):
  541. print(output_messages.INFO_HEADER)
  542. print("\n" + output_messages.INFO_LOG_FILE_PATH % logFile)
  543. # Get parameters
  544. _handleParams(configFile)
  545. # Generate answer file, only if no answer file was provided
  546. if not options.answer_file:
  547. path = _getanswerfilepath()
  548. if path:
  549. generateAnswerFile(path)
  550. # If an answer file was provided, some options may have been overriden
  551. # Overwrite answer file with updated options
  552. else:
  553. generateAnswerFile(options.answer_file)
  554. # Update masked_value_list with user input values
  555. _updateMaskedValueSet()
  556. # Print masked conf
  557. logging.debug(mask(controller.CONF))
  558. # Start configuration stage
  559. print("\n" + output_messages.INFO_INSTALL)
  560. # Initialize Sequences
  561. initPluginsSequences()
  562. # Run main setup logic
  563. runSequences()
  564. # Lock rhevm version
  565. # _lockRpmVersion()
  566. # Print info
  567. _addFinalInfoMsg(logFile)
  568. print(output_messages.INFO_INSTALL_SUCCESS)
  569. def remove_remote_var_dirs(options, config, messages):
  570. """
  571. Removes the temp directories on remote hosts,
  572. doesn't remove data on localhost
  573. """
  574. for host in filtered_hosts(config):
  575. try:
  576. host_dir = config['HOST_DETAILS'][host]['tmpdir']
  577. except KeyError:
  578. # Nothing was added to this host yet, so we have nothing to delete
  579. continue
  580. if options.debug:
  581. # we keep temporary directories on hosts in debug mode
  582. messages.append(
  583. 'Note temporary directory {host_dir} on host {host} was '
  584. 'not deleted for debugging purposes.'.format(**locals())
  585. )
  586. continue
  587. logging.debug(output_messages.INFO_REMOVE_REMOTE_VAR % (host_dir, host))
  588. server = utils.ScriptRunner(host)
  589. server.append('rm -rf %s' % host_dir)
  590. try:
  591. server.execute()
  592. except Exception as e:
  593. msg = output_messages.ERR_REMOVE_REMOTE_VAR % (host_dir, host)
  594. logging.error(msg)
  595. logging.exception(e)
  596. messages.append(utils.color_text(msg, 'red'))
  597. def remove_temp_files():
  598. """
  599. Removes any temporary files generated during
  600. configuration
  601. """
  602. for myfile in tmpfiles:
  603. try:
  604. os.unlink(myfile)
  605. except Exception as e:
  606. msg = output_messages.ERR_REMOVE_TMP_FILE % (myfile)
  607. logging.error(msg)
  608. logging.exception(e)
  609. controller.MESSAGES.append(utils.color_text(msg, 'red'))
  610. def generateAnswerFile(outputFile, overrides={}):
  611. sep = os.linesep
  612. fmt = ("%(comment)s%(separator)s%(conf_name)s=%(default_value)s"
  613. "%(separator)s")
  614. outputFile = os.path.expanduser(outputFile)
  615. # Remove the answer file so it can be recreated as the current user with
  616. # the mode -rw-------
  617. if os.path.exists(outputFile):
  618. os.remove(outputFile)
  619. fd = os.open(outputFile, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
  620. with os.fdopen(fd, "w") as ans_file:
  621. ans_file.write("[general]%s" % os.linesep)
  622. for group in controller.getAllGroups():
  623. for param in group.parameters.itervalues():
  624. comm = param.USAGE or ''
  625. comm = textwrap.fill(comm,
  626. initial_indent='%s# ' % sep,
  627. subsequent_indent='# ',
  628. break_long_words=False)
  629. value = controller.CONF.get(param.CONF_NAME,
  630. param.DEFAULT_VALUE)
  631. args = {'comment': comm,
  632. 'separator': sep,
  633. 'default_value': overrides.get(param.CONF_NAME, value),
  634. 'conf_name': param.CONF_NAME}
  635. ans_file.write(fmt % args)
  636. def single_step_aio_install(options, logFile):
  637. """Installs an All in One host on this host."""
  638. options.install_hosts = utils.get_localhost_ip()
  639. single_step_install(options, logFile)
  640. def single_step_install(options, logFile):
  641. answerfilepath = _gettmpanswerfilepath()
  642. if not answerfilepath:
  643. _printAdditionalMessages()
  644. return
  645. # We're going to generate the answerfile and run Packstack in a single step
  646. # todo this we generate the answerfile and pass in some override variables to
  647. # override the default hosts
  648. overrides = {}
  649. hosts = options.install_hosts
  650. hosts = [host.strip() for host in hosts.split(',')]
  651. for group in controller.getAllGroups():
  652. for param in group.parameters.itervalues():
  653. # and directives that contain _HOST are set to the controller node
  654. if param.CONF_NAME.find("_HOST") != -1:
  655. overrides[param.CONF_NAME] = hosts[0]
  656. # If there are more than one host, all but the first are a compute nodes
  657. if len(hosts) > 1:
  658. overrides["CONFIG_COMPUTE_HOSTS"] = ','.join(hosts[1:])
  659. # We can also override defaults with command line options
  660. _set_command_line_values(options)
  661. for key, value in commandLineValues.items():
  662. overrides[key] = value
  663. generateAnswerFile(answerfilepath, overrides)
  664. _main(options, answerfilepath, logFile)
  665. def initCmdLineParser():
  666. """
  667. Initiate the optparse object, add all the groups and general command line flags
  668. and returns the optparse object
  669. """
  670. # Init parser and all general flags
  671. usage = "usage: %prog [options] [--help]"
  672. parser = OptionParser(usage=usage, version="%prog {0}".format(version_info.version_string()))
  673. parser.add_option("--gen-answer-file", help="Generate a template of an answer file.")
  674. parser.add_option("--answer-file", help="Runs the configuration in non-interactive mode, extracting all information from the"
  675. "configuration file. using this option excludes all other options")
  676. parser.add_option("--install-hosts", help="Install on a set of hosts in a single step. The format should be a comma separated list "
  677. "of hosts, the first is setup as a controller, and the others are setup as compute nodes."
  678. "if only a single host is supplied then it is setup as an all in one installation. An answerfile "
  679. "will also be generated and should be used if Packstack needs to be run a second time ")
  680. parser.add_option("--allinone", action="store_true", help="Shorthand for --install-hosts=<local ipaddr> --novanetwork-pubif=<dev> "
  681. "--novacompute-privif=lo --novanetwork-privif=lo --os-swift-install=y --nagios-install=y "
  682. ", this option can be used to install an all in one OpenStack on this host")
  683. parser.add_option("-t", "--timeout", default=300, help="The timeout for puppet Exec calls")
  684. parser.add_option("-o", "--options", action="store_true", dest="options", help="Print details on options available in answer file(rst format)")
  685. parser.add_option("-d", "--debug", action="store_true", default=False, help="Enable debug in logging")
  686. parser.add_option("-y", "--dry-run", action="store_true", default=False, help="Don't execute, just generate manifests")
  687. # For each group, create a group option
  688. for group in controller.getAllGroups():
  689. groupParser = OptionGroup(parser, group.DESCRIPTION)
  690. for param in group.parameters.itervalues():
  691. cmdOption = param.CMD_OPTION
  692. paramUsage = param.USAGE
  693. optionsList = param.OPTION_LIST
  694. useDefault = param.USE_DEFAULT
  695. if not useDefault:
  696. groupParser.add_option("--%s" % cmdOption, help=paramUsage)
  697. # Add group parser to main parser
  698. parser.add_option_group(groupParser)
  699. return parser
  700. def printOptions():
  701. """
  702. print and document the available options to the answer file (rst format)
  703. """
  704. # For each group, create a group option
  705. for group in controller.getAllGroups():
  706. print("%s" % group.DESCRIPTION)
  707. print("-" * len(group.DESCRIPTION) + "\n")
  708. for param in group.parameters.itervalues():
  709. cmdOption = param.CONF_NAME
  710. paramUsage = param.USAGE
  711. optionsList = param.OPTION_LIST or ""
  712. print("%s" % (("**%s**" % str(cmdOption)).ljust(30)))
  713. print(" %s" % paramUsage + "\n")
  714. def plugin_compare(x, y):
  715. """
  716. Used to sort the plugin file list
  717. according to the number at the end of the plugin module
  718. """
  719. x_match = re.search(".+\_(\d\d\d)", x)
  720. x_cmp = x_match.group(1)
  721. y_match = re.search(".+\_(\d\d\d)", y)
  722. y_cmp = y_match.group(1)
  723. return int(x_cmp) - int(y_cmp)
  724. def loadPlugins():
  725. """
  726. Load All plugins from ./plugins
  727. """
  728. sys.path.append(basedefs.DIR_PLUGINS)
  729. sys.path.append(basedefs.DIR_MODULES)
  730. fileList = [f for f in os.listdir(basedefs.DIR_PLUGINS) if f[0] != "_"]
  731. fileList = sorted(fileList, cmp=plugin_compare)
  732. for item in fileList:
  733. # Looking for files that end with ###.py, example: a_plugin_100.py
  734. match = re.search("^(.+\_\d\d\d)\.py$", item)
  735. if match:
  736. try:
  737. moduleToLoad = match.group(1)
  738. logging.debug("importing module %s, from file %s", moduleToLoad, item)
  739. moduleobj = __import__(moduleToLoad)
  740. moduleobj.__file__ = os.path.join(basedefs.DIR_PLUGINS, item)
  741. globals()[moduleToLoad] = moduleobj
  742. checkPlugin(moduleobj)
  743. controller.addPlugin(moduleobj)
  744. except:
  745. logging.error("Failed to load plugin from file %s", item)
  746. logging.error(traceback.format_exc())
  747. raise Exception("Failed to load plugin from file %s" % item)
  748. def checkPlugin(plugin):
  749. for funcName in ['initConfig', 'initSequences']:
  750. if not hasattr(plugin, funcName):
  751. raise ImportError("Plugin %s does not contain the %s function" % (plugin.__class__, funcName))
  752. def countCmdLineFlags(options, flag):
  753. """
  754. counts all command line flags that were supplied, excluding the supplied flag name
  755. """
  756. counter = 0
  757. # make sure only flag was supplied
  758. for key, value in options.__dict__.items():
  759. if key in (flag, 'debug', 'timeout', 'dry_run', 'default_password'):
  760. next
  761. # If anything but flag was called, increment
  762. elif value:
  763. counter += 1
  764. return counter
  765. def validateSingleFlag(options, flag):
  766. counter = countCmdLineFlags(options, flag)
  767. if counter > 0:
  768. flag = flag.replace("_", "-")
  769. msg = output_messages.ERR_ONLY_1_FLAG % ("--%s" % flag)
  770. raise FlagValidationError(msg)
  771. def initPluginsConfig():
  772. for plugin in controller.getAllPlugins():
  773. plugin.initConfig(controller)
  774. def initPluginsSequences():
  775. for plugin in controller.getAllPlugins():
  776. plugin.initSequences(controller)
  777. def _set_command_line_values(options):
  778. for key, value in options.__dict__.items():
  779. # Replace the _ with - in the string since optparse replace _ with -
  780. for group in controller.getAllGroups():
  781. param = group.search("CMD_OPTION", key.replace("_", "-"))
  782. if len(param) > 0 and value:
  783. commandLineValues[param[0].CONF_NAME] = value
  784. def main():
  785. options = ""
  786. try:
  787. # Load Plugins
  788. loadPlugins()
  789. initPluginsConfig()
  790. optParser = initCmdLineParser()
  791. # Do the actual command line parsing
  792. # Try/Except are here to catch the silly sys.exit(0) when calling rhevm-setup --help
  793. (options, args) = optParser.parse_args()
  794. if options.options:
  795. printOptions()
  796. raise SystemExit
  797. # Initialize logging
  798. logFile = initLogging(options.debug)
  799. # Parse parameters
  800. runConfiguration = True
  801. confFile = None
  802. controller.CONF['DEFAULT_EXEC_TIMEOUT'] = options.timeout
  803. controller.CONF['DRY_RUN'] = options.dry_run
  804. controller.CONF['DIR_LOG'] = basedefs.DIR_LOG
  805. # If --gen-answer-file was supplied, do not run main
  806. if options.gen_answer_file:
  807. answerfilepath = _gettmpanswerfilepath()
  808. if not answerfilepath:
  809. _printAdditionalMessages()
  810. return
  811. # We can also override defaults with command line options
  812. overrides = {}
  813. _set_command_line_values(options)
  814. for key, value in commandLineValues.items():
  815. overrides[key] = value
  816. generateAnswerFile(answerfilepath, overrides)
  817. _handleParams(answerfilepath)
  818. generateAnswerFile(options.gen_answer_file)
  819. # Are we installing an all in one
  820. elif options.allinone:
  821. if getattr(options, 'answer_file', None):
  822. msg = ('Please use either --allinone or --answer-file, '
  823. 'but not both.')
  824. raise FlagValidationError(msg)
  825. single_step_aio_install(options, logFile)
  826. # Are we installing in a single step
  827. elif options.install_hosts:
  828. single_step_install(options, logFile)
  829. # Otherwise, run main()
  830. else:
  831. # Make sure only --answer-file was supplied
  832. if options.answer_file:
  833. validateSingleFlag(options, "answer_file")
  834. # If using an answer file, setting a default password
  835. # does not really make sense
  836. if getattr(options, 'default_password', None):
  837. msg = ('Please do not set --default-password '
  838. 'when specifying an answer file.')
  839. raise FlagValidationError(msg)
  840. confFile = os.path.expanduser(options.answer_file)
  841. if not os.path.exists(confFile):
  842. raise Exception(output_messages.ERR_NO_ANSWER_FILE % confFile)
  843. else:
  844. _set_command_line_values(options)
  845. _main(options, confFile, logFile)
  846. except FlagValidationError as ex:
  847. optParser.error(str(ex))
  848. except Exception as e:
  849. logging.error(traceback.format_exc())
  850. print("\n" + utils.color_text("ERROR : " + str(e), 'red'))
  851. try:
  852. print(output_messages.ERR_CHECK_LOG_FILE_FOR_MORE_INFO % (logFile))
  853. except NameError:
  854. pass
  855. sys.exit(1)
  856. finally:
  857. remove_remote_var_dirs(options, controller.CONF, controller.MESSAGES)
  858. remove_temp_files()
  859. # Always print user params to log
  860. _printAdditionalMessages()
  861. _summaryParamsToLog()
  862. if __name__ == "__main__":
  863. main()