processors.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # -*- coding: utf-8 -*-
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  11. # implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import netaddr
  15. import os
  16. import uuid
  17. from .utils import force_ip
  18. from .utils import ScriptRunner
  19. from .exceptions import NetworkError
  20. from .exceptions import ParamProcessingError
  21. __all__ = ('ParamProcessingError', 'process_cidr', 'process_host',
  22. 'process_ssh_key', 'process_add_quotes_around_values',
  23. 'process_password', 'process_string_nofloat', 'process_bool')
  24. def process_cidr(param, param_name, config=None):
  25. """
  26. Corrects given CIDR if necessary.
  27. """
  28. if '/' not in param:
  29. # we need to skip this if single IP address has been given
  30. return param
  31. try:
  32. return str(netaddr.IPNetwork(param).cidr)
  33. except Exception as ex:
  34. raise ParamProcessingError(str(ex))
  35. def process_host(param, param_name, config=None):
  36. """
  37. Tries to change given parameter to IP address, if it is in hostname
  38. format
  39. """
  40. try:
  41. return force_ip(param, allow_localhost=True)
  42. except NetworkError as ex:
  43. raise ParamProcessingError(str(ex))
  44. def process_ssh_key(param, param_name, config=None):
  45. """
  46. Generates SSH key if given key in param doesn't exist. In case param
  47. is an empty string it generates default SSH key ($HOME/.ssh/id_rsa).
  48. """
  49. def create_key(path):
  50. # make path absolute
  51. path = os.path.expanduser(path)
  52. path = os.path.abspath(path)
  53. # create new ssh key
  54. local = ScriptRunner()
  55. local.append('ssh-keygen -f "%s" -N ""' % path)
  56. local.execute()
  57. if not param:
  58. key_file = '%s/.ssh/id_rsa' % os.environ["HOME"]
  59. param = '%s.pub' % key_file
  60. if not os.path.isfile(param):
  61. create_key(key_file)
  62. elif not os.path.isfile(param):
  63. key_file = param.endswith('.pub') and param[:-4] or param
  64. param = param.endswith('.pub') and param or ('%s.pub' % param)
  65. create_key(key_file)
  66. return param
  67. def process_add_quotes_around_values(param, param_name, config=None):
  68. """
  69. Add a single quote character around each element of a comma
  70. separated list of values
  71. """
  72. params_list = param.split(',')
  73. for index, elem in enumerate(params_list):
  74. if not elem.startswith("'"):
  75. elem = "'" + elem
  76. if not elem.endswith("'"):
  77. elem = elem + "'"
  78. params_list[index] = elem
  79. param = ','.join(params_list)
  80. return param
  81. def process_password(param, param_name, config=None):
  82. """
  83. Process passwords, checking the following:
  84. 1- If there is a user-entered password, use it
  85. 2- Otherwise, check for a global default password, and use it if available
  86. 3- As a last resort, generate a random password
  87. """
  88. if not hasattr(process_password, "pw_dict"):
  89. process_password.pw_dict = {}
  90. if param == "PW_PLACEHOLDER":
  91. if config["CONFIG_DEFAULT_PASSWORD"] != "":
  92. param = config["CONFIG_DEFAULT_PASSWORD"]
  93. else:
  94. # We need to make sure we store the random password we provide
  95. # and return it once we are asked for it again
  96. if param_name.endswith("_CONFIRMED"):
  97. unconfirmed_param = param_name[:-10]
  98. if unconfirmed_param in process_password.pw_dict:
  99. param = process_password.pw_dict[unconfirmed_param]
  100. else:
  101. param = uuid.uuid4().hex[:16]
  102. process_password.pw_dict[unconfirmed_param] = param
  103. elif param_name not in process_password.pw_dict:
  104. param = uuid.uuid4().hex[:16]
  105. process_password.pw_dict[param_name] = param
  106. else:
  107. param = process_password.pw_dict[param_name]
  108. return param
  109. def process_heat(param, param_name, config=None):
  110. if config["CONFIG_SAHARA_INSTALL"] == 'y':
  111. param = 'y'
  112. return param
  113. def process_string_nofloat(param, param_name, config=None):
  114. """
  115. Process a string, making sure it is *not* convertible into a float
  116. If it is, change it into a random 16 char string, and check again
  117. """
  118. while True:
  119. try:
  120. float(param)
  121. except ValueError:
  122. return param
  123. else:
  124. param = uuid.uuid4().hex[:16]
  125. def process_bool(param, param_name, config=None):
  126. """Converts param to appropriate boolean representation.
  127. Retunrs True if answer == y|yes|true, False if answer == n|no|false.
  128. """
  129. if param.lower() in ('y', 'yes', 'true'):
  130. return True
  131. elif param.lower() in ('n', 'no', 'false'):
  132. return False
  133. # Define silent processors
  134. for proc_func in (process_bool, process_add_quotes_around_values):
  135. proc_func.silent = True