Beispiel #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 ''
Beispiel #2
0
  def setup_main():
    prism_ip = cluster['external_ip']
    prism_user = cluster['prism_user']
    prism_password = cluster['prism_password']
    print('Setup-1 : Make session to Prism.')
    logger = NutanixRestApiClient.create_logger('setup_cluster_rest.log', logging.DEBUG)
    try:
      print('  ip : {}'.format(prism_ip))
      print('  user : {}'.format(prism_user))
      print('  password : {}'.format(prism_password))
      session = NutanixRestApiClient(prism_ip, prism_user, prism_password, logger)
      print('  Success')
    except:
      print('  Failed with error "Connection or Credential problem"')
      raise ErrorException('Failed to change password.')

    print('Setup-2 : Basics')
    basics = segment['basics']
    language = basics['language']
    setup_basics(session, language)

    print('Setup-3 : Container')
    containers = segment['containers']
    #print(containers)
    setup_container(session, containers)

    print('Setup-4 : Network')
    networks = []
    for (name, config_network) in segment['networks'].items():
      if not config_network['use_dhcp']:
        networks.append((name, config_network['vlan']))
        continue

      network = 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))
      networks.append((network, prefix, gateway, dns, pools))
    setup_network(session, networks)
    #print(networks)

    print('Setup-5 : Images')
    images = []
    for (name, config_image) in segment['images'].items():
      images.append((name, config_image['container'], config_image['url']))
    setup_image(session, images)
Beispiel #3
0
    def __init__(self, prism_ip, prism_user, prism_password):
        self.prism_ip = prism_ip
        self.prism_user = prism_user
        self.prism_password = prism_password

        self.session = NutanixRestApiClient(prism_ip, prism_user,
                                            prism_password)
        (success, result) = self.session.get_ipmi_host_cvm_ips()
        if not success:
            raise Exception("Failed to get IPs")
        (self.ipmi_list, self.host_list, self.cvm_list) = result
 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.')
Beispiel #5
0
def eula(segment, cluster):
  prism_ip = cluster['external_ip']
  prism_user = cluster['prism_user']
  password = cluster['prism_password']

  print('Eula Start!!')
  print('Eula-1 : Initialize Prism password to temporary one "{}"'.format(TEMPORARY_PASSWORD))
  (success, result) = NutanixRestApiClient.change_default_system_password(prism_ip, INITIAL_PASSWORD, TEMPORARY_PASSWORD)
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(result['error']))
    raise ErrorException('Failed to initialize Prism password. "{}"'.format(result['error']))

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

  print('Eula-3 : Set Eula (User:Yuichi, Company:Nutanix, Position:Inside SE)')
  (success, result) = session.set_eula('Yuichi', 'Nutanix', 'Inside SE')
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to set Eula.')

  print('Eula-4 : Set initial pulse settings.')
  (success, result) = session.set_initial_pulse()
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to set initial pulse setting.')

  print('Eula-5 : Set initial alert settings.')
  (success, result) = session.set_initial_alerts()
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to set alert settings.')

  print('Eula-6 : Change password to "{}"'.format(password))
  if password == TEMPORARY_PASSWORD:
    print('  Same password. Skip.')
  else:
    (success, result) = session.change_password(TEMPORARY_PASSWORD, password)
    if success:
      print('  Success')
    else:
      print('  Failed with error "{}"'.format(response['error']))
      raise ErrorException('Failed to change password.')

  print('Eula Finished!!')
Beispiel #6
0
    def start_cluster(self):
        print('start_cluster()')

        def issue_cluster_start(cvm_ip, user, password):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(cvm_ip,
                               username=user,
                               password=password,
                               timeout=3.0)
                command = '/usr/local/nutanix/cluster/bin/cluster start'
                stdin, stdout, stderr = client.exec_command(command)
                print(stdout.read().decode().strip())
                print(stderr.read().decode().strip())
            except Exception as e:
                print(e)

        # Try login to Prism. If fails, issue "cluster start" on first CVM
        for i in range(5):
            try:
                NutanixRestApiClient(self.prism_ip, self.prism_user,
                                     self.prism_password)
                return
            except:
                issue_cluster_start(self.cvm_ips[0], 'nutanix', 'nutanix/4u')
            time.sleep(30)
Beispiel #7
0
def check(foundation_vm, segment, cluster):

  netmask = cluster['netmask']
  gateway = cluster['gateway']
  nodeinfo_list = get_nodeinfo_list(cluster)
  cluster_name = cluster['name']
  external_ip = cluster['external_ip']
  name_server = cluster['name_server']
  ntp_server = cluster['ntp_server']

  print('Check Start!!')
  print('Check-01 : Connecting to Foundation VM.')
  logger = NutanixRestApiClient.create_logger('foundation_rest.log', logging.DEBUG)
  try:
    fvm_ip = foundation_vm['ip_address']
    fvm_user = foundation_vm['user']
    fvm_password = foundation_vm['password']
    print('  ip : {}'.format(fvm_ip))
    print('  user : {}'.format(fvm_user))
    print('  password : {}'.format(fvm_password))
    client = NutanixFoundationClient(fvm_ip, fvm_user, fvm_password, logger)
    (success, fvm_version) = client.get_version()
    if not success:
      raise Exception()
    print('  Success. Foundation VM version "{}"'.format(fvm_version))
  except:
    print('  Failed with error "Unable to make session."'.format(fvm_ip, fvm_user, fvm_password))
    raise ErrorException('Failed to make session to foundation vm "{}"'.format(fvm_ip))

  print('Check-02 : Check IPMI MAC and IPMI address are OK.')
  check_ipmi_mac_ip(client, cluster)

  print('Check Finished!!')
 def connect_to_fvm(self):
     print('Foundation-01 : Connecting to Foundation VM.')
     logger = NutanixRestApiClient.create_logger('foundation_rest.log',
                                                 logging.DEBUG)
     foundation_vm = self.cluster['foundation_vms']
     fvm_ip = foundation_vm['ip_addresses'][0]
     fvm_user = foundation_vm['user']
     fvm_password = foundation_vm['password']
     print('  ip : {}'.format(fvm_ip))
     print('  user : {}'.format(fvm_user))
     print('  password : {}'.format(fvm_password))
     self.client = NutanixFoundationClient(fvm_ip, fvm_user, fvm_password,
                                           logger)
 def set_initial_password(self):
     print('Eula Start!!')
     print(
         'Eula-1 : Initialize Prism password to temporary one "{}"'.format(
             self.TEMPORARY_PASSWORD))
     (success,
      result) = NutanixRestApiClient.change_default_system_password(
          self.prism_ip, self.INITIAL_PASSWORD, self.TEMPORARY_PASSWORD)
     if success:
         print('  Success')
     else:
         print('  Failed with error "{}"'.format(result['error']))
         raise ErrorException(
             'Failed to initialize Prism password. "{}"'.format(
                 result['error']))
Beispiel #10
0
 def check_cluster_up(ip, user, password):
     try:
         client = NutanixRestApiClient(ip, user, password)
     except Exception as e:
         return False
     return True
Beispiel #11
0
class ClusterStopOps:
    def __init__(self, prism_ip, prism_user, prism_password):
        self.prism_ip = prism_ip
        self.prism_user = prism_user
        self.prism_password = prism_password

        self.session = NutanixRestApiClient(prism_ip, prism_user,
                                            prism_password)
        (success, result) = self.session.get_ipmi_host_cvm_ips()
        if not success:
            raise Exception("Failed to get IPs")
        (self.ipmi_list, self.host_list, self.cvm_list) = result

    def stop_calm(self):
        print('stop_calm()')
        pass

    def stop_non_agent_guests(self):
        print('stop_non_agent_guests()')

        def get_poweredon_guest_vms():
            (_, pc_vms) = self.session.get_pc_vms()
            (_, fsvms) = self.session.get_fsvms()
            (_, agentvms) = self.session.get_agent_vms()
            special_vms = pc_vms + fsvms + agentvms
            (_, poweredon_vms) = self.session.get_poweredon_vms()

            poweredon_guestvms = []
            for vm in poweredon_vms:
                if vm not in special_vms:
                    poweredon_guestvms.append(vm)
            return poweredon_guestvms

        def stop_vms(vm_list, force=False):
            if len(vm_list) == 0:
                return

            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(self.prism_ip,
                               username=self.prism_user,
                               password=self.prism_password)

                if force:
                    command = 'acli vm.off {}'.format(
                        ','.join(poweredon_guest_vms))
                else:
                    command = 'acli vm.shutdown {}'.format(
                        ','.join(poweredon_guest_vms))
                stdin, stdout, stderr = client.exec_command(command)
            except Exception as e:
                print(e)

        # Stop normal guest vms.
        for i in range(5):
            poweredon_guest_vms = get_poweredon_guest_vms()
            if len(poweredon_guest_vms) == 0:
                break

            if i > 3:
                stop_vms(poweredon_guest_vms, True)
            else:
                stop_vms(poweredon_guest_vms)
            time.sleep(10)

    def stop_files(self):
        print('stop_files()')

        def issue_stop_command():
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(self.prism_ip,
                               username=self.prism_user,
                               password=self.prism_password)

                command = '/usr/local/nutanix/minerva/bin/afs infra.stop'
                stdin, stdout, stderr = client.exec_command(command)
            except Exception as e:
                print(e)

        def is_all_fsvm_down(fsvms):
            for fsvm in fsvms:
                (_, power) = self.session.get_vm_powerstate(fsvm)
                logger.debug('FSVM {} : Power {}'.format(fsvm, power))
                if power == 'on':
                    return False
            return True

        issue_stop_command()
        (_, fsvms) = self.session.get_fsvms()
        for i in range(20):
            if is_all_fsvm_down(fsvms):
                return
            time.sleep(10)

    def stop_pc(self):
        print('stop_pc()')

        def pc_cluster_stop(pc_ip):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(pc_ip,
                               username='******',
                               password='******')
                command = "/home/nutanix/prism/cli/ncli cluster stop"
                stdin, stdout, stderr = client.exec_command(command)
                print(stdout.read().decode().strip())
            except Exception as e:
                print(e)

        def is_pc_cluster_stop(pc_ip):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(pc_ip,
                               username='******',
                               password='******')
                command = "/usr/local/nutanix/cluster/bin/cluster status | grep state"
                stdin, stdout, stderr = client.exec_command(command)
                buf = stdout.read().decode().strip()
                cluster_state = buf.split()
                return cluster_state[-1] == "stop"
            except Exception as e:
                print(e)
            return False

        def pc_vm_stop(pc_ip):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(pc_ip,
                               username='******',
                               password='******')

                command = "sudo /usr/sbin/shutdown -h now"
                stdin, stdout, stderr = client.exec_command(command)
                print(stdout.read().decode().strip())
            except Exception as e:
                print(e)

        def is_pc_vm_down(pc_vm):
            try:
                (_, power) = self.session.get_vm_powerstate(pc_vm)
                logger.debug('PCVM {} : Power {}'.format(pc_vm, power))
                if power == 'on':
                    return False
            except Exception as e:
                print(e)
                return False

        # Get PC VMs
        (_, pc_vms) = self.session.get_pc_vms()

        # Exit if no pcs are up
        if (len(pc_vms)) == 0:
            return
        all_down = True
        for pc_vm in pc_vms:
            if not is_pc_vm_down(pc_vm):
                all_down = False
                break
        if all_down:
            return

        # Cluster stop on all PCs
        for pc_vm in pc_vms:
            (_, pc_ip) = self.session.get_vm_ip(pc_vm)
            if not is_pc_cluster_stop(pc_ip):
                pc_cluster_stop(pc_ip)
                for i in range(5):
                    if is_pc_cluster_stop(pc_ip):
                        return
                    time.sleep(10)

        # Power Off on all PCs
        for pc_vm in pc_vms:
            if not is_pc_vm_down(pc_vm):
                (_, pc_ip) = self.session.get_vm_ip(pc_vm)
                pc_vm_stop(pc_ip)
                for i in range(10):
                    if is_pc_vm_down(pc_vm):
                        break
                    time.sleep(5)

    def stop_all_vms(self):
        print('stop_all_vms()')

        def stop_vms(vm_list, force=False):
            if len(vm_list) == 0:
                return

            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(self.prism_ip,
                               username=self.prism_user,
                               password=self.prism_password)

                if force:
                    command = 'acli vm.off {}'.format(
                        ','.join(poweredon_guest_vms))
                else:
                    command = 'acli vm.shutdown {}'.format(
                        ','.join(poweredon_guest_vms))
                stdin, stdout, stderr = client.exec_command(command)
            except Exception as e:
                print(e)

        # Stop all VMs
        for i in range(5):
            (_, poweredon_vms) = self.session.get_poweredon_vms()

            if i > 3:
                stop_vms(poweredon_vms, True)
            else:
                stop_vms(poweredon_vms)
            time.sleep(10)

    def stop_cluster(self):
        print('stop_cluster()')

        def cluster_stop(cvm_ip):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(cvm_ip,
                               username='******',
                               password='******')
                command = "/home/nutanix/prism/cli/ncli cluster stop"
                stdin, stdout, stderr = client.exec_command(command)
                print(stdout.read().decode().strip())
            except Exception as e:
                print(e)

        def is_cluster_stop(cvm_ip):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(cvm_ip,
                               username='******',
                               password='******')
                command = "/usr/local/nutanix/cluster/bin/cluster status | grep state"
                stdin, stdout, stderr = client.exec_command(command)
                buf = stdout.read().decode().strip()
                cluster_state = buf.split()
                return cluster_state[-1] == "stop"
            except Exception as e:
                print(e)
            return False

        cluster_stop(self.cvm_list[0])
        for i in range(10):
            is_cluster_stop(self.cvm_list[0])
            time.sleep(5)

    def stop_cvms(self):
        print('stop_cvms()')

        def cvm_stop(cvm_ip):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(cvm_ip,
                               username='******',
                               password='******')

                command = "sudo /usr/sbin/shutdown -h now"
                stdin, stdout, stderr = client.exec_command(command)
            except Exception as e:
                print(e)

        def is_cvm_stop(host_ip):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(host_ip, username='******', password='******')

                command = "bash -c 'virsh list | wc -l'"
                stdin, stdout, stderr = client.exec_command(command)
                buf = stdout.read().decode().strip()
                return buf == '3'
            except Exception as e:
                print(e)
            return False

        for cvm_ip in self.cvm_list:
            cvm_stop(cvm_ip)

        for i in range(10):
            all_down = True
            for host_ip in self.host_list:
                if not is_cvm_stop(host_ip):
                    all_down = False
            if all_down:
                return
            time.sleep(5)

    def stop_hosts(self):
        print('stop_hosts()')

        def stop_host(host_ip):
            try:
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(host_ip, username='******', password='******')

                command = "shutdown -h now"
                stdin, stdout, stderr = client.exec_command(command)
            except Exception as e:
                print(e)

        for host_ip in self.host_list:
            stop_host(host_ip)
Beispiel #12
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.')
Beispiel #13
0
def foundation(foundation_vm, segment, cluster, nos_package):

  netmask = cluster['netmask']
  gateway = cluster['gateway']
  nodeinfo_list = get_nodeinfo_list(cluster)
  cluster_name = cluster['name']
  external_ip = cluster['external_ip']
  name_server = cluster['name_server']
  ntp_server = cluster['ntp_server']

  print('Foundation Start!!')
  print('Foundation-01 : Connecting to Foundation VM.')
  logger = NutanixRestApiClient.create_logger('foundation_rest.log', logging.DEBUG)
  try:
    fvm_ip = foundation_vm['ip_address']
    fvm_user = foundation_vm['user']
    fvm_password = foundation_vm['password']
    print('  ip : {}'.format(fvm_ip))
    print('  user : {}'.format(fvm_user))
    print('  password : {}'.format(fvm_password))
    client = NutanixFoundationClient(fvm_ip, fvm_user, fvm_password, logger)
    (success, fvm_version) = client.get_version()
    if not success:
      raise Exception()
    print('  Success. Foundation VM version "{}"'.format(fvm_version))
  except:
    print('  Failed with error "Unable to make session."'.format(fvm_ip, fvm_user, fvm_password))
    raise ErrorException('Failed to make session to foundation vm "{}"'.format(fvm_ip))

  print('Foundation-02 : Check IPMI MAC and IPMI address are OK.')
  check_ipmi_mac_ip(client, cluster)

  print('Foundation-03 : Check currently imaging or not.')
  (success, result) = client.get_progress()
  if not success:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to get Foundation VM progress.')
  if result['imaging_stopped']:
    print('  Success. Foundation VM is not imaging now.')
  else:
    print('  Failed. Foundation VM is imaging now. If it is not intended, please abort manually on the Foundation VM.')
    raise ErrorException('Foundation VM is imaging now. Please wait or abort manually.')

  print('Foundation-04 : Check whether foundation vm has nos_package or not.')
  (success, nos_packages) = client.get_nos_packages()
  if not success:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to get AOS package list.')
  if nos_package in nos_packages:
    print('  Foundation VM has nos_package "{}"'.format(nos_package))
  else:
    print('  Foundation VM does not have nos_package "{}". But having "{}". Abort.'.format(nos_package, nos_packages))
    raise ErrorException("Foundation VM doesn't have nos_package '{}'".format(nos_package))

  print('Foundation-05 : Reset Foundation VM')
  (success, result) = client.reset_state()
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException("Failed to reset foundation state.")

  print('Foundation-06 : Choose primary nic to "eth0"')
  (success, nics) = client.get_nics()
  if not success:
    print('  Failed. Unable to get nic list.')
    raise ErrorException("Failed to get nic list")
  primary_nic = ''
  for (nic, nic_info) in nics.items():
    if nic_info['name'].lower() == 'eth0':
      primary_nic = nic
      break
  if primary_nic == '':
    print('  Failed. Unable to find "eth0".')
    raise ErrorException('Failed to find nic "eth0" on nic list')
  (success, result) = client.choose_primary_nic(primary_nic)
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to choose "eth0" as primary nic.')

  print('Foundation-07 : Configure IPMI IP. May take few minutes.')
  (success, result) = client.ipmi_config(netmask, gateway, nodeinfo_list,
    cluster_name, external_ip, name_server, ntp_server, nos_package)
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to configure IPMI IP.')

  print('Foundation-08 : Pre Check. May take few minutes.')
  (success, result) = client.pre_check(netmask, gateway, nodeinfo_list,
    cluster_name, external_ip, name_server, ntp_server, nos_package)
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to do pre check.')

  print('Foundation-09 : Kicking imaging nodes.')
  (success, result) = client.image_nodes(netmask, gateway, nodeinfo_list,
    cluster_name, external_ip, name_server, ntp_server, nos_package)
  if success:
    print('  Success')
  else:
    print('  Failed with error "{}"'.format(response['error']))
    raise ErrorException('Failed to kick imaging nodes.')

  print('Foundation-10 : Polling foundation status till complete.')
  error_counter = 0
  while(True):
    (success, result) = client.get_progress()
    if success:
      for node in result['nodes']:
        node_ip = node['hypervisor_ip']
        node_percent = node['percent_complete']
        node_status = node['status']
        print('node({}) {}% : {}'.format(node_ip, node_percent, node_status))

      cluster_name = result['clusters'][0]['cluster_name']
      cluster_percent = result['clusters'][0]['percent_complete']
      cluster_status = result['clusters'][0]['status']
      print('cluster({}) {}% : {}'.format(cluster_name, cluster_percent, cluster_status))
      aggregate_percent = result['aggregate_percent_complete']
      print('aggregate {}%'.format(aggregate_percent))

      if aggregate_percent == 100:
        time.sleep(3)
        break
      else:
        if result['abort_session'] == True:
          print('  Failed. Imaging was aborted.')
          exit(-1)
        elif result['imaging_stopped'] == True:
          print('  Failed. Imaging was stopped.')
          raise ErrorException('Failed. Imaging was stopped.')

      print('=== waiting 15 secs ===')
      time.sleep(15)
      error_counter = 0

    else:
      # failed to get status
      print('  Failed to getting progress. Try again soon.')
      time.sleep(3)
      error_counter += 1
      if error_counter >= 5:
        print('  Failed to getting progress 5 times sequentially. Abort.')
        raise ErrorException('Failed to getting progress 5 times sequentially.')
    
  print('Foundation Finished!!')