Exemplo n.º 1
0
 def get_hypervisor(ip, user, password):
     try:
         client = NutanixRestApiClient(ip, user, password)
         (success, version) = client.get_hypervisor()
         if not success:
             return ''
         return version
     except Exception as e:
         return ''
Exemplo n.º 2
0
class SetupOps:
    def __init__(self, cluster):
        self.cluster = cluster

        self.prism_ip = cluster['external_ip']
        self.prism_user = cluster['prism_user']
        self.prism_password = cluster['prism_password']

    def connect_to_prism(self):
        print('Setup-1 : Make session to Prism')
        logger = NutanixRestApiClient.create_logger('setup_cluster_rest.log',
                                                    logging.DEBUG)
        try:
            self.session = NutanixRestApiClient(self.prism_ip, self.prism_user,
                                                self.prism_password, logger)
            print('  Success')
        except:
            print('  Failed with error "Connection or Credential problem"')
            raise ErrorException('Failed to make connection to Prism.')

    def setup_basics(self):
        basics = self.cluster['basics']
        language = basics['language']

        print('  Change language to "{}"'.format(language))
        language = language.lower()
        lmap = {'en-us': 'en-US', 'ja-jp': 'ja-JP', 'zh-cn': 'zh-CN'}
        if language not in ['en-us', 'ja-jp', 'zh-cn']:
            print('    Failed. supports only {}'.format(
                ['en-US', 'ja-JP', 'zh-CN']))
            raise ErrorException('Failed. Unsupported language "{}".'.format(
                lmap[language]))

        (success, result) = self.session.change_language(lmap[language])
        if success:
            print('    Success')
        else:
            print('    Failed with error "{}"'.format(response['error']))
            raise ErrorException('Failed to change language.')

    def setup_containers(self):
        containers = self.cluster['containers']

        # get existing containers
        (success, existing_containers) = self.session.get_container_names()
        if not success:
            raise Exception(
                'Error happens on getting existing container names.')
        print('  Existing containers "{}"'.format(existing_containers))

        # delete useless containers
        for existing_container in existing_containers:
            if existing_container in containers:
                continue
            (success, container_info
             ) = self.session.get_container_info(existing_container)
            if not success:
                raise Exception(
                    'Error happens on getting container info "{}".'.format(
                        existing_container))
            if container_info['usage'] != '0':
                continue
            print(
                '  Deleting useless container "{}"'.format(existing_container))
            (success, _) = self.session.delete_container(existing_container)
            if not success:
                raise Exception(
                    'Error happens on deleting container "{}".'.format(
                        existing_container))

        # create containers which doesn't exist.
        task_list = []
        for container in containers:
            if container in existing_containers:
                continue
            print('  Creating container "{}"'.format(container))
            (success, taskuuid) = self.session.create_container(container)
            if not success:
                raise Exception(
                    'Error happens on creating container "{}".'.format(
                        container))
            task_list.append(taskuuid)

        # wait till end
        self.wait_tasks(task_list)

    def setup_networks(self):
        networks = []
        for (name, config_network) in self.cluster['networks'].items():

            if not config_network['use_dhcp']:
                # NON DHCP
                vlan = config_network['vlan']
                networks.append((name, vlan))
                continue

            # DHCP
            vlan = config_network['vlan']
            network_address = config_network['network']
            prefix = config_network['prefix']
            gateway = config_network['gateway']
            dns = config_network['dns']
            pools = []
            for config_pool in config_network['pools']:
                config_from = config_pool['from']
                if 'POCID' in config_from:
                    config_from = config_from.replace('POCID',
                                                      cluster['POCID'])
                config_to = config_pool['to']
                if 'POCID' in config_to:
                    config_to = config_to.replace('POCID', cluster['POCID'])
                pools.append((config_from, config_to))
            network = (name, vlan, network_address, prefix, gateway, dns,
                       pools)
            networks.append(network)

        (success, existing_networks) = self.session.get_network_names()
        if not success:
            raise Exception('Error happens on getting existing networks.')
        print('  Existing networks "{}"'.format(existing_networks))

        network_names = []
        for network in networks:
            network_names.append(network[0])

        # delete useless network
        for existing_network in existing_networks:
            if existing_network in network_names:
                continue
            (success, used) = self.session.is_network_used(existing_network)
            if not success:
                raise Exception('Error happens on getting existing networks.')
            if used:
                continue

            print('  Deleting useless network "{}"'.format(existing_network))
            (success, taskuuid) = self.session.delete_network(existing_network)
            if not success:
                raise Exception('Error happens on getting existing networks.')

        # Hypervisor
        (success, hypervisor) = self.session.get_hypervisor()
        if not success:
            raise Exception('Error happens on getting hypervisor.')

        # add new network
        task_list = []
        for network in networks:
            name = network[0]
            if name in existing_networks:
                continue

            print('  Creating network "{}"'.format(name))
            if len(network) == 2:
                (name, vlan) = network
                (success, taskuuid) = self.session.create_network(name, vlan)
                if not success:
                    raise Exception(
                        'Error happens on creating network "{}"'.format(name))
            else:
                (name, vlan, network, prefix, gateway, dns, pools) = network
                if hypervisor != 'AHV':
                    (success,
                     taskuuid) = self.session.create_network(name, vlan)
                    if not success:
                        raise Exception(
                            'Error happens on creating network "{}"'.format(
                                name))
                else:
                    (success, taskuuid) = self.session.create_network_managed(
                        name, vlan, network, prefix, gateway, pools, dns)
                    if not success:
                        raise Exception(
                            'Error happens on creating network "{}"'.format(
                                name))

            task_list.append(taskuuid)

        # wait till end
        self.wait_tasks(task_list)

    def setup_images(self):
        images = []
        for (name, config_image) in self.cluster['images'].items():
            images.append(
                (name, config_image['container'], config_image['url']))

        # check whether container exist or not
        (success, containers) = self.session.get_container_names()
        if not success:
            raise Exception('Error happens on checking container existance.')

        # get existing images
        (success, existing_images) = self.session.get_image_names()
        if not success:
            raise Exception('Error happens on getting existing images names.')
        print('  Existing images "{}"'.format(existing_images))

        # upload images which doesn't exist
        task_list = []
        for (image_name, image_container, image_url) in images:
            if image_name in existing_images:
                continue
            if image_container not in containers:
                print(
                    '  Failed. container "{}" does not exist on the cluster.'.
                    format(image_container))
                raise Exception('Error happens on uploading image.')

            print('  Request uploading {} : {}'.format(image_name, image_url))
            (success,
             taskuuid) = self.session.upload_image(image_url, image_container,
                                                   image_name)
            if not success:
                raise Exception('Error happens on uploading image.')
            task_list.append(taskuuid)

        # wait till end
        #self.wait_tasks(task_list)

    def wait_tasks(self, uuids, interval=5):
        first = True
        while (True):
            (success, tasks) = self.session.get_tasks_status()
            if not success:
                print(tasks)
                continue
                #raise Exception('Error happens on getting tasks status.')

            finished = True
            for task in tasks:
                if task['uuid'] in uuids:
                    if first:
                        print('Wait till all tasks end. Polling interval {}s.'.
                              format(interval))
                        first = False
                    print('{} {}% : {}'.format(task['method'], task['percent'],
                                               task['uuid']))
                    finished = False
                else:
                    # Child or other task
                    pass

            if finished:
                break
            else:
                print('--')
            time.sleep(interval)

        if not first:
            print('All tasks end.')