Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2
- """
- Script in charge of executing the post instantiation actions in the VNF-LCM CUDB instantiation workflow
- """
- import argparse
- import json
- import logging
- import time
- import sys
- from imscommon import SSHUtility
- CUDB_CONFIG_DIR = "/home/coremw_appdata/incoming/cudb-install-temp/"
- DEFAULT_ROOT_PASSWORD = "ericsson"
- logger = logging.getLogger("postinstantiation")
- class ReturnCode(object):
- """
- Class holding constants for different return codes
- """
- RETURN_ERROR = 4
- REPEAT = 100
- def mkcmd(*parts):
- """ Create an escaped command line from its parts """
- return ' '.join("'{0}'".format(p) for p in parts)
- class Exit(Exception):
- """
- Exception class holding a return code
- """
- def __init__(self, return_code):
- self.return_code = return_code
- class PostInstantiation(object):
- """
- Class in charge of executing the post instantiation actions
- """
- class InputData:
- """
- Class holding the input parameters to the post instantation script
- """
- def __init__(
- self,
- config_dir,
- sc1_ip,
- key_file,
- root_password,
- ):
- """!
- Constructor.
- @param config_dir directory where the configuration for the VNF to be instantiated is stored
- @param sc1_ip IP adddress of the SC_2_1
- @param key_file file storing the key to access the VNF via ssh
- @param root_password password of the root user of the VNF
- """
- self.config_dir = config_dir
- self.sc1_ip = sc1_ip
- self.key_file = key_file
- self.root_password = root_password
- def __repr__(self):
- """!
- Returns the string representation of the object
- @return the string representation of the object
- """
- return repr(self.__dict__)
- def __init__(self):
- """!
- Constructor. Parses the arguments to the script and stores them in members
- """
- self.input_data = PostInstantiation.argument_parsing()
- self.ssh_sc1 = None
- def __call__(self):
- """!
- Executes the post instantiation actions which basically monitor the
- installation of CUDB providing progress via the exit code and
- standard output to the workflow logs.
- """
- self.ssh_sc1 = self.connect_to_host(host=self.input_data.sc1_ip,
- username="root",
- password=self.input_data.root_password,
- port=22)
- logger.debug("Checking if SC_2_1 is available")
- if not self.check_connection():
- print("Waiting for SC_2_1 to be ready")
- raise Exit(ReturnCode.REPEAT)
- # Check if we have been here before
- (_, _, retcode) = self.ssh_sc1.run_command(mkcmd("ls", CUDB_CONFIG_DIR),
- fail_at_error=False)
- if retcode != 0:
- time.sleep(10)
- print("Waiting for the configuration to be ready")
- raise Exit(ReturnCode.REPEAT)
- (out, _, retcode) = self.execute_automated_install_progress_mon()
- if retcode == 200:
- print(out)
- raise Exit(ReturnCode.REPEAT)
- if retcode != 0:
- sys.stderr.write(out + '\n')
- raise Exit(ReturnCode.RETURN_ERROR)
- print("Finished CUDB Installation")
- self.ssh_sc1.close()
- def connect_to_host(self, host, username, password=None, port=22):
- """!
- Creates an ssh connection to the host using the parameters passed
- @param host The host to connect to
- @param username The username for the connection
- @param password The password
- @param port The port on which the connection will be established
- """
- return SSHUtility.SSHUtility(
- ip=host,
- username=username,
- password=password,
- port=port,
- keep_alive=True,
- )
- def check_connection(self):
- """!
- Checks that the connection to both SC_2_1 and SC_2 is established
- """
- try:
- self.ssh_sc1.run_command("w")
- except:
- logger.exception("Couldn't execute remote command:")
- return False
- else:
- return True
- def execute_automated_install_progress_mon(self):
- """!
- Executes the cudbAutomatedInstallProgressTracker.py command to monitor the progress
- of the installation of CUDB returning with 0 when installation has finished,
- 200 when installation is in progress (to provide feedback via log with what
- s printed in stout) and a different
- error code in case of error in the execution of some step.
- """
- command = "cd /cluster/home/coremw_appdata/incoming/cudb-install-temp/; python ./cudbAutomatedInstallProgressTracker.py"
- logger.info("Executing: %s", command)
- ret = self.ssh_sc1.run_command(command, fail_at_error=False)
- logger.debug("End of execution of command: %s", command)
- return ret
- @staticmethod
- def argument_parsing():
- """!
- Parses the input arguments.
- """
- parser = argparse.ArgumentParser(
- description='post_instance hook for workflow')
- arg = parser.add_argument
- arg('-f', '--stack-details-file', metavar='<FILE>',
- help=('Path to the file containing the response of stack show '
- 'details command in json format.'),
- type=str, required=True)
- arg('-c', '--config-dir', metavar='<CONFIG_DIR>',
- help='Configuration directory', type=str, required=True)
- arg('-k', '--key-file', metavar='<KEY_FILE>',
- help='SSH public key', type=str, required=False)
- arg('-u', '--user-name', metavar='<USERNAME>',
- help='user name', type=str, required=False)
- arg('-p', '--password-file', metavar='<PASSWORD_FILE>',
- help='password file', type=str, required=False)
- args = parser.parse_args()
- logger.debug('Loading json file %r', args.stack_details_file)
- with open(args.stack_details_file) as json_file:
- stack_details = json.load(json_file)['stack']
- config_dir = args.config_dir
- key_file = args.key_file
- parameters = dict(
- (k, v.strip())
- for k, v in stack_details["parameters"].iteritems()
- )
- sc1_ip = parameters.get("sysmgmt_SC1")
- root_password = parameters.get("root_password")
- if root_password is None:
- logger.info(
- "Root's password not specified in parameters, "
- "USING DEFAULT PASSWORD")
- root_password = DEFAULT_ROOT_PASSWORD
- data = PostInstantiation.InputData(
- config_dir, sc1_ip,
- key_file, root_password)
- logger.debug("Input data: %r", data)
- return data
- def main():
- """!
- Creates an instance of the PostInstantiation class and invokes the __call__ method
- """
- post_instantiation = PostInstantiation()
- try:
- post_instantiation()
- except Exit as e:
- logger.debug("Exiting (%d)", e.return_code)
- sys.exit(e.return_code)
- if __name__ == '__main__':
- logging.basicConfig(
- # When set to DEBUG there could be problems with the workflow that does not accept answers longer than ... 50000
- #level=logging.DEBUG,
- level=logging.WARNING,
- #level=logging.INFO,
- #format='%(asctime)s [%(name)s] %(levelname)s %(message)s',
- format='%(asctime)s %(message)s',
- stream=sys.stdout,
- ) # pragma: no cover
- main() # pragma: no cover
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement