Advertisement
Guest User

Untitled

a guest
Jun 11th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.93 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. """
  3. Script in charge of executing the post instantiation actions in the VNF-LCM CUDB instantiation workflow
  4. """
  5.  
  6. import argparse
  7. import json
  8. import logging
  9. import time
  10. import sys
  11. from imscommon import SSHUtility
  12.  
  13.  
  14. CUDB_CONFIG_DIR = "/home/coremw_appdata/incoming/cudb-install-temp/"
  15.  
  16. DEFAULT_ROOT_PASSWORD = "ericsson"
  17.  
  18. logger = logging.getLogger("postinstantiation")
  19.  
  20.  
  21. class ReturnCode(object):
  22. """
  23. Class holding constants for different return codes
  24. """
  25. RETURN_ERROR = 4
  26. REPEAT = 100
  27.  
  28.  
  29. def mkcmd(*parts):
  30. """ Create an escaped command line from its parts """
  31. return ' '.join("'{0}'".format(p) for p in parts)
  32.  
  33.  
  34. class Exit(Exception):
  35. """
  36. Exception class holding a return code
  37. """
  38. def __init__(self, return_code):
  39. self.return_code = return_code
  40.  
  41.  
  42. class PostInstantiation(object):
  43. """
  44. Class in charge of executing the post instantiation actions
  45. """
  46. class InputData:
  47. """
  48. Class holding the input parameters to the post instantation script
  49. """
  50. def __init__(
  51. self,
  52. config_dir,
  53. sc1_ip,
  54. key_file,
  55. root_password,
  56. ):
  57. """!
  58. Constructor.
  59. @param config_dir directory where the configuration for the VNF to be instantiated is stored
  60. @param sc1_ip IP adddress of the SC_2_1
  61. @param key_file file storing the key to access the VNF via ssh
  62. @param root_password password of the root user of the VNF
  63. """
  64. self.config_dir = config_dir
  65. self.sc1_ip = sc1_ip
  66. self.key_file = key_file
  67. self.root_password = root_password
  68.  
  69. def __repr__(self):
  70. """!
  71. Returns the string representation of the object
  72. @return the string representation of the object
  73. """
  74. return repr(self.__dict__)
  75.  
  76. def __init__(self):
  77. """!
  78. Constructor. Parses the arguments to the script and stores them in members
  79. """
  80. self.input_data = PostInstantiation.argument_parsing()
  81. self.ssh_sc1 = None
  82.  
  83. def __call__(self):
  84. """!
  85. Executes the post instantiation actions which basically monitor the
  86. installation of CUDB providing progress via the exit code and
  87. standard output to the workflow logs.
  88.  
  89. """
  90. self.ssh_sc1 = self.connect_to_host(host=self.input_data.sc1_ip,
  91. username="root",
  92. password=self.input_data.root_password,
  93. port=22)
  94. logger.debug("Checking if SC_2_1 is available")
  95. if not self.check_connection():
  96. print("Waiting for SC_2_1 to be ready")
  97. raise Exit(ReturnCode.REPEAT)
  98.  
  99. # Check if we have been here before
  100. (_, _, retcode) = self.ssh_sc1.run_command(mkcmd("ls", CUDB_CONFIG_DIR),
  101. fail_at_error=False)
  102.  
  103. if retcode != 0:
  104. time.sleep(10)
  105. print("Waiting for the configuration to be ready")
  106. raise Exit(ReturnCode.REPEAT)
  107.  
  108. (out, _, retcode) = self.execute_automated_install_progress_mon()
  109. if retcode == 200:
  110. print(out)
  111. raise Exit(ReturnCode.REPEAT)
  112.  
  113. if retcode != 0:
  114. sys.stderr.write(out + '\n')
  115. raise Exit(ReturnCode.RETURN_ERROR)
  116.  
  117. print("Finished CUDB Installation")
  118.  
  119. self.ssh_sc1.close()
  120.  
  121. def connect_to_host(self, host, username, password=None, port=22):
  122. """!
  123. Creates an ssh connection to the host using the parameters passed
  124. @param host The host to connect to
  125. @param username The username for the connection
  126. @param password The password
  127. @param port The port on which the connection will be established
  128. """
  129. return SSHUtility.SSHUtility(
  130. ip=host,
  131. username=username,
  132. password=password,
  133. port=port,
  134. keep_alive=True,
  135. )
  136.  
  137. def check_connection(self):
  138. """!
  139. Checks that the connection to both SC_2_1 and SC_2 is established
  140. """
  141. try:
  142. self.ssh_sc1.run_command("w")
  143. except:
  144. logger.exception("Couldn't execute remote command:")
  145.  
  146. return False
  147. else:
  148. return True
  149.  
  150. def execute_automated_install_progress_mon(self):
  151. """!
  152. Executes the cudbAutomatedInstallProgressTracker.py command to monitor the progress
  153. of the installation of CUDB returning with 0 when installation has finished,
  154. 200 when installation is in progress (to provide feedback via log with what
  155. s printed in stout) and a different
  156. error code in case of error in the execution of some step.
  157. """
  158. command = "cd /cluster/home/coremw_appdata/incoming/cudb-install-temp/; python ./cudbAutomatedInstallProgressTracker.py"
  159. logger.info("Executing: %s", command)
  160. ret = self.ssh_sc1.run_command(command, fail_at_error=False)
  161. logger.debug("End of execution of command: %s", command)
  162. return ret
  163.  
  164.  
  165. @staticmethod
  166. def argument_parsing():
  167. """!
  168. Parses the input arguments.
  169. """
  170. parser = argparse.ArgumentParser(
  171. description='post_instance hook for workflow')
  172. arg = parser.add_argument
  173. arg('-f', '--stack-details-file', metavar='<FILE>',
  174. help=('Path to the file containing the response of stack show '
  175. 'details command in json format.'),
  176. type=str, required=True)
  177. arg('-c', '--config-dir', metavar='<CONFIG_DIR>',
  178. help='Configuration directory', type=str, required=True)
  179. arg('-k', '--key-file', metavar='<KEY_FILE>',
  180. help='SSH public key', type=str, required=False)
  181. arg('-u', '--user-name', metavar='<USERNAME>',
  182. help='user name', type=str, required=False)
  183. arg('-p', '--password-file', metavar='<PASSWORD_FILE>',
  184. help='password file', type=str, required=False)
  185.  
  186. args = parser.parse_args()
  187.  
  188. logger.debug('Loading json file %r', args.stack_details_file)
  189. with open(args.stack_details_file) as json_file:
  190. stack_details = json.load(json_file)['stack']
  191.  
  192. config_dir = args.config_dir
  193. key_file = args.key_file
  194.  
  195. parameters = dict(
  196. (k, v.strip())
  197. for k, v in stack_details["parameters"].iteritems()
  198. )
  199.  
  200. sc1_ip = parameters.get("sysmgmt_SC1")
  201. root_password = parameters.get("root_password")
  202.  
  203. if root_password is None:
  204. logger.info(
  205. "Root's password not specified in parameters, "
  206. "USING DEFAULT PASSWORD")
  207. root_password = DEFAULT_ROOT_PASSWORD
  208.  
  209. data = PostInstantiation.InputData(
  210. config_dir, sc1_ip,
  211. key_file, root_password)
  212.  
  213. logger.debug("Input data: %r", data)
  214. return data
  215.  
  216.  
  217. def main():
  218. """!
  219. Creates an instance of the PostInstantiation class and invokes the __call__ method
  220. """
  221. post_instantiation = PostInstantiation()
  222. try:
  223. post_instantiation()
  224. except Exit as e:
  225. logger.debug("Exiting (%d)", e.return_code)
  226. sys.exit(e.return_code)
  227.  
  228.  
  229. if __name__ == '__main__':
  230. logging.basicConfig(
  231. # When set to DEBUG there could be problems with the workflow that does not accept answers longer than ... 50000
  232. #level=logging.DEBUG,
  233. level=logging.WARNING,
  234. #level=logging.INFO,
  235. #format='%(asctime)s [%(name)s] %(levelname)s %(message)s',
  236. format='%(asctime)s %(message)s',
  237. stream=sys.stdout,
  238. ) # pragma: no cover
  239. main() # pragma: no cover
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement