Exemplo n.º 1
0
def main():
    set_log_level(logging.ERROR)
    nc = nuage_connect(nuage_username, nuage_password, nuage_enterprise,
                       nuage_host, nuage_port)

    delete_pending_list = []
    vsp = get_nuage_entity(nc.user, 'VSP', '', True)

    print 'Searching for VMs in \'DELETE_PENDING\' state...'
    vscs = get_nuage_entity(vsp, 'VSC', '', False)
    for vsc in vscs:
        vrss = get_nuage_entity(vsc, 'VRS', '', False)
        for vrs in vrss:
            vms = get_nuage_entity(vrs, 'VM', '', False)
            for vm in vms:
                if vm.status == 'DELETE_PENDING':
                    if vm.id not in delete_pending_list:
                        delete_pending_list.append(vm.id)
                        print '%s,%s,%s,%s,%s,%s,%s' % (
                            vm.enterprise_name, vm.name, vm.status,
                            vm.reason_type, vm.delete_expiry, vm.delete_mode,
                            vm.id)

    print '\nTotal number of VMs in \'DELETE_PENDING\' state: %s\n' % len(
        delete_pending_list)

    if delete_pending_list:
        delete = raw_input("Delete all VMs above? [y/n]: ")
        if delete.lower() == 'y' or delete.lower() == 'yes':
            for vm_id in delete_pending_list:
                vm = vspk.NUVM(id=vm_id)
                vm.fetch()
                print 'Deleting VM \'%s\'...' % vm.name,
                vm.delete()
                print '[DONE]'
Exemplo n.º 2
0
 def _create_vm(self):
     self.nuage_object = vsdk.NUVM(name=self.vm_name,
                                   uuid=self.vm_uuid,
                                   interfaces=self.vm_interface_list,
                                   external_id=self.cms_name)
     try:
         self.logger.debug('Trying to save VM %s.' % self.vm_name)
         self.nc.create_child(self.nuage_object)
         self.logger.info('VM %s is created by user %s.' % (self.nuage_object.name, self.nuage_object.user_name))
     except Exception as e:
         self.logger.error('VM %s can not be created because of error %s' % (self.vm_name, str(e)))
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    mode = args.mode
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    nuage_vm_enterprise = args.nuage_vm_enterprise
    nuage_vm_domain = None
    if args.nuage_vm_domain:
        nuage_vm_domain = args.nuage_vm_domain
    nuage_vm_zone = None
    if args.nuage_vm_zone:
        nuage_vm_zone = args.nuage_vm_zone
    nuage_vm_subnet = args.nuage_vm_subnet
    nuage_vm_user = None
    if args.nuage_vm_user:
        nuage_vm_user = args.nuage_vm_user
    vcenter_host = args.vcenter_host
    vcenter_port = args.vcenter_port
    vcenter_password = None
    if args.vcenter_password:
        vcenter_password = args.vcenter_password
    vcenter_username = args.vcenter_username
    vcenter_portgroup = args.vcenter_portgroup
    vcenter_vm = args.vcenter_vm

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file,
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Disabling SSL verification if set
    ssl_context = None
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()
        import ssl
        if hasattr(ssl, 'SSLContext'):
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            ssl_context.verify_mode = ssl.CERT_NONE

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (nuage_host, nuage_username))

    # Getting user password for vCenter connection
    if vcenter_password is None:
        logger.debug(
            'No command line vCenter password received, requesting vCenter password from user'
        )
        vcenter_password = getpass.getpass(
            prompt='Enter password for vCenter host %s for user %s: ' %
            (vcenter_host, vcenter_username))

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' %
                    (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username,
                               password=nuage_password,
                               enterprise=nuage_enterprise,
                               api_url="https://%s:%s" %
                               (nuage_host, nuage_port))
        nc.start()

        if not nc or not nc.is_current_session():
            logger.error(
                'Could not connect to Nuage host %s with user %s, enterprise %s and specified password'
                % (nuage_host, nuage_username, nuage_enterprise))
            return 1

        # Connecting to vCenter
        try:
            logger.info('Connecting to vCenter server %s:%s with username %s' %
                        (vcenter_host, vcenter_port, vcenter_username))
            if ssl_context:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port),
                                  sslContext=ssl_context)
            else:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port))
        except IOError, e:
            pass

        if not vc:
            logger.error(
                'Could not connect to vCenter host %s with user %s and specified password'
                % (vcenter_host, vcenter_username))
            return 1

        logger.info('Connected to both Nuage & vCenter servers')

        logger.debug('Registering vCenter disconnect at exit')
        atexit.register(Disconnect, vc)

        # Finding the Virtual Machine
        logger.debug('Searching for Virtual Machine: %s' % vcenter_vm)
        vc_vm = get_vcenter_object(logger, vc, [vim.VirtualMachine],
                                   vcenter_vm)
        if vc_vm is None:
            logger.critical('VM %s not found, ending run' % vcenter_vm)
            return 1

        # Finding the Portgroup
        logger.debug('Searching for Distributed Portgroup %s' %
                     vcenter_portgroup)
        vc_dvs_pg = get_vcenter_object(logger, vc,
                                       [vim.dvs.DistributedVirtualPortgroup],
                                       vcenter_portgroup)
        if vc_dvs_pg is None:
            logger.critical('Unknown distributed portgroup %s, exiting' %
                            vcenter_portgroup)
            return 1

        # Finding enterprise
        logger.debug('Searching for enterprise %s' % nuage_vm_enterprise)
        nc_enterprise = get_nuage_object(logger, nc.user, 'ENTERPRISE',
                                         'name == "%s"' % nuage_vm_enterprise,
                                         True)
        if nc_enterprise is None:
            logger.critical('Unknown enterprise %s, exiting' %
                            nuage_vm_enterprise)
            return 1

        # Finding subnet
        logger.debug(
            'Searching for the subnet, first by looking at the subnet itself.')
        nc_subnet = None
        nc_subnets = get_nuage_object(logger, nc.user, 'SUBNET',
                                      'name == "%s"' % nuage_vm_subnet, False)

        if len(nc_subnets) == 1:
            logger.debug('Found the L3 subnet %s in Nuage' % nuage_vm_subnet)
            nc_subnet = nc_subnets[0]
        elif len(nc_subnets) == 0:
            logger.debug(
                'Found no L3 subnet with name %s, checking L2 domains' %
                nuage_vm_subnet)
            nc_subnet = get_nuage_object(logger, nc_enterprise, 'L2DOMAIN',
                                         'name == "%s"' % nuage_vm_subnet,
                                         True)
        elif len(
                nc_subnets
        ) > 1 and nuage_vm_domain is not None and nuage_vm_zone is not None:
            logger.debug(
                'Found more than one L3 subnet with name %s, using Domain %s and Zone %s to find the right subnet'
                % (nuage_vm_subnet, nuage_vm_domain, nuage_vm_zone))
            nc_domain = get_nuage_object(logger, nc_enterprise, 'DOMAIN',
                                         'name == "%s"' % nuage_vm_domain,
                                         True)
            if nc_domain is None:
                logger.critical(
                    'Domain %s does not exist in Enterprise %s, exiting' %
                    (nuage_vm_domain, nuage_vm_zone))
                return 1
            nc_zone = get_nuage_object(logger, nc_domain, 'ZONE',
                                       'name == "%s"' % nuage_vm_zone, True)
            if nc_zone is None:
                logger.critical(
                    'Zone %s does not exist in Domain %s in Enterprise %s, exiting'
                    % (nuage_vm_zone, nuage_vm_domain, nuage_vm_enterprise))
                return 1
            nc_subnet = get_nuage_object(logger, nc_zone, 'SUBNET',
                                         'name == "%s"' % nuage_vm_subnet,
                                         False)

        if nc_subnet is None:
            logger.critical(
                'Subnet with name %s does not exist as an L3 subnet or an L2 domain, exiting'
            )
            return 1

        # Getting VM UUID
        logger.debug('Getting VM UUID, MAC & IP')
        vc_vm_uuid = vc_vm.config.uuid
        logger.debug('Found UUID %s for VM %s' % (vc_vm_uuid, vcenter_vm))
        vc_vm_net_info = vc_vm.guest.net
        vc_vm_mac = None
        vc_vm_ip = None

        for cur_net in vc_vm_net_info:
            if cur_net.macAddress:
                logger.debug('Mac address %s found for VM %s' %
                             (cur_net.macAddress, vcenter_vm))
                vc_vm_mac = cur_net.macAddress
            if vc_vm_mac and cur_net.ipConfig:
                if cur_net.ipConfig.ipAddress:
                    for cur_ip in cur_net.ipConfig.ipAddress:
                        logger.debug('Checking ip address %s for VM %s' %
                                     (cur_ip.ipAddress, vcenter_vm))
                        if re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
                                    cur_ip.ipAddress
                                    ) and cur_ip.ipAddress != '127.0.0.1':
                            vc_vm_ip = cur_ip.ipAddress
                            break
            if vc_vm_mac and vc_vm_ip:
                logger.debug('Found MAC %s and IP %s for VM %s' %
                             (vc_vm_mac, vc_vm_ip, vcenter_vm))
                break

        # Check if IP is in subnet
        logger.debug('Verifying that IP %s of VM %s is part of subnet %s' %
                     (vc_vm_ip, vcenter_vm, nuage_vm_subnet))
        if not ipaddress.ip_address(unicode(
                vc_vm_ip, 'utf-8')) in ipaddress.ip_network(
                    '%s/%s' % (nc_subnet.address, nc_subnet.netmask)):
            logger.critical('IP %s is not part of subnet %s with netmask %s' %
                            (vc_vm_ip, nc_subnet.address, nc_subnet.netmask))
            return 1

        logger.info('Found UUID %s, MAC %s and IP %s for VM %s' %
                    (vc_vm_uuid, vc_vm_mac, vc_vm_ip, vcenter_vm))

        # if metadata mode, create metadata on the VM
        if mode.lower() == 'metadata':
            logger.debug('Setting the metadata on VM %s' % vcenter_vm)
            vm_option_values = []
            # Network type
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.nic0.networktype',
                                       value='ipv4'))
            # User
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.user', value=nuage_vm_user))
            # IP
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.nic0.ip', value=vc_vm_ip))
            if type(nc_subnet) is vsdk.NUSubnet:
                nc_zone = vsdk.NUZone(id=nc_subnet.parent_id)
                nc_zone.fetch()
                nc_domain = vsdk.NUDomain(id=nc_zone.parent_id)
                nc_domain.fetch()
                nc_enterprise = vsdk.NUEnterprise(id=nc_domain.parent_id)
                nc_enterprise.fetch()
                # Enterprise
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.enterprise',
                                           value=nc_enterprise.name))
                # Domain
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.domain',
                                           value=nc_domain.name))
                # Zone
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.zone',
                                           value=nc_zone.name))
                # Subnet
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.network',
                                           value=nc_subnet.name))
            else:
                nc_enterprise = vsdk.NUEnterprise(id=nc_subnet.parent_id)
                nc_enterprise.fetch()
                # Enterprise
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.enterprise',
                                           value=nc_enterprise.name))
                # L2Domain
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.l2domain',
                                           value=nc_subnet.name))

            logger.debug('Creating of config spec for VM')
            config_spec = vim.vm.ConfigSpec(extraConfig=vm_option_values)
            logger.info(
                'Applying advanced parameters. This might take a couple of seconds'
            )
            config_task = vc_vm.ReconfigVM_Task(spec=config_spec)
            logger.debug('Waiting for the advanced paramerter to be applied')
            run_loop = True
            while run_loop:
                info = config_task.info
                if info.state == vim.TaskInfo.State.success:
                    logger.debug('Advanced parameters applied')
                    run_loop = False
                    break
                elif info.state == vim.TaskInfo.State.error:
                    if info.error.fault:
                        logger.info(
                            'Applying advanced parameters has quit with error: %s'
                            % info.error.fault.faultMessage)
                    else:
                        logger.info(
                            'Applying advanced parameters has quit with cancelation'
                        )
                    run_loop = False
                    break
                sleep(1)
        # Else if mode split-activation, create vPort and VM
        elif mode.lower() == 'split-activation':
            # Creating vPort
            logger.debug('Creating vPort for VM %s' % vcenter_vm)
            nc_vport = vsdk.NUVPort(
                name=vcenter_vm,
                address_spoofing='INHERITED',
                type='VM',
                description='Automatically created, do not edit.')
            nc_subnet.create_child(nc_vport)
            # Creating VM
            logger.debug('Creating a Nuage VM for VM %s' % vcenter_vm)
            nc_vm = vsdk.NUVM(name=vcenter_vm,
                              uuid=vc_vm_uuid,
                              interfaces=[{
                                  'name': vcenter_vm,
                                  'VPortID': nc_vport.id,
                                  'MAC': vc_vm_mac,
                                  'IPAddress': vc_vm_ip
                              }])
            nc.user.create_child(nc_vm)

        # Fetching nic from the VM
        logger.debug('Searching for NIC on VM %s' % vcenter_vm)
        vc_vm_nic = None
        for device in vc_vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualEthernetCard):
                logger.debug('Found NIC for VM %s' % vcenter_vm)
                vc_vm_nic = device
                break

        if vc_vm_nic is None:
            logger.critical('Could not find NIC for VM %s, exiting' %
                            vcenter_vm)
            return 1

        # Switching VM nic
        logger.debug('Creating spec to reconfigure the NIC of VM %s' %
                     vcenter_vm)
        vc_nicspec = vim.vm.device.VirtualDeviceSpec()
        vc_nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        vc_nicspec.device = vc_vm_nic
        vc_nicspec.device.wakeOnLanEnabled = True
        vc_nicspec.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo(
        )
        vc_nicspec.device.backing.port = vim.dvs.PortConnection()
        vc_nicspec.device.backing.port.portgroupKey = vc_dvs_pg.key
        vc_nicspec.device.backing.port.switchUuid = vc_dvs_pg.config.distributedVirtualSwitch.uuid
        vc_nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
        )
        vc_nicspec.device.connectable.startConnected = True
        vc_nicspec.device.connectable.connected = True
        vc_nicspec.device.connectable.allowGuestControl = True
        vc_vm_nic_reconfig = vim.vm.ConfigSpec(deviceChange=[vc_nicspec])

        logger.info(
            'Applying NIC changes. This might take a couple of seconds')
        config_task = vc_vm.ReconfigVM_Task(spec=vc_vm_nic_reconfig)
        logger.debug('Waiting for the nic change to be applied')
        run_loop = True
        while run_loop:
            info = config_task.info
            if info.state == vim.TaskInfo.State.success:
                logger.debug('Nic change applied')
                run_loop = False
                break
            elif info.state == vim.TaskInfo.State.error:
                if info.error.fault:
                    logger.info(
                        'Applying nic changes has quit with error: %s' %
                        info.error.fault.faultMessage)
                else:
                    logger.info(
                        'Applying nic changes has quit with cancelation')
                run_loop = False
                break
            sleep(1)

        logger.info(
            'Succesfully attached VM %s to Nuage subnet %s, in mode %s' %
            (vcenter_vm, nuage_vm_subnet, mode))
Exemplo n.º 4
0
def main():
    """
    Manage the activation of a vSphere VM
    """
    # Handling arguments
    args = get_args()

    if args.config_file:
        cfg = parse_config(args.config_file)
    elif os.path.isfile('{0:s}/.nuage/config.ini'.format(os.path.expanduser('~'))):
        cfg = parse_config('{0:s}/.nuage/config.ini'.format(os.path.expanduser('~')))
    else:
        print 'Missing config file'
        return 1

    mode = args.mode

    nuage_vm_enterprise = None
    if args.nuage_vm_enterprise:
        nuage_vm_enterprise = args.nuage_vm_enterprise
    nuage_vm_domain = None
    if args.nuage_vm_domain:
        nuage_vm_domain = args.nuage_vm_domain
    nuage_vm_zone = None
    if args.nuage_vm_zone:
        nuage_vm_zone = args.nuage_vm_zone
    nuage_vm_subnet = None
    if args.nuage_vm_subnet:
        nuage_vm_subnet = args.nuage_vm_subnet
    nuage_vm_ip = None
    if args.nuage_vm_ip:
        nuage_vm_ip = args.nuage_vm_ip
    nuage_vm_user = None
    if args.nuage_vm_user:
        nuage_vm_user = args.nuage_vm_user
    nuage_vm_policy_group = None
    if args.nuage_vm_policy_group:
        nuage_vm_user = args.nuage_vm_policy_group
    nuage_vm_redirection_target = None
    if args.nuage_vm_redirection_target:
        nuage_vm_user = args.nuage_vm_redirection_target
    vcenter_vm_name = None
    if args.vcenter_vm_name:
        vcenter_vm_name = args.vcenter_vm_name

    # Handling logging
    log_dir = cfg.get('LOG', 'directory')
    log_file = cfg.get('LOG', 'file')
    log_level = cfg.get('LOG', 'level')

    if not log_level:
        log_level = 'ERROR'

    log_path = None
    if log_dir and log_file and os.path.isdir(log_dir) and os.access(log_dir, os.W_OK):
        log_path = os.path.join(log_dir, log_file)

    logging.basicConfig(filename=log_path, format='%(asctime)s %(levelname)s - %(name)s - %(message)s', level=log_level)
    logging.info('Logging initiated')

    # Disabling SSL verification if set
    logging.debug('Disabling SSL certificate verification.')
    requests.packages.urllib3.disable_warnings()

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        try:
            logging.info('Connecting to Nuage server {0:s} with username {1:s} and enterprise {2:s}'.format(
                cfg.get('NUAGE', 'vsd_api_url'), cfg.get('NUAGE', 'vsd_api_user'),
                cfg.get('NUAGE', 'vsd_api_enterprise')))
            nc = vsdk.NUVSDSession(username=cfg.get('NUAGE', 'vsd_api_user'),
                                   password=cfg.get('NUAGE', 'vsd_api_password'),
                                   enterprise=cfg.get('NUAGE', 'vsd_api_enterprise'),
                                   api_url=cfg.get('NUAGE', 'vsd_api_url'))
            nc.start()
        except IOError:
            pass

        if not nc or not nc.is_current_session():
            logging.error(
                'Could not connect to Nuage host {0:s} with user {1:s}, enterprise {2:s} and specified password'.format(
                    cfg.get('NUAGE', 'vsd_api_url'), cfg.get('NUAGE', 'vsd_api_user'),
                    cfg.get('NUAGE', 'vsd_api_enterprise')))
            return 1

        # Connecting to vCenter
        try:
            logging.info(
                'Connecting to vCenter server {0:s} with username {1:s}'.format(cfg.get('VSPHERE', 'vsphere_api_host'),
                                                                                cfg.get('VSPHERE', 'vsphere_api_user')))
            vc = SmartConnect(host=cfg.get('VSPHERE', 'vsphere_api_host'), user=cfg.get('VSPHERE', 'vsphere_api_user'),
                              pwd=cfg.get('VSPHERE', 'vsphere_api_password'),
                              port=int(cfg.get('VSPHERE', 'vsphere_api_port')))
        except IOError:
            pass

        if not vc:
            logging.error('Could not connect to vCenter host {0:s} with user {1:s} and specified password'.format(
                cfg.get('VSPHERE', 'vsphere_api_host'), cfg.get('VSPHERE', 'vsphere_api_user')))
            return 1

        logging.info('Connected to both Nuage & vCenter servers')

        logging.debug('Registering vCenter disconnect at exit')
        atexit.register(Disconnect, vc)

        vcenter_vm = None
        vm_enterprise = None
        vm_user = None
        vm_domain = None
        vm_is_l2domain = False
        vm_zone = None
        vm_subnet = None
        vm_ip = None
        vm_policy_group = None
        vm_redirection_target = None
        # Verifying the vCenter VM existence or selecting it
        if vcenter_vm_name:
            vcenter_vm = find_vm(vc, vcenter_vm_name)
            if vcenter_vm is None:
                logging.critical('Unable to find specified VM with name {0:s}'.format(vcenter_vm_name))
                return 1
        else:
            logging.debug('Offering a choice of which VM to activate')
            content = vc.content
            obj_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
            vm_list = obj_view.view
            clear()
            print('Please select your VM:')
            index = 0
            for cur_vm in vm_list:
                print('%s. %s' % (index + 1, cur_vm.name))
                index += 1
            while vcenter_vm is None:
                choice = raw_input('Please enter the number of the VM [1-%s]: ' % len(vm_list))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(vm_list):
                    vcenter_vm = vm_list[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Enterprise existence or selecting it
        if nuage_vm_enterprise:
            logging.debug('Finding Nuage enterprise %s' % nuage_vm_enterprise)
            vm_enterprise = nc.user.enterprises.get_first(filter="name == '%s'" % nuage_vm_enterprise)
            if vm_enterprise is None:
                logging.error('Unable to find Nuage enterprise %s' % nuage_vm_enterprise)
                return 1
            logging.info('Nuage enterprise %s found' % nuage_vm_enterprise)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print(80 * '-')
            print('Please select your enterprise:')
            index = 0
            all_ent = nc.user.enterprises.get()
            for cur_ent in all_ent:
                print('%s. %s' % (index + 1, cur_ent.name))
                index += 1
            while vm_enterprise is None:
                choice = raw_input('Please enter the number of the enterprise [1-%s]: ' % len(all_ent))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_ent):
                    vm_enterprise = all_ent[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage User existence or selecting it
        if nuage_vm_user:
            logging.debug('Finding Nuage user %s' % nuage_vm_user)
            vm_user = vm_enterprise.users.get_first(filter="userName == '%s'" % nuage_vm_user)
            if vm_user is None:
                logging.error('Unable to find Nuage user %s' % nuage_vm_user)
                return 1
            logging.info('Nuage user %s found' % nuage_vm_user)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print(80 * '-')
            print('Please select your user:'******'%s. %s' % (index + 1, cur_user.user_name))
                index += 1
            while vm_user is None:
                choice = raw_input('Please enter the number of the user [1-%s]: ' % len(all_users))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_users):
                    vm_user = all_users[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Domain existence or selecting it
        if nuage_vm_domain:
            logging.debug('Finding Nuage domain %s' % nuage_vm_domain)
            vm_domain = vm_enterprise.domains.get_first(filter="name == '%s'" % nuage_vm_domain)
            if vm_domain is None:
                logging.debug('Unable to find the domain {0:s} as an L3 domain'.format(nuage_vm_domain))
                vm_domain = vm_enterprise.l2_domains.get_first(filter="name == '%s'" % nuage_vm_domain)
                vm_is_l2domain = True
                if vm_domain is None:
                    logging.error('Unable to find Nuage domain {0:s}'.format(nuage_vm_domain))
                    return 1
            logging.info('Nuage domain %s found' % nuage_vm_domain)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            print(80 * '-')
            print('Please select your domain:')
            index = 0
            all_l3_dom = vm_enterprise.domains.get()
            all_l2_dom = vm_enterprise.l2_domains.get()
            all_dom = all_l2_dom + all_l3_dom
            for cur_dom in all_l2_dom:
                print('%s. L2 %s - %s/%s' % (index + 1, cur_dom.name, cur_dom.address, cur_dom.netmask))
                index += 1
            for cur_dom in all_l3_dom:
                print('%s. L3 - %s' % (index + 1, cur_dom.name))
                index += 1
            while vm_domain is None:
                choice = raw_input('Please enter the number of the domain [1-%s]: ' % len(all_dom))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_dom):
                    vm_domain = all_dom[choice - 1]
                    if type(vm_domain) is vsdk.NUL2Domain:
                        vm_is_l2domain = True
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Zone existence or selecting it
        if not vm_is_l2domain and nuage_vm_zone:
            logging.debug('Finding Nuage zone %s' % nuage_vm_zone)
            vm_zone = vm_domain.zones.get_first(filter="name == '%s'" % nuage_vm_zone)
            if vm_zone is None:
                logging.error('Unable to find Nuage zone %s' % nuage_vm_zone)
                return 1
            logging.info('Nuage zone %s found' % nuage_vm_zone)
        elif not vm_is_l2domain:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            print('Domain: %s' % vm_domain.name)
            print(80 * '-')
            print('Please select your zone:')
            index = 0
            all_zone = vm_domain.zones.get()
            for cur_zone in all_zone:
                print('%s. %s' % (index + 1, cur_zone.name))
                index += 1
            while vm_zone is None:
                choice = raw_input('Please enter the number of the zone [1-%s]: ' % len(all_zone))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_zone):
                    vm_zone = all_zone[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Subnet existence or selecting it
        if not vm_is_l2domain and nuage_vm_subnet:
            logging.debug('Finding Nuage subnet %s' % nuage_vm_subnet)
            vm_subnet = vm_zone.subnets.get_first(filter="name == '%s'" % nuage_vm_subnet)
            if vm_subnet is None:
                logging.error('Unable to find Nuage subnet %s' % nuage_vm_subnet)
                return 1
            logging.info('Nuage subnet %s found' % nuage_vm_subnet)
        elif not vm_is_l2domain:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            print('Domain: %s' % vm_domain.name)
            print('Zone: %s' % vm_zone.name)
            print(80 * '-')
            print('Please select your subnet:')
            index = 0
            all_subnet = vm_zone.subnets.get()
            for cur_subnet in all_subnet:
                print('%s. %s - %s/%s' % (index + 1, cur_subnet.name, cur_subnet.address, cur_subnet.netmask))
                index += 1
            while vm_subnet is None:
                choice = raw_input('Please enter the number of the subnet [1-%s]: ' % len(all_subnet))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_subnet):
                    vm_subnet = all_subnet[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the IP or asking for it
        if nuage_vm_ip:
            logging.debug('Verifying if IP %s is inside Nuage subnet %s range' % (nuage_vm_ip, vm_subnet.name))
            if not ipaddress.ip_address(nuage_vm_ip) in ipaddress.ip_network('%s/%s' % (vm_subnet.address, vm_subnet.netmask)):
                logging.error('IP %s is not part of subnet %s with netmask %s' % (nuage_vm_ip, vm_subnet.address, vm_subnet.netmask))
                return 1
            vm_ip = nuage_vm_ip
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            if not vm_is_l2domain:
                print('Domain: %s' % vm_domain.name)
                print('Zone: %s' % vm_zone.name)
                print('Subnet: %s - %s/%s' % (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
            else:
                print('Domain: %s - %s/%s' % (vm_domain.name, vm_domain.address, vm_domain.netmask))
            print(80 * '-')
            print('If you want a static IP, please enter it. Or press enter for a DHCP assigned IP.')
            while vm_ip is None:
                choice = raw_input('Please enter the IP or press enter for a DHCP assigned IP: ')
                if not choice or ipaddress.ip_address(choice) in ipaddress.ip_network(
                                '%s/%s' % (vm_subnet.address, vm_subnet.netmask)):
                    vm_ip = choice
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage policy group existence or selecting it
        if nuage_vm_policy_group:
            logging.debug('Finding Nuage policy group %s' % nuage_vm_policy_group)
            vm_policy_group = vm_domain.policy_groups.get_first(filter="name == '%s'" % nuage_vm_policy_group)
            if vm_policy_group is None:
                logging.error('Unable to find Nuage policy group {0:s}'.format(nuage_vm_policy_group))
                return 1
            logging.info('Nuage policy group %s found' % nuage_vm_policy_group)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            if not vm_is_l2domain:
                print('Domain: %s' % vm_domain.name)
                print('Zone: %s' % vm_zone.name)
                print('Subnet: %s - %s/%s' % (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
            else:
                print('Domain: %s - %s/%s' % (vm_domain.name, vm_domain.address, vm_domain.netmask))
            if vm_ip:
                print('IP: {0:s}'.format(vm_ip))
            print(80 * '-')
            print('Please select your policy group:')
            index = 0
            all_pg = vm_domain.policy_groups.get()
            print('0. None')
            for cur_pg in all_pg:
                print('%s. %s' % (index + 1, cur_pg.name))
                index += 1
            while vm_policy_group is None:
                choice = raw_input('Please enter the number of the policy group [0-%s]: ' % len(all_pg))
                choice = int(choice)
                if choice == 0:
                    vm_policy_group = None
                    break
                elif choice > 0 and choice - 1 < len(all_pg):
                    vm_policy_group = all_pg[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage redirection target existence or selecting it
        if nuage_vm_redirection_target:
            logging.debug('Finding Nuage redirection target %s' % nuage_vm_redirection_target)
            vm_redirection_target = vm_domain.redirection_targets.get_first(
                filter="name == '%s'" % nuage_vm_redirection_target)
            if vm_redirection_target is None:
                logging.error('Unable to find Nuage redirection target {0:s}'.format(nuage_vm_redirection_target))
                return 1
            logging.info('Nuage redirection target %s found' % nuage_vm_redirection_target)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            if not vm_is_l2domain:
                print('Domain: %s' % vm_domain.name)
                print('Zone: %s' % vm_zone.name)
                print('Subnet: %s - %s/%s' % (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
            else:
                print('Domain: %s - %s/%s' % (vm_domain.name, vm_domain.address, vm_domain.netmask))
            if vm_ip:
                print('IP: {0:s}'.format(vm_ip))
            if vm_policy_group:
                print('Policy group: {0:s}'.format(vm_policy_group.name))
            print(80 * '-')
            print('Please select your redirection target:')
            index = 0
            all_rt = vm_domain.redirection_targets.get()
            print('0. None')
            for cur_rt in all_rt:
                print('%s. %s' % (index + 1, cur_rt.name))
                index += 1
            while vm_redirection_target is None:
                choice = raw_input('Please enter the number of the redirection target [0-%s]: ' % len(all_rt))
                choice = int(choice)
                if choice == 0:
                    vm_redirection_target = None
                    break
                elif choice > 0 and choice - 1 < len(all_rt):
                    vm_redirection_target = all_rt[choice - 1]
                    break
                print('Invalid choice, please try again')

        logging.info('Using following Nuage values:')
        logging.info('Enterprise: %s' % vm_enterprise.name)
        logging.info('User: %s' % vm_user.user_name)
        if not vm_is_l2domain:
            logging.info('Domain: %s' % vm_domain.name)
            logging.info('Zone: %s' % vm_zone.name)
            logging.info('Subnet: %s - %s/%s' % (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
        else:
            logging.info('Domain: %s - %s/%s' % (vm_domain.name, vm_domain.address, vm_domain.netmask))
        if vm_ip:
            logging.info('Static IP: %s' % vm_ip)
        if vm_policy_group:
            logging.info('Policy group: {0:s}'.format(vm_policy_group.name))
        if vm_redirection_target:
            logging.info('Redirection target: {0:s}'.format(vm_redirection_target.name))

        clear()

        if mode == 'metadata':
            print('Setting Nuage Metadata on VM')
            # Setting Nuage metadata
            logging.info('Setting Nuage Metadata')
            vm_option_values = []
            # Enterprise
            vm_option_values.append(vim.option.OptionValue(key='nuage.enterprise', value=vm_enterprise.name))
            if vm_is_l2domain:
                # L2 Domain
                vm_option_values.append(vim.option.OptionValue(key='nuage.nic0.l2domain', value=vm_domain.name))
            else:
                # Domain
                vm_option_values.append(vim.option.OptionValue(key='nuage.nic0.domain', value=vm_domain.name))
                # Zone
                vm_option_values.append(vim.option.OptionValue(key='nuage.nic0.zone', value=vm_zone.name))
                # Subnet
                vm_option_values.append(vim.option.OptionValue(key='nuage.nic0.network', value=vm_subnet.name))
            # Network type
            vm_option_values.append(vim.option.OptionValue(key='nuage.nic0.networktype', value='ipv4'))
            # User
            vm_option_values.append(vim.option.OptionValue(key='nuage.user', value=vm_user.user_name))
            # IP
            if vm_ip:
                vm_option_values.append(vim.option.OptionValue(key='nuage.nic0.ip', value=vm_ip))
            # Policy group
            if vm_policy_group:
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.policy-group', value=vm_policy_group.name))
            # Redirection target
            if vm_redirection_target:
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.redirection-target', value=vm_redirection_target.name))

            logging.debug('Creating of config spec for VM')
            config_spec = vim.vm.ConfigSpec(extraConfig=vm_option_values)
            logging.info('Applying advanced parameters. This might take a couple of seconds')
            config_task = vcenter_vm.ReconfigVM_Task(spec=config_spec)
            logging.debug('Waiting for the advanced paramerter to be applied')
            while True:
                info = config_task.info
                if info.state == vim.TaskInfo.State.success:
                    logging.debug('Advanced parameters applied')
                    break
                elif info.state == vim.TaskInfo.State.error:
                    if info.error.fault:
                        logging.info(
                            'Applying advanced parameters has quit with error: %s' % info.error.fault.faultMessage)
                    else:
                        logging.info('Applying advanced parameters has quit with cancelation')
                    break
                sleep(5)

        elif mode == 'split-activation':
            print('Creating vPort and VM in VSD for split activation')
            logging.debug('Starting split activation')

            # Getting VM UUID
            logging.debug('Getting VM UUID, MAC & IP')
            vcenter_vm_uuid = vcenter_vm.config.uuid
            logging.debug('Found UUID %s for VM %s' % (vcenter_vm_uuid, vcenter_vm.name))
            vcenter_vm_mac = None
            vcenter_vm_hw = vcenter_vm.config.hardware
            for dev in vcenter_vm_hw.device:
                if isinstance(dev, vim.vm.device.VirtualEthernetCard):
                    if dev.macAddress:
                        logging.debug('Found MAC {0:s} for VM {1:s}'.format(dev.macAddress, vcenter_vm.name))
                        vcenter_vm_mac = dev.macAddress
                        break

            if vcenter_vm_mac is None:
                logging.critical('Unable to find a valid mac address for VM')
                return 1

            # Creating vPort
            logging.debug('Creating vPort for VM %s' % vcenter_vm.name)
            nc_vport = vsdk.NUVPort(name='{0:s}-vport'.format(vcenter_vm.name), address_spoofing='INHERITED', type='VM',
                                    description='Automatically created, do not edit.')
            if vm_is_l2domain:
                vm_domain.create_child(nc_vport)
            else:
                vm_subnet.create_child(nc_vport)

            # Creating VM
            logging.debug('Creating a Nuage VM for VM %s' % vcenter_vm)
            nc_vm = vsdk.NUVM(name=vcenter_vm.name, uuid=vcenter_vm_uuid, interfaces=[{
                'name': vcenter_vm_mac,
                'VPortID': nc_vport.id,
                'MAC': vcenter_vm_mac
            }])
            nc.user.create_child(nc_vm)

        else:
            logging.critical('Invalid mode')
            return 1

    except vmodl.MethodFault, e:
        logging.critical('Caught vmodl fault: {0:s}'.format(e.msg))
        return 1
Exemplo n.º 5
0
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    vmid = args.vmid

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file,
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' %
                    (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username,
                               password=nuage_password,
                               enterprise=nuage_enterprise,
                               api_url="https://%s:%s" %
                               (nuage_host, nuage_port))
        nc.start()

    except Exception as e:
        logger.error(
            'Could not connect to Nuage host %s with user %s and specified password'
            % (nuage_host, nuage_username))
        logger.critical('Caught exception: %s' % str(e))
        return 1

    # Creating VM
    logger.info('Deleting VM %s' % vmid)
    vm = vsdk.NUVM(id=vmid)
    try:
        vm.fetch()
        logger.debug('Getting vPorts')
        vport_ids = []
        for interface in vm.vm_interfaces.get():
            vport_ids.append(interface.vport_id)
        logger.debug('Trying to delete VM %s.' % vmid)
        vm.delete()
        logger.debug('Trying to delete vports.')
        for vport in vport_ids:
            vport = vsdk.NUVPort(id=vport)
            vport.delete()
    except Exception as e:
        logger.critical('VM %s can not be deleted because of error %s' %
                        (vmid, str(e)))
        return 1

    logger.info('Deleted VM %s' % vmid)
    return 0
Exemplo n.º 6
0
def main():
    # Handling arguments
    args = get_args()
    debug = args.debug
    verbose = args.verbose
    log_file = args.logfile
    nuage_organization = args.nuage_organization
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nuage_myEnterprise = args.nuage_myEnterprise
    nuage_myDomain = args.nuage_myDomain
    nuage_myZone = []
    if args.nuage_myZone:
        nuage_myZone = args.nuage_myZone
    nuage_mySubnetName = []
    if args.nuage_mySubnetName:
        nuage_mySubnetName = args.nuage_mySubnetName
    nuage_myVPortName = args.nuage_myVPortName
    nuage_myVMname = args.nuage_myVMname
    nuage_myVMuuid = args.nuage_myVMuuid
    nuage_myVMIfIp = []
    if args.nuage_myVMIfIp:
        nuage_myVMIfIp = args.nuage_myVMIfIp
    nuage_myVMIfMac = args.nuage_myVMIfMac
    MyCmsName = 'CMS-scripts'

    # Logging settings
    logger = setup_logging(debug, verbose, log_file)

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (nuage_host, nuage_username))

    # Connection to VSD
    nc = start_nuage_connection(nuage_host, nuage_port, nuage_username,
                                nuage_password, nuage_organization, logger)

    # lookup Enterprise
    myFilter = "name == \"" + nuage_myEnterprise + "\""
    myEnterprise = nc.enterprises.get_first(filter=myFilter)
    print('Entreprise : %s' % myEnterprise.name)

    # Sanity checks
    if len(nuage_myDomain) > 0 and len(nuage_myDomain) != len(nuage_myVMIfMac):
        print(
            '!!!>error: incorrect arguments. Each interface must be in a different subnet, zone, domain.<!!!'
        )
        logger.critical(
            'Specific to AES project. Each interface must be in a different subnet, zone, domain.'
        )
        return 1
    if len(nuage_myVPortName) > 0 and len(nuage_myVPortName) != len(
            nuage_myVMIfMac):
        print(
            '!!!>error: incorrect arguments. Each interface must be in a different subnet, zone, domain.<!!!'
        )
        logger.critical(
            'Specific to AES project. Each interface must be in a different subnet, zone, domain.'
        )
        return 1

    myFilter = "name == \"" + nuage_myDomain[0] + "\""
    myDomain = myEnterprise.domains.get_first(filter=myFilter)
    if myDomain:
        print('|>---------- L3 DOMAIN ----------<')
        domain_type = "L3_DOMAIN"
        if len(nuage_myZone) > 0 and len(nuage_myZone) != len(nuage_myVMIfMac):
            print(
                '!!!>error: incorrect arguments. Each interface must be in a different subnet, zone, domain.<!!!'
            )
            logger.critical(
                'Specific to AES project. Each interface must be in a different subnet, zone, domain.'
            )
            return 1
        if len(nuage_mySubnetName) > 0 and len(nuage_mySubnetName) != len(
                nuage_myVMIfMac):
            print(
                '!!!>error: incorrect arguments. Each interface must be in a different subnet, zone, domain.<!!!'
            )
            logger.critical(
                'Specific to AES project. Each interface must be in a different subnet, zone, domain.'
            )
            return 1
        if len(nuage_myVMIfIp) > 0 and len(nuage_myVMIfIp) != len(
                nuage_myVMIfMac):
            print(
                '!!!>error: incorrect arguments. Each interface must be in a different subnet, zone, domain.<!!!'
            )
            logger.critical(
                'Specific to AES project. Each interface must be in a different subnet, zone, domain.'
            )
            return 1
    else:
        myDomain = myEnterprise.l2_domains.get_first(filter=myFilter)
        print('|>---------- L2 DOMAIN ----------<')
        domain_type = "L2_DOMAIN"

    # Handling each mac/subnet combination and creating the necessary VM Interfaces
    vports = []
    vm_interfaces = []
    for mac in nuage_myVMIfMac:
        index = nuage_myVMIfMac.index(mac)
        domain_name = nuage_myDomain[index]
        zone_name = nuage_myZone[index]
        subnet_name = nuage_mySubnetName[index]
        vport_name = nuage_myVPortName[index]

        # lookup Domain
        myFilter = "name == \"" + domain_name + "\""
        if domain_type == "L3_DOMAIN":
            myDomain = myEnterprise.domains.get_first(filter=myFilter)
        else:
            myDomain = myEnterprise.l2_domains.get_first(filter=myFilter)
        print('+-- Domain : %s' % (myDomain.name))

        # lookup Zone
        if domain_type == "L3_DOMAIN":
            myFilter = "name == \"" + zone_name + "\""
            myZone = myDomain.zones.get_first(filter=myFilter)
            print('|   +-- Zone : %s' % (myZone.name))

        # lookup Subnet
        if domain_type == "L3_DOMAIN":
            myFilter = "name == \"" + subnet_name + "\""
            mySubnet = myZone.subnets.get_first(filter=myFilter)
            print('|   |   +-- Subnet : %s - %s %s' %
                  (mySubnet.name, mySubnet.address, mySubnet.netmask))

        # Get vPort
        myFilter = "name == \"" + vport_name + "\""
        if domain_type == "L3_DOMAIN":
            myVPort = myZone.vports.get_first(filter=myFilter)
        else:
            # L2_DOMAIN
            cur_domain
            myVPort = cur_domain.vports.get_first(filter=myFilter)
        print('|   |   |  +-- vPort : %s' % (myVPort.name))
        vports.append(myVPort)

        # Creating VMInterface
        if domain_type == "L3_DOMAIN":
            vm_interface = vsdk.NUVMInterface(name='eth%s' % (index + 1),
                                              vport_id=myVPort.id,
                                              mac=mac,
                                              external_id=MyCmsName,
                                              ip_address=nuage_myVMIfIp[index])
        else:
            # L2_DOMAIN
            vm_interface = vsdk.NUVMInterface(name='eth%s' % (index + 1),
                                              vport_id=myVPort.id,
                                              mac=mac,
                                              external_id=MyCmsName)
        vm_interfaces.append(vm_interface)

    # Creating VM
    logger.info('Creating VM %s with UUID %s' %
                (nuage_myVMname, nuage_myVMuuid))
    vm = vsdk.NUVM(name=nuage_myVMname,
                   uuid=nuage_myVMuuid,
                   interfaces=vm_interfaces,
                   external_id=MyCmsName)
    try:
        logger.debug('Trying to save VM %s.' % nuage_myVMname)
        nc.create_child(vm)
        print('VM %s is created by user %s.' % (vm.name, vm.user_name))
    except Exception as e:
        logger.critical('VM %s can not be created because of error %s' %
                        (nuage_myVMname, str(e)))
        print('!!!> error: VM %s is NOT %s because of error %s<!!!' %
              (nuage_myVMname, str(e)))
Exemplo n.º 7
0
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    external = args.external
    ips = []
    if args.ips:
        ips = args.ips
    macs = args.macs
    name = args.name
    subnets = args.subnets
    uuid = args.uuid

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file, format='%(asctime)s %(levelname)s %(message)s', level=log_level)
    logger = logging.getLogger(__name__)

    # Sanity checks
    if len(macs) > 0 and len(macs) != len(subnets):
        logger.critical('The amount of macs is not equal to the amount of subnets, which is an invalid configuration.')
        return 1

    if len(ips) > 0 and len(macs) != len(ips):
        logger.critical('Some IPs are specified, but not the same amount as macs and subnets, which is an invalid configuration.')
        return 1

    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug('No command line Nuage password received, requesting Nuage password from user')
        nuage_password = getpass.getpass(prompt='Enter password for Nuage host %s for user %s: ' % (nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' % (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username, password=nuage_password, enterprise=nuage_enterprise, api_url="https://%s:%s" % (nuage_host, nuage_port))
        nc.start()

    except Exception as e:
        logger.error('Could not connect to Nuage host %s with user %s and specified password' % (nuage_host, nuage_username))
        logger.critical('Caught exception: %s' % str(e))
        return 1

    # Handling each mac/subnet combination and creating the necessary vPorts and VM Interfaces
    vports = []
    vm_interfaces = []
    for mac in macs:
        index = macs.index(mac)
        subnet_id = subnets[index]
        logger.info('Handling mac address %s connection to subnet or L2 domain %s' % (mac, subnet_id))

        logger.debug('Trying to fetch subnet for ID %s' % subnet_id)
        try:
            subnet = vsdk.NUSubnet(id=subnet_id)
            subnet.fetch()
        except:
            logger.debug('Subnet with ID %s does not exist, looking for a L2 domain' % subnet_id)
            try:
                subnet = vsdk.NUL2Domain(id=subnet_id)
                subnet.fetch()
            except:
                logger.error('Subnet with ID %s can not be found as an subnet in an L3 domain or as an L2 domain, skipping mac %s and subnet %s and continuing to the next pair' % (subnet_id, mac, subnet_id))
                continue

        # Creating vPort in subnet
        logger.debug('Creating vPort %s-vPort-%s in subnet %s (%s)' % (name, index, subnet.name, subnet_id))
        vport = vsdk.NUVPort(name='%s-vPort-%s' % (name, index), address_spoofing='INHERITED', type='VM', description='Automatically created, do not edit.')
        if external:
            vport.external_id = '%s-vPort-%s' % (name, index)
        subnet.create_child(vport)
        vports.append(vport)

        # Creating VMInterface
        logger.debug('Creating VMInterface object %s-vm-interface-%s for mac %s with vPort ID %s' % (name, index, mac, vport.id))
        vm_interface = vsdk.NUVMInterface(name='%s-vm-interface-%s' % (name, index), vport_id=vport.id, mac=mac)
        if external:
            vm_interface.external_id = '%s-vm-interface-%s' % (name, index)
        if len(ips) > 0:
            vm_interface.ip_address = ips[index]
        vm_interfaces.append(vm_interface)

    # Creating VM
    logger.info('Creating VM %s with UUID %s' % (name, uuid))
    vm = vsdk.NUVM(name=name, uuid=uuid, interfaces=vm_interfaces)
    if external:
        vm.external_id = uuid
    try:
        logger.debug('Trying to save VM %s.' % name)
        nc.user.create_child(vm)
    except Exception as e:
        logger.critical('VM %s can not be created because of error %s' % (name, str(e)))
        logger.debug('Cleaning up the vPorts')
        for vport in vports:
            logger.debug('Deleting vPort %s' % vport.name)
            vport.delete()
        return 1

    logger.info('Created all necessary entities in the appropriate subnets or L2 domains for VM %s' % name)
    return 0
Exemplo n.º 8
0
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    ips = []
    if args.ips:
        ips = args.ips
    macs = args.macs
    subnets = args.subnets
    uuid = args.uuid

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file,
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Sanity checks
    if len(macs) > 0 and len(macs) != len(subnets):
        logger.critical(
            'The amount of macs is not equal to the amount of subnets, which is an invalid configuration.'
        )
        return 1

    if len(ips) > 0 and len(macs) != len(ips):
        logger.critical(
            'Some IPs are specified, but not the same amount as macs and subnets, which is an invalid configuration.'
        )
        return 1

    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host {0:s} for user {1:s}: '.
            format(nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info(
            'Connecting to Nuage server {0:s}:{1:d} with username {2:s}'.
            format(nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username,
                               password=nuage_password,
                               enterprise=nuage_enterprise,
                               api_url="https://{0:s}:{1:d}".format(
                                   nuage_host, nuage_port))
        nc.start()

    except Exception as e:
        logger.error(
            'Could not connect to Nuage host {0:s} with user {1:s} and specified password'
            .format(nuage_host, nuage_username))
        logger.critical('Caught exception: {0:s}'.format(str(e)))
        return 1

    logger.debug('Trying to fetch VM with ID {0:s}'.format(uuid))
    vm = vsdk.NUVM(id=uuid)
    vm.fetch()

    for mac in macs:
        index = macs.index(mac)
        subnet_id = subnets[index]
        subnet_type = None
        logger.info(
            'Handling mac address {0:s} connection to subnet or L2 domain {1:s}'
            .format(mac, subnet_id))

        logger.debug('Trying to fetch subnet for ID {0:s}'.format(subnet_id))
        try:
            subnet = vsdk.NUSubnet(id=subnet_id)
            subnet.fetch()
            subnet_type = 'SUBNET'
        except:
            logger.debug(
                'Subnet with ID {0:s} does not exist, looking for a L2 domain'.
                format(subnet_id))
            try:
                subnet = vsdk.NUL2Domain(id=subnet_id)
                subnet.fetch()
                subnet_type = 'L2DOMAIN'
            except:
                logger.error(
                    'Subnet with ID {0:s} can not be found as an subnet in an L3 domain or as an L2 domain, skipping mac {1:s} and subnet {2:s} and continuing to the next pair'
                    .format(subnet_id, mac, subnet_id))
                continue

        vm_interface = vsdk.NUVMInterface()
        if len(ips) > 0:
            vm_interface.ip_address = ips[index]
        vm_interface.mac = mac
        vm_interface.name = 'if-{0:s}'.format(mac).replace(':', '-')
        vm_interface.attached_network_id = subnet_id
        vm_interface.attached_network_type = subnet_type

        logger.debug('Creating interface {0:s} on VM {1:s}'.format(
            vm_interface.name, vm.name))
        try:
            vm.create_child(vm_interface)
        except Exception as e:
            logger.error(
                'Failed to create interface {0:s} on VM {1:s}: {2:s}'.format(
                    vm_interface.name, vm.name, str(e)))

    logger.info('Successfully added interfaces to VM {0:s}'.format(vm.name))
    return 0