Exemple #1
0
def create_new_vspk_session():
    session = vspk.NUVSDSession(
        username='******',
        password='******',
        enterprise='csp',
        api_url=get_vsd_api_url())
    session.start()
    return session
Exemple #2
0
def nuage_login(user='******',
                password='******',
                org='csp',
                vsdhost='vsd.mydomain.com:8443'):
    session = vsdk.NUVSDSession(username=user,
                                password=password,
                                enterprise=org,
                                api_url="https://" + vsdhost)
    try:
        logging.info('Establishing session to VSD %s as User %s', vsdhost,
                     user)
        session.start()
        logging.info('Logged to VSD successfully')
    except:
        logging.error('Failed to start a Session to VSD')
        exit(-1)
    return session.user
def inspect_topology(username, password, enterprise, api_url):
    session = vsdk.NUVSDSession(username=username,
                                password=password,
                                enterprise=enterprise,
                                api_url=api_url)
    session.start()
    user = session.user
    print("User:\n=====\nname: {0:s}, role: {1:s}".format(
        user.user_name, user.role))

    print_items("\nEnterprises:\n============",
                user.enterprises.get(),
                name=True)
    print_items("\nDomains:\n========",
                user.domains.get(),
                name=True,
                description=True)
    print_items("\nL2Domains:\n==========",
                user.l2_domains.get(),
                name=True,
                description=True)
Exemple #4
0
def main():
    """
    Manage the vCenter Integration Node configuration
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    folder_name = None
    if args.folder:
        folder_name = args.folder
    log_file = None
    if args.logfile:
        log_file = args.logfile
    name = args.name
    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
    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
    power_on = not args.nopoweron
    resource_pool_name = None
    if args.resource_pool:
        resource_pool_name = args.resource_pool
    nosslcheck = args.nosslcheck
    template = args.template
    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
    verbose = args.verbose

    # 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__)

    # 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
        try:
            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 IOError:
            pass

        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 nosslcheck:
                vc = SmartConnectNoSSL(host=vcenter_host,
                                       user=vcenter_username,
                                       pwd=vcenter_password,
                                       port=int(vcenter_port))
            else:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port))
        except IOError:
            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)

        # Verifying the Nuage Enterprise existence or selecting it
        if nuage_vm_enterprise:
            logger.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:
                logger.error('Unable to find Nuage enterprise %s' %
                             nuage_vm_enterprise)
                return 1
            logger.info('Nuage enterprise %s found' % nuage_vm_enterprise)
        else:
            clear(logger)
            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
            vm_enterprise = None
            while vm_enterprise is None:
                choice = eval(
                    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:
            logger.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:
                logger.error('Unable to find Nuage user %s' % nuage_vm_user)
                return 1
            logger.info('Nuage user %s found' % nuage_vm_user)
        else:
            clear(logger)
            print('Enterprise: %s' % vm_enterprise.name)
            print(80 * '-')
            print('Please select your user:'******'%s. %s' % (index + 1, cur_user.user_name))
                index += 1
            vm_user = None
            while vm_user is None:
                choice = eval(
                    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:
            logger.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:
                logger.error('Unable to find Nuage domain %s' %
                             nuage_vm_domain)
                return 1
            logger.info('Nuage domain %s found' % nuage_vm_domain)
        else:
            clear(logger)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            print(80 * '-')
            print('Please select your domain:')
            index = 0
            all_dom = vm_enterprise.domains.get()
            for cur_dom in all_dom:
                print('%s. %s' % (index + 1, cur_dom.name))
                index += 1
            vm_domain = None
            while vm_domain is None:
                choice = eval(
                    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]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Zone existence or selecting it
        if nuage_vm_zone:
            logger.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:
                logger.error('Unable to find Nuage zone %s' % nuage_vm_zone)
                return 1
            logger.info('Nuage zone %s found' % nuage_vm_zone)
        else:
            clear(logger)
            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
            vm_zone = None
            while vm_zone is None:
                choice = eval(
                    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 nuage_vm_subnet:
            logger.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:
                logger.error('Unable to find Nuage subnet %s' %
                             nuage_vm_subnet)
                return 1
            logger.info('Nuage subnet %s found' % nuage_vm_subnet)
        else:
            clear(logger)
            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
            vm_subnet = None
            while vm_subnet is None:
                choice = eval(
                    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:
            logger.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)):
                logger.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(logger)
            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('Subnet: %s - %s/%s' %
                  (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
            print(80 * '-')
            print(
                'If you want a static IP, please enter it. Or press enter for a DHCP assigned IP.'
            )
            vm_ip = None
            while vm_ip is None:
                choice = eval(
                    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')

        logger.info('Using following Nuage values:')
        logger.info('Enterprise: %s' % vm_enterprise.name)
        logger.info('User: %s' % vm_user.user_name)
        logger.info('Domain: %s' % vm_domain.name)
        logger.info('Zone: %s' % vm_zone.name)
        logger.info('Subnet: %s - %s/%s' %
                    (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
        if vm_ip:
            logger.info('Static IP: %s' % vm_ip)

        # Find the correct VM
        logger.debug('Finding template %s' % template)
        template_vm = find_vm(vc, logger, template)
        if template_vm is None:
            logger.error('Unable to find template %s' % template)
            return 1
        logger.info('Template %s found' % template)

        # Find the correct Resource Pool
        resource_pool = None
        if resource_pool_name is not None:
            logger.debug('Finding resource pool %s' % resource_pool_name)
            resource_pool = find_resource_pool(vc, logger, resource_pool_name)
            if resource_pool is None:
                logger.critical('Unable to find resource pool %s' %
                                resource_pool_name)
                return 1
            logger.info('Resource pool %s found' % resource_pool_name)

        # Find the correct folder
        folder = None
        if folder_name is not None:
            logger.debug('Finding folder %s' % folder_name)
            folder = find_folder(vc, logger, folder_name)
            if folder is None:
                logger.critical('Unable to find folder %s' % folder_name)
                return 1
            logger.info('Folder %s found' % folder_name)
        else:
            logger.info('Setting folder to template folder as default')
            folder = template_vm.parent

        # Creating necessary specs
        logger.debug('Creating relocate spec')
        if resource_pool is not None:
            logger.debug('Resource pool found, using')
            relocate_spec = vim.vm.RelocateSpec(pool=resource_pool)
        else:
            logger.debug('No resource pool found, continuing without it')
            relocate_spec = vim.vm.RelocateSpec()

        logger.debug('Creating clone spec')
        clone_spec = vim.vm.CloneSpec(powerOn=False,
                                      template=False,
                                      location=relocate_spec)

        run_loop = True
        vm = None
        logger.info('Trying to clone %s to new virtual machine' % template)

        if find_vm(vc, logger, name):
            logger.warning('Virtual machine already exists, not creating')
            run_loop = False
        else:
            logger.debug('Creating clone task')
            task = template_vm.Clone(name=name, folder=folder, spec=clone_spec)
            logger.info('Cloning task created')
            logger.info(
                'Checking task for completion. This might take a while')

        while run_loop:
            info = task.info
            logger.debug('Checking clone task')
            if info.state == vim.TaskInfo.State.success:
                logger.info('Cloned and running')
                vm = info.result
                run_loop = False
                break
            elif info.state == vim.TaskInfo.State.running:
                logger.debug('Cloning task is at %s percent' % info.progress)
            elif info.state == vim.TaskInfo.State.queued:
                logger.debug('Cloning task is queued')
            elif info.state == vim.TaskInfo.State.error:
                if info.error.fault:
                    logger.info('Cloning task has quit with error: %s' %
                                info.error.fault.faultMessage)
                else:
                    logger.info('Cloning task has quit with cancelation')
                run_loop = False
                break
            logger.debug('Sleeping 10 seconds for new check')
            sleep(10)

        # If the VM does not exist, cloning failed and the script is terminated
        if not vm:
            logger.error('Clone failed')
            return 1

        # Setting Nuage metadata
        logger.info('Setting Nuage Metadata')
        vm_option_values = []
        # Enterprise
        vm_option_values.append(
            vim.option.OptionValue(key='nuage.enterprise',
                                   value=vm_enterprise.name))
        # 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))

        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 = 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(5)

        if power_on:
            logger.info('Powering on VM. This might take a couple of seconds')
            power_on_task = vm.PowerOn()
            logger.debug('Waiting fo VM to power on')
            run_loop = True
            while run_loop:
                info = power_on_task.info
                if info.state == vim.TaskInfo.State.success:
                    run_loop = False
                    break
                elif info.state == vim.TaskInfo.State.error:
                    if info.error.fault:
                        logger.info('Power on has quit with error: %s' %
                                    info.error.fault.faultMessage)
                    else:
                        logger.info('Power on has quit with cancelation')
                    run_loop = False
                    break
                sleep(5)

    except vmodl.MethodFault as e:
        logger.critical('Caught vmodl fault: %s' % e.msg)
        return 1
    except Exception as e:
        logger.critical('Caught exception: %s' % str(e))
        return 1
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    entity_type = args.entity_type
    json_output = args.json_output
    log_file = None
    if args.logfile:
        log_file = args.logfile
    entity_name = None
    if args.entity_name:
        entity_name = args.entity_name
    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
    statistic_types = statistics_valid_types
    if args.statistic_types:
        statistic_types = args.statistic_types
#    nosslcheck          = args.nosslcheck
    time_difference = args.time_difference
    verbose = args.verbose

    # 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__)

    # Validating time_difference input
    time_check = re.compile('^([0-9]+)([m|h|d]?)$')
    time_matches = time_check.match(time_difference)
    if time_matches is None:
        logger.critical('The time indication %s is an invalid value, exiting' %
                        time_difference)
        return 1

    time_diff = int(float(time_matches.group(1)))
    if time_matches.group(2) == 'm':
        logger.debug(
            'Found m in the time difference, multiplying integer by 60')
        time_diff *= 60
    elif time_matches.group(2) == 'h':
        logger.debug(
            'Found h in the time difference, multiplying integer by 3600')
        time_diff *= 3600
    elif time_matches.group(2) == 'd':
        logger.debug(
            'Found d in the time difference, multiplying integer by 86400')
        time_diff *= 86400

    logger.debug('Time difference set to %s seconds' % time_diff)

    # 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

    # Getting entities & defining output fields
    output_type = None
    entities = []
    output_type = entity_type.capitalize()
    search_query = 'name == "%s"' % entity_name if entity_name else None
    logger.debug('Getting %ss matching the search' % output_type)
    entities = nc.user.fetcher_for_rest_name(
        entity_type.lower()).get(filter=search_query)

    if entity_type == 'VM' and entities:
        vms = entities
        entities = []
        for vm in vms:
            for vm_interface in vm.vm_interfaces.get():
                entities.append(vm_interface)

    # Filling output fields
    output_fields = [
        output_type, 'Start timestamp', 'End timestamp', 'Start date/time',
        'End date/time', '# datapoints'
    ]
    output_fields.extend(statistic_types)

    # Verifying if there are enities
    if len(entities) == 0:
        logger.critical('No matching entities found of type %s' % entity_type)
        return 1

    # Starting output
    if json_output:
        logger.debug('JSON output enabled, not setting up an output table')
        json_object = []
    else:
        logger.debug('Setting up output table')
        pt = PrettyTable(output_fields)

    # Setting general values
    stat_end_time = int(time.time())
    stat_start_time = int(stat_end_time - time_diff)
    stat_metric_types_str = ','.join(statistic_types)
    entity_data_freq = 60

    for entity in entities:
        if entity_type != 'VM' and 'BackHaul' in entity.name:
            logger.debug('Found a BackHaul %s, skipping' % output_type)
            continue

        # Getting stats collection frequency
        if entity_type != 'VM':
            logger.debug('Looking for a statistics policy on %s %s' %
                         (output_type, entity.name))
            entity_stat_policies = entity.statistics_policies.get()
            if len(entity_stat_policies) > 0:
                logger.debug(
                    'Found at least one statistics policy on %s %s, getting data collection frequency'
                    % (output_type, entity.name))
                entity_data_freq = entity_stat_policies[
                    0].data_collection_frequency
            logger.debug('Data collection frequency for %s %s saved as %s' %
                         (output_type, entity.name, entity_data_freq))

        num_data_points = int(old_div(time_diff, entity_data_freq))

        # Collecting statistics
        logger.debug(
            'Collecting %s datapoints of statistics %s on %s %s from timestamp %s to timestamp %s'
            % (num_data_points, stat_metric_types_str, output_type,
               entity.name, stat_start_time, stat_end_time))
        stats_data = entity.statistics.get_first(
            query_parameters={
                'startTime': stat_start_time,
                'endTime': stat_end_time,
                'numberOfDataPoints': num_data_points,
                'metricTypes': stat_metric_types_str
            }).stats_data

        # Determining name
        output_name = entity.name
        if entity_type == "VM":
            output_name = '%s %s' % (entity.parent.name, entity.mac)

        # Generating output row
        if json_output:
            json_dict = {
                output_type:
                output_name,
                'Start timestamp':
                stat_start_time,
                'End timestamp':
                stat_end_time,
                'Start date/time':
                datetime.datetime.fromtimestamp(stat_start_time).strftime(
                    '%Y-%m-%d %H:%M:%S'),
                'End date/time':
                datetime.datetime.fromtimestamp(stat_end_time).strftime(
                    '%Y-%m-%d %H:%M:%S'),
                '# datapoints':
                num_data_points
            }
            json_dict.update(stats_data)
            json_object.append(json_dict)
        else:
            row = [
                output_name, stat_start_time, stat_end_time,
                datetime.datetime.fromtimestamp(stat_start_time).strftime(
                    '%Y-%m-%d %H:%M:%S'),
                datetime.datetime.fromtimestamp(stat_end_time).strftime(
                    '%Y-%m-%d %H:%M:%S'), num_data_points
            ]
            for statistic_type in statistic_types:
                row.append(stats_data[statistic_type])
            pt.add_row(row)

    logger.debug('Printing output')
    if json_output:
        print(json.dumps(json_object, sort_keys=True, indent=4))
    else:
        print(pt.get_string())

    return 0
Exemple #6
0
def main():
    args = get_args()
    ip = args.ip[0]
    debug = args.debug
    verbose = args.verbose

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

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

    nc = None

    # Connecting to Nuage
    try:
        logger.info('Connecting to Nuage server %s as csproot' % ip)
        nc = vsdk.NUVSDSession(username=u'csproot',
                               password=u'csproot',
                               enterprise=u'csp',
                               api_url=u'https://%s:8443' % ip)
        nc.start()
    except IOError:
        pass

    if not nc or not nc.is_current_session():
        logger.error('Could not connect to Nuage host %s with user csproot' %
                     ip)
        return 1

    logger.info('Connected to Nuage')

    for vcenter in nc.user.vcenters.get():
        logger.info("Checking values on vCenter %s" % vcenter.name)
        replace_interfaces(logger, vcenter)

        for datacenter in vcenter.vcenter_data_centers.get():
            logger.info("Checking values on datacenter %s" % datacenter.name)
            replace_interfaces(logger, datacenter)

            for hypervisor in datacenter.vcenter_hypervisors.get():
                logger.info("Checking values for standalone hypervisor %s" %
                            hypervisor.name)
                replace_interfaces(logger, hypervisor)

            for cluster in datacenter.vcenter_clusters.get():
                logger.info("Checking values for cluster %s" % cluster.name)
                replace_interfaces(logger, cluster)

                for hypervisor in cluster.vcenter_hypervisors.get():
                    logger.info("Checking values for hypervisor %s" %
                                hypervisor.name)
                    replace_interfaces(logger, hypervisor)

    return 0
Exemple #7
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')

    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 = SmartConnectNoSSL(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 = eval(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 = eval(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 = eval(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 = eval(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 = eval(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 = eval(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 = eval(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 = eval(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 = eval(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 as e:
        logging.critical('Caught vmodl fault: {0:s}'.format(e.msg))
        return 1
    except Exception as e:
        logging.critical('Caught exception: {0:s}'.format(str(e)))
        return 1

    print('Activation of VM finished')
def main():
    """
    Main function to handle vcenter vm names and the mapping to a policy group
    """
    global logger, configuration, nc, nc_enterprise, nc_domain, nc_subnetmap, nc_policygroupmap, nc_vportmap, nc_networkmacromap, ingress_learning_acl, egress_learning_acl

    # Handling arguments
    args = get_args()
    configuration['debug'] = args.debug
    configuration['next_priority'] = args.first_priority
    configuration['log_file'] = None
    if args.logfile:
        configuration['log_file'] = args.logfile
    configuration['nuage_domain'] = args.nuage_domain
    configuration['nuage_enterprise'] = args.nuage_enterprise
    configuration['nuage_host'] = args.nuage_host
    configuration['nuage_port'] = args.nuage_port
    configuration['nuage_password'] = None
    if args.nuage_password:
        configuration['nuage_password'] = args.nuage_password
    configuration['nuage_username'] = args.nuage_username
    configuration['strictsource'] = args.strictsource
    configuration['nosslcheck'] = args.nosslcheck
    configuration['acl_type'] = args.acl_type
    configuration['verbose'] = args.verbose

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

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

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

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

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

    # Finding domain
    logger.debug('Finding domain %s' % configuration['nuage_domain'])
    nc_domain = nc.user.domains.get_first(filter="name == '%s'" %
                                          configuration['nuage_domain'])
    if nc_domain is None:
        logger.critical('Unable to find domain %s, quiting' %
                        configuration['nuage_domain'])
        return 1
    logger.info('Found domain %s' % nc_domain.name)

    # Getting enterprise
    logger.debug('Getting enterprise for domain %s' % nc_domain.name)
    nc_enterprise = vsdk.NUEnterprise(id=nc_domain.parent_id)
    nc_enterprise.fetch()

    if configuration['acl_type'] == 'SUBNET' or configuration[
            'acl_type'] == 'ZONE':
        # Mapping subnets
        logger.debug('Mapping subnets for domain %s' % nc_domain.name)
        for nc_subnet in nc_domain.subnets.get():
            logger.debug(
                'Found subnet with network %s/%s in domain %s' %
                (nc_subnet.address, nc_subnet.netmask, nc_domain.name))
            nc_subnetmap[nc_subnet.id] = {
                'id': nc_subnet.id,
                'address': nc_subnet.address,
                'netmask': nc_subnet.netmask,
                'zone': nc_subnet.parent_id
            }

    if configuration['acl_type'] == 'POLICYGROUP':
        # Mapping policy groups
        logger.debug('Mapping policy groups for domain %s' % nc_domain.name)
        for nc_policygroup in nc_domain.policy_groups.get():
            logger.debug('Found policy group %s in domain %s' %
                         (nc_policygroup.name, nc_domain.name))
            nc_policygroupmap[nc_policygroup.id] = {
                'id': nc_policygroup.id,
                'name': nc_policygroup.name
            }

    # Mapping vPorts
    logger.debug('Mapping vPorts for domain %s' % nc_domain.name)
    for nc_vport in nc_domain.vports.get():
        logger.debug('Found vPort with IP %s and MAC %s in domain %s' %
                     (nc_vport.vm_interfaces.get_first().ip_address,
                      nc_vport.vm_interfaces.get_first().mac, nc_domain.name))
        nc_vportmap[nc_vport.vm_interfaces.get_first().ip_address] = {
            'id': nc_vport.id,
            'mac': nc_vport.vm_interfaces.get_first().mac,
            'subnet': nc_vport.parent_id,
            'policygroups': []
        }
        for nc_policygroup in nc_vport.policy_groups.get():
            logger.debug(
                'Found policy group %s for vPort with %s and MAC %s in domain %s'
                % (nc_policygroup.name,
                   nc_vport.vm_interfaces.get_first().ip_address,
                   nc_vport.vm_interfaces.get_first().mac, nc_domain.name))
            nc_vportmap[nc_vport.vm_interfaces.get_first().
                        ip_address]['policygroups'].append({
                            'id':
                            nc_policygroup.id,
                            'name':
                            nc_policygroup.name
                        })

    # Mapping Network Macros
    logger.debug('Mapping Network Macros for enterprise %s' %
                 nc_enterprise.name)
    for nc_networkmacro in nc_enterprise.enterprise_networks.get():
        logger.debug(
            'Found Network Macro with IP %s and netmask %s for Enterprise %s' %
            (nc_networkmacro.address, nc_networkmacro.netmask,
             nc_enterprise.name))
        nc_networkmacromap['%s-%s' % (nc_networkmacro.address,
                                      nc_networkmacro.netmask)] = {
                                          'id': nc_networkmacro.id,
                                          'address': nc_networkmacro.address,
                                          'netmask': nc_networkmacro.netmask
                                      }

    # Checking if ACL logging rules are present
    ingress_learning_acl = nc_domain.ingress_acl_templates.get_first(
        filter="name == 'Ingress Learning ACLs'")
    egress_learning_acl = nc_domain.egress_acl_templates.get_first(
        filter="name == 'Egress Learning ACLs'")

    if ingress_learning_acl is None:
        logger.info('Creating Ingress Learning ACLs')
        ingress_learning_acl = vsdk.NUIngressACLTemplate(
            name='Ingress Learning ACLs',
            priority_type='NONE',
            priority=100,
            default_allow_non_ip=False,
            default_allow_ip=False,
            allow_l2_address_spoof=False,
            active=True)
        nc_domain.create_child(ingress_learning_acl, as_async=False)
        logger.debug('Creating Ingress ACL TCP rule')
        ingress_acl_entry_1 = vsdk.NUIngressACLEntryTemplate(
            action='FORWARD',
            description='Learning ACL for TCP traffic',
            ether_type='0x0800',
            flow_logging_enabled=True,
            location_type='ANY',
            network_type='ANY',
            priority=1000,
            protocol=6,
            reflexive=True,
            source_port='*',
            destination_port='*',
            dscp='*')
        ingress_learning_acl.create_child(ingress_acl_entry_1, as_async=False)
        logger.debug('Creating Ingress ACL UDP rule')
        ingress_acl_entry_2 = vsdk.NUIngressACLEntryTemplate(
            action='FORWARD',
            description='Learning ACL for UDP traffic',
            ether_type='0x0800',
            flow_logging_enabled=True,
            location_type='ANY',
            network_type='ANY',
            priority=1001,
            protocol=17,
            reflexive=True,
            source_port='*',
            destination_port='*',
            dscp='*')
        ingress_learning_acl.create_child(ingress_acl_entry_2, as_async=False)
        logger.debug('Creating Ingress ACL other rule')
        ingress_acl_entry_3 = vsdk.NUIngressACLEntryTemplate(
            action='FORWARD',
            description='Learning ACL for other traffic',
            ether_type='0x0800',
            flow_logging_enabled=True,
            location_type='ANY',
            network_type='ANY',
            priority=1002,
            protocol='ANY',
            source_port=None,
            destination_port=None,
            dscp='*')
        ingress_learning_acl.create_child(ingress_acl_entry_3, as_async=False)
        logger.info('Ingress ACL rules created')

    if egress_learning_acl is None:
        logger.info('Creating Egress Learning ACLs')
        egress_learning_acl = vsdk.NUEgressACLTemplate(
            name='Egress Learning ACLs',
            priority_type='NONE',
            priority=100,
            default_allow_non_ip=False,
            default_allow_ip=False,
            default_install_acl_implicit_rules=True,
            active=True)
        nc_domain.create_child(egress_learning_acl, as_async=False)
        logger.debug('Creating Egress ACL TCP rule')
        egress_acl_entry_1 = vsdk.NUEgressACLEntryTemplate(
            action='FORWARD',
            description='ACL for TCP traffic',
            ether_type='0x0800',
            flow_logging_enabled=True,
            location_type='ANY',
            network_type='ANY',
            priority=1000,
            protocol=6,
            reflexive=True,
            source_port='*',
            destination_port='*',
            dscp='*')
        egress_learning_acl.create_child(egress_acl_entry_1, as_async=False)
        logger.debug('Creating Egress ACL UDP rule')
        egress_acl_entry_2 = vsdk.NUEgressACLEntryTemplate(
            action='FORWARD',
            description='ACL for UDP traffic',
            ether_type='0x0800',
            flow_logging_enabled=True,
            location_type='ANY',
            network_type='ANY',
            priority=1001,
            protocol=17,
            reflexive=True,
            source_port='*',
            destination_port='*',
            dscp='*')
        egress_learning_acl.create_child(egress_acl_entry_2, as_async=False)
        logger.debug('Creating Egress ACL other rule')
        egress_acl_entry_3 = vsdk.NUEgressACLEntryTemplate(
            action='FORWARD',
            description='ACL for other traffic',
            ether_type='0x0800',
            flow_logging_enabled=True,
            location_type='ANY',
            network_type='ANY',
            priority=1002,
            protocol='ANY',
            source_port=None,
            destination_port=None,
            dscp='*')
        egress_learning_acl.create_child(egress_acl_entry_3, as_async=False)
        logger.info('Egress ACL rules created')

    logger.info('Starting capture server on port 514')
    capture_server = socketserver.TCPServer(('0.0.0.0', 514), ACLTCPHandler)

    try:
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        capture_server.serve_forever()
    except KeyboardInterrupt:
        logger.info('Received interrupt, finishing up')
        capture_server.shutdown()

    logger.info('All done!')
    return 1
Exemple #9
0
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    flush = args.flush
    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__)

    # 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 nosslcheck:
                vc = SmartConnectNoSSL(host=vcenter_host,
                                       user=vcenter_username,
                                       pwd=vcenter_password,
                                       port=int(vcenter_port))
            else:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port))
        except IOError as 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(r'\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(str(
                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 isinstance(nc_subnet, 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 = not flush
        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)

        if flush:
            vc_nicspec = vim.vm.device.VirtualDeviceSpec()
            vc_nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
            vc_nicspec.device = vc_vm_nic
            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(
                'Reconnecting NIC. 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(
            'Successfully attached VM %s to Nuage subnet %s, in mode %s' %
            (vcenter_vm, nuage_vm_subnet, mode))

    except vmodl.MethodFault as e:
        logger.critical('Caught vmodl fault: %s' % e.msg)
        return 1
    except Exception as e:
        logger.critical('Caught exception: %s' % str(e))

    return 0
nuage_host = args.nuage_host

# Getting host port for Nuage connection
if args.nuage_port is None:
    logger.debug(
        'No command line Nuage host port received, default will be used.')
    nuage_port = 8443
else:
    nuage_port = args.nuage_port

try:
    logger.info('Connecting to Nuage server %s:%s with username %s' %
                (nuage_host, nuage_port, nuage_username))
    nc = vspk.NUVSDSession(username=nuage_username,
                           password=nuage_password,
                           enterprise=nuage_enterprise,
                           api_url="https://{0}:{1}".format(
                               nuage_host, nuage_port))
    nc.start()
    nuage_user = nc.user
except Exceptione 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))
    exit()
# Main logic
for subnet in nuage_user.subnets.get():
    if subnet.associated_shared_network_resource_id is not None:
        shared_net_obj = vspk.NUSharedNetworkResource(
            id=subnet.associated_shared_network_resource_id).fetch()[0]
def main():
    """
    Main function to handle vcenter vm os and the mapping to a policy group
    """

    # Handling arguments
    args = get_args()
    clusters = []
    if args.clusters:
        clusters = args.clusters
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    mapping_file = args.mapping_file
    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
    remove_policygroups = args.remove_policygroups
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    vcenter_host = args.vcenter_host
    vcenter_https_port = args.vcenter_https_port
    vcenter_password = None
    if args.vcenter_password:
        vcenter_password = args.vcenter_password
    vcenter_username = args.vcenter_username

    # 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__)

    # 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))

    # 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 {0:s} for user {1:s}: '.
            format(vcenter_host, vcenter_username))

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        try:
            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 IOError:
            pass

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

        # Connecting to vCenter
        try:
            logger.info(
                'Connecting to vCenter server {0:s}:{1:d} with username {2:s}'.
                format(vcenter_host, vcenter_https_port, vcenter_username))
            if nosslcheck:
                vc = SmartConnectNoSSL(host=vcenter_host,
                                       user=vcenter_username,
                                       pwd=vcenter_password,
                                       port=int(vcenter_https_port))
            else:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_https_port))

        except IOError:
            pass

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

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

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

    except vmodl.MethodFault as e:
        logger.critical('Caught vmodl fault: {0:s}'.format(e.msg))
        return 1

    # CSV Handling
    if not os.path.isfile(mapping_file):
        logger.critical(
            'Mapping file {0:s} does not exist, exiting'.format(mapping_file))
        return 1

    mapping_list = {}
    # CSV fields:
    # vCenter VM name regex, Policy group
    logger.debug('Parsing mapping file {0:s}'.format(mapping_file))

    with open(mapping_file, 'rb') as maplist:
        mapping_list_raw = csv.reader(maplist, delimiter=',', quotechar='"')
        for row in mapping_list_raw:
            logger.debug('Found CSV row: {0:s}'.format(','.join(row)))
            mapping_list[row[0]] = row[1]

    # Getting clusters in the current vCenter
    logger.debug(
        'Gathering all Clusters from the vCenter {0:s}'.format(vcenter_host))
    content = vc.content
    obj_view = content.viewManager.CreateContainerView(
        content.rootFolder, [vim.ClusterComputeResource], True)
    vc_cl_list = obj_view.view
    obj_view.Destroy()

    for vc_cl in vc_cl_list:
        if vc_cl.name not in clusters:
            continue

        # Getting VMs in the current vCenter Cluster
        logger.debug('Gathering all VMs from the vCenter Cluster {0:s}'.format(
            vc_cl.name))
        obj_view = content.viewManager.CreateContainerView(
            vc_cl, [vim.VirtualMachine], True)
        vc_vm_list = obj_view.view
        obj_view.Destroy()

        for vc_vm in vc_vm_list:
            # Verifying if VM matches a regex in the list
            logger.debug('Found VM {0:s}, checking'.format(vc_vm.name))

            # If the VM is a template skip it
            if vc_vm.config.template:
                logger.debug('VM {0:s} is a template, skipping'.format(
                    vc_vm.name))
                continue

            # Getting VM info
            nc_vm_properties = {}
            vc_vm_nuage_enterprise = next((x for x in vc_vm.config.extraConfig
                                           if x.key == 'nuage.enterprise'),
                                          None)
            vc_vm_nuage_domain = next((x for x in vc_vm.config.extraConfig
                                       if x.key == 'nuage.nic0.domain'), None)
            vc_vm_nuage_l2domain = next((x for x in vc_vm.config.extraConfig
                                         if x.key == 'nuage.nic0.l2domain'),
                                        None)
            vc_vm_nuage_zone = next((x for x in vc_vm.config.extraConfig
                                     if x.key == 'nuage.nic0.zone'), None)
            vc_vm_nuage_network = next((x for x in vc_vm.config.extraConfig
                                        if x.key == 'nuage.nic0.network'),
                                       None)

            # Check if all the settings for an L3 domain are present
            if vc_vm_nuage_enterprise is None or vc_vm_nuage_domain is None or vc_vm_nuage_zone is None or vc_vm_nuage_network is None:
                # Check if it is an L2 domain
                if vc_vm_nuage_enterprise is None or vc_vm_nuage_l2domain is None:
                    logger.info(
                        'VM {0:s} has no correct Nuage metadata set, assuming it is not a VM connected through Nuage and skipping it.'
                        .format(vc_vm.name))
                    continue

            nc_vm_properties['name'] = vc_vm.name
            nc_vm_properties['os'] = vc_vm.config.guestFullName
            nc_vm_properties['nuage.enterprise'] = vc_vm_nuage_enterprise.value
            # If domain is not set, it is an l2 domain
            if vc_vm_nuage_domain is not None:
                nc_vm_properties['nuage.domain'] = vc_vm_nuage_domain.value
                nc_vm_properties['nuage.l2domain'] = None
                nc_vm_domain_name = vc_vm_nuage_domain.value
            else:
                nc_vm_properties['nuage.domain'] = None
                nc_vm_properties['nuage.l2domain'] = vc_vm_nuage_l2domain.value
                nc_vm_domain_name = vc_vm_nuage_l2domain.value
            if vc_vm_nuage_zone is not None:
                nc_vm_properties['nuage.zone'] = vc_vm_nuage_zone.value
            else:
                nc_vm_properties['nuage.zone'] = None
            if vc_vm_nuage_network is not None:
                nc_vm_properties['nuage.network'] = vc_vm_nuage_network.value
            else:
                nc_vm_properties['nuage.network'] = None

            logger.debug(
                'VM {0:s} with OS {1:s} has following Nuage settings: Enterprise {2:s}, Domain {3:s}, Zone {4:s}, Subnet {5:s}'
                .format(nc_vm_properties['name'], nc_vm_properties['os'],
                        nc_vm_properties['nuage.enterprise'],
                        nc_vm_domain_name, nc_vm_properties['nuage.zone'],
                        nc_vm_properties['nuage.network']))

            # Getting VM MAC
            vc_vm_nic = next(
                (x for x in vc_vm.config.hardware.device
                 if isinstance(x, vim.vm.device.VirtualEthernetCard)), None)
            if vc_vm_nic is None:
                logger.error(
                    'VM {0:s} has no valid network interfaces, skipping it'.
                    format(nc_vm_properties['name']))
                continue

            nc_vm_properties['mac'] = vc_vm_nic.macAddress
            logger.debug('VM {0:s} has MAC {1:s}'.format(
                nc_vm_properties['name'], nc_vm_properties['mac']))

            # Getting Nuage vport for this VM
            nc_vm_properties['vm_interface'] = nc.user.vm_interfaces.get_first(
                filter="MAC == '{0:s}'".format(nc_vm_properties['mac']))
            if nc_vm_properties['vm_interface'] is None:
                logger.error(
                    'VM {0:s} with MAC address {1:s} is not known in Nuage, skipping it'
                    .format(nc_vm_properties['name'], nc_vm_properties['mac']))
                continue

            # Getting Nuage vport for this VM
            nc_vm_properties['vport'] = vsdk.NUVPort(
                id=nc_vm_properties['vm_interface'].vport_id)
            try:
                nc_vm_properties['vport'].fetch()
            except BambouHTTPError:
                logger.error(
                    'VM {0:s} with MAC address {1:s} has a vm_interface but no vport in Nuage, this should not be possible... Skipping it'
                    .format(nc_vm_properties['name'], nc_vm_properties['mac']))
                continue

            logger.debug(
                'Found vm_interface and vport for VM {0:s} with MAC address {1:s}'
                .format(nc_vm_properties['name'], nc_vm_properties['mac']))

            # Checking regex's on VMs
            nc_vm_pgs = []
            for regex in list(mapping_list.keys()):
                logger.debug(
                    'Checking regex "{0:s}" on VM {1:s} with OS {2:s}'.format(
                        regex, nc_vm_properties['name'],
                        nc_vm_properties['os']))
                pattern = re.compile(regex)
                if pattern.match(nc_vm_properties['os']):
                    logger.debug(
                        'Found match: regex "{0:s}" and VM OS "{1:s}", adding to the task list to hand over to Nuage.'
                        .format(regex, nc_vm_properties['os']))
                    nc_vm_pgs.append(mapping_list[regex])

            if len(nc_vm_pgs) > 0:
                logger.debug(
                    'Handing task over to Nuage part to set {0:d} Policy Groups on VM {1:s}'
                    .format(len(nc_vm_pgs), nc_vm_properties['name']))
                update_nuage_policy_group(
                    logger=logger,
                    nc=nc,
                    nc_vm_properties=nc_vm_properties,
                    nc_vm_pgs=nc_vm_pgs,
                    remove_policygroups=remove_policygroups)

    logger.info('All done!')
    return 0
Exemple #12
0
def main():
    """
    Main function to handle vcenter vm names and the mapping to a policy group
    """

    # Handling arguments
    args                = get_args()
    debug               = args.debug
    extended            = args.extended
    json_output         = args.json_output
    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
    time_difference     = args.time_difference
    verbose             = args.verbose

    # 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__)

    # Validating time_difference input
    time_check = re.compile('^([0-9]+)([m|h|d]?)$')
    time_matches = time_check.match(time_difference)
    if time_matches is None:
        logger.critical('The time indication %s is an invalid value, exiting' % time_difference)
        return 1

    time_diff = int(float(time_matches.group(1)))
    if time_matches.group(2) == 'm':
        logger.debug('Found m in the time difference, multiplying integer by 60')
        time_diff *= 60
    elif time_matches.group(2) == 'h':
        logger.debug('Found h in the time difference, multiplying integer by 3600')
        time_diff *= 3600
    elif time_matches.group(2) == 'd':
        logger.debug('Found d in the time difference, multiplying integer by 86400')
        time_diff *= 86400

    logger.debug('Time difference set to %s seconds' % time_diff)

    # 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

    if json_output:
        logger.debug('JSON output enabled, not setting up an output table')
        json_object = []
    elif extended:
        logger.debug('Setting up extended output table')
        pt = PrettyTable(['Enterprise', 'Timestamp', 'Date/Time', 'Type', 'Entity', 'Entity parent', 'Extended info'])
    else:
        logger.debug('Setting up basic output table')
        pt = PrettyTable(['Enterprise', 'Timestamp', 'Date/Time', 'Type', 'Entity', 'Entity parent'])

    unix_check_time = time.time() - time_diff
    logger.debug('Gathering all events from after UNIX timestamp %s' % unix_check_time)

    for ent in nc.user.enterprises.get():
        logger.debug('Gathering events for enterprise %s' % ent.name)
        for event in ent.event_logs.get(filter="eventReceivedTime >= '%s'" % int(unix_check_time * 1000)):
            logger.debug('Found event of type %s with timestamp %s' % (event.type, event.event_received_time))
            clean_time = datetime.datetime.fromtimestamp(int(old_div(event.event_received_time, 1000))).strftime('%Y-%m-%d %H:%M:%S')

            if json_output:
                json_dict = {
                    'Enterprise': ent.name,
                    'Timestamp': event.event_received_time,
                    'Date/Time': clean_time,
                    'Type': event.type,
                    'Entity': event.entity_type,
                    'Entity parent': event.entity_parent_type
                }
                if extended:
                    json_dict['Extended info'] = event.entities
                json_object.append(json_dict)
            elif extended:
                pt.add_row([ent.name, event.event_received_time, clean_time, event.type, event.entity_type, event.entity_parent_type, json.dumps(event.entities)])
            else:
                pt.add_row([ent.name, event.event_received_time, clean_time, event.type, event.entity_type, event.entity_parent_type])

    logger.debug('Printing output')
    if json_output:
        print(json.dumps(json_object, sort_keys=True, indent=4))
    else:
        print(pt.get_string(sortby='Timestamp'))

    return 0
from vspk import v6 as vsdk

if __name__ == '__main__':

    # Connection with a certificate
    cert = ("/path/to/csproot.pem", "/path/to/csproot-Key.pem")
    session = vsdk.NUVSDSession(username='******',
                                enterprise='csp',
                                api_url='https://localhost:7443',
                                certificate=cert)
    session.start()

    # Reset the session to start a new one
    session.reset()

    # Connection with a user/password
    session = vsdk.NUVSDSession(username="******",
                                password="******",
                                enterprise="csp",
                                api_url="https://localhost:8443")
    session.start()
Exemple #14
0
def main():
    """
    Main function to handle vcenter vm names and the mapping to a policy group
    """

    # Handling arguments
    args                = get_args()
    debug               = args.debug
    json_output         = args.json_output
    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

    # 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__)

    # 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

    if json_output:
        logger.debug('Setting up json output')
        json_object = []
    else:
        logger.debug('Setting up basic output table')
        pt = PrettyTable(['Enterprise', 'Domain', 'VM Name', 'VM IP', 'VM MAC', 'FIP'])

    logger.debug('Getting FIPs for the logged in user.')
    for nc_fip in nc.user.floating_ips.get():
        logger.debug('Found FIP with IP %s' % nc_fip.address)
        nc_vport = nc_fip.vports.get()[0]
        nc_interface = nc_vport.vm_interfaces.get()[0]
        nc_vm = nc_vport.vms.get()[0]

        if json_output:
            json_dict = {
                'Enterprise': nc_vm.enterprise_name,
                'Domain': nc_interface.domain_name,
                'VM Name': nc_vm.name,
                'VM IP': nc_interface.ip_address,
                'VM MAC': nc_interface.mac,
                'FIP': nc_fip.address
            }
            json_object.append(json_dict)
        else:
            logger.debug('Add row: %s, %s, %s, %s, %s, %s' % (nc_vm.enterprise_name, nc_interface.domain_name, nc_vm.name, nc_interface.ip_address, nc_interface.mac, nc_fip.address))
            pt.add_row([nc_vm.enterprise_name, nc_interface.domain_name, nc_vm.name, nc_interface.ip_address, nc_interface.mac, nc_fip.address])

    if json_output:
        print(json.dumps(json_object, sort_keys=True, indent=4))
    else:
        print(pt)

    return 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

    # 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
Exemple #16
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__)

    # 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
    timeout_start = time.time()
    while time.time() < timeout_start + timeout:
        job.fetch()
        if job.status == 'SUCCESS':
            print('SUCCESS :: Re-keying Job succeeded!')
            return True
        if job.status == 'FAILED':
            return False
        time.sleep(1)
    print('ERROR :: Job {} failed to return its status in {}sec interval'.format(
        job.command, timeout))

nuage_session = vspk.NUVSDSession(
    username=n_username,
    password=n_password,
    enterprise=n_org,
    api_url=api_url)

me = nuage_session.start().user

# get parent for the re-key job object
org = me.enterprises.get_first(filter='name == "{}"'.format(org_name))

# create job object
job = vspk.NUJob(command='FORCE_KEYSERVER_UPDATE')

print('Starting {} job for the {} Organization'.format(
    'FORCE_KEYSERVER_UPDATE',
    org.name))
Exemple #18
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
    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__)

    # 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

    # Updating VM UUID
    logger.info('Updating VM %s UUID to %s' % (vmid, uuid))
    vm = vsdk.NUVM(id=vmid)
    try:
        vm.fetch()
        logger.debug('VM ID %s - OLD UUID %s - NEW UUID %s' % (vmid, vm.uuid, uuid))
        vm.uuid = uuid
        vm.resync_info = None
        vm.save()
    except Exception as e:
        logger.critical('VM %s can not be updated because of error %s' % (vmid, str(e)))
        return 1

    logger.info('Updated VM %s' % vmid)
    return 0
Exemple #19
0
                for cur_rule in cur_acl.ingress_acl_entry_templates.get():
                    print('        |- Rule: %s' % cur_rule.description)

            for cur_acl in cur_domain.egress_acl_templates.get():
                print('    |- Egress ACL: %s' % cur_acl.name)
                for cur_rule in cur_acl.egress_acl_entry_templates.get():
                    print('        |- Rule: %s' % cur_rule.description)

        print(
            '--------------------------------------------------------------------------------'
        )


session_1 = vsdk.NUVSDSession(username='******',
                              enterprise='csp',
                              certificate=('nuage/vsd01.nuage.intern.pem',
                                           'nuage/vsd01.nuage.intern-Key.pem'),
                              api_url='https://vsd01.nuage.intern:7443')
session_1.start()

session_2 = vsdk.NUVSDSession(
    username='******',
    enterprise='csp',
    certificate=('nuage/vsd02.nuage.intern.pem',
                 '/Users/pdellaer/nuage/vsd02.nuage.intern-Key.pem'),
    api_url='https://vsd02.nuage.intern:7443')
session_2.start()

session_3 = vsdk.NUVSDSession(username='******',
                              password='******',
                              enterprise='csp',
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

    # 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
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    json_output = args.json_output
    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
    verbose = args.verbose

    # 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__)

    # 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 %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://{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

    if json_output:
        logger.debug('Setting up json output')
        json_object = []
    else:
        logger.debug('Setting up basic output table')
        pt = PrettyTable(['Enterprise', 'Domain', '# vPorts'])

    logger.debug('Fetching enterprises with flow collection enabled')
    for ent in nc.user.enterprises.get(filter='flowCollectionEnabled == "ENABLED"'):
        logger.debug('Handling enterprise: {0:s}'.format(ent.name))
        for dom in ent.domains.get(filter='flowCollectionEnabled == "INHERITED" OR flowCollectionEnabled == "ENABLED"'):
            logger.debug('Handling domain: {0:s}'.format(dom.name))
            _, _, vport_count = dom.vports.count()

            if json_output:
                json_dict = {
                    'Enterprise': ent.name,
                    'Domain': dom.name,
                    '# vPorts': vport_count
                }
                json_object.append(json_dict)
            else:
                logger.debug('Add row: {0:s}, {1:s}, {2:d}'.format(
                    ent.name, dom.name, vport_count))
                pt.add_row([ent.name, dom.name, vport_count])

    if json_output:
        print(json.dumps(json_object, sort_keys=True, indent=4))
    else:
        print(pt)

    return 0
def main():
    """
    Backup the vCenter Integration Node configuration
    """

    # 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
    output_folder = args.output_folder
    #    nosslcheck = args.nosslcheck
    verbose = args.verbose
    # 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__)

    # Checking if folder is writeable
    if not os.access(output_folder, os.W_OK):
        logger.critical(
            'Folder {0:s} is not writable, exiting.'.format(output_folder))
        return 1

    # 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))

    nc = None

    # Connecting to Nuage
    try:
        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 IOError:
        pass

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

    logger.info('Connected to Nuage')

    # Run through each vCenter
    for nvc in nc.user.vcenters.get():
        logger.debug('Running for vCenter {0:s}'.format(nvc.name))
        hosts = []
        for ndc in nvc.vcenter_data_centers.get():
            logger.debug('Running for DC {0:s}'.format(ndc.name))
            for ncl in ndc.vcenter_clusters.get():
                logger.debug('Running for cluster {0:s}'.format(ncl.name))
                for host in ncl.vcenter_hypervisors.get():
                    logger.debug('Handling host {0:s}'.format(host.name))
                    host = [
                        host.hypervisor_ip, host.name, host.hypervisor_user,
                        host.hypervisor_password, host.mgmt_network_portgroup,
                        host.data_network_portgroup, host.vm_network_portgroup,
                        host.multicast_source_portgroup, host.allow_mgmt_dhcp,
                        host.mgmt_ip_address, host.mgmt_netmask,
                        host.mgmt_gateway, host.mgmt_dns1, host.mgmt_dns2,
                        host.separate_data_network, host.allow_data_dhcp,
                        host.data_ip_address, host.data_netmask,
                        host.data_gateway, host.data_dns1, host.data_dns2,
                        host.mtu, host.v_require_nuage_metadata,
                        host.generic_split_activation, host.multi_vmssupport,
                        host.dhcp_relay_server, host.flow_eviction_threshold,
                        host.datapath_sync_timeout,
                        host.network_uplink_interface,
                        host.network_uplink_interface_ip,
                        host.network_uplink_interface_netmask,
                        host.network_uplink_interface_gateway,
                        host.customized_script_url, host.personality,
                        host.site_id, host.nfs_log_server, host.nfs_mount_path,
                        host.primary_nuage_controller,
                        host.secondary_nuage_controller, host.ntp_server1,
                        host.ntp_server2, host.static_route,
                        host.static_route_netmask, host.static_route_gateway,
                        host.multicast_send_interface,
                        host.multicast_send_interface_ip,
                        host.multicast_send_interface_netmask,
                        host.multicast_receive_interface_ip,
                        host.multicast_receive_interface_netmask, '', ''
                    ]
                    hosts.append(host)

                logger.debug('Writing CSV for vCenter {0:s}'.format(nvc.name))
                with open('{0:s}/{1:s}.csv'.format(output_folder, nvc.name),
                          'w') as hostlist:
                    writer = csv.writer(hostlist,
                                        delimiter=',',
                                        quotechar='"',
                                        quoting=csv.QUOTE_ALL)
                    writer.writerows(hosts)

            logger.info('Completed all tasks.')
            return 0
Exemple #23
0
def main():
    """
    Main function to gather the information on the VM applied policies
    """
    global configuration, logger, output_parser

    # Handling arguments
    args = get_args()
    configuration = {}
    configuration['debug'] = args.debug
    configuration['json_output'] = args.json_output
    configuration['log_file'] = None
    if args.logfile:
        configuration['log_file'] = args.logfile
    configuration['nuage_enterprise'] = args.nuage_enterprise
    configuration['nuage_host'] = args.nuage_host
    configuration['nuage_port'] = args.nuage_port
    configuration['nuage_password'] = None
    if args.nuage_password:
        configuration['nuage_password'] = args.nuage_password
    configuration['nuage_username'] = args.nuage_username
    configuration['verbose'] = args.verbose

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

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

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

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

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

    # Setting output correctly
    output_fields = [
        'VM Name',
        'Interface MAC',
        'Enterprise',
        'Domain',
        'Domain type',
        'ACL type',
        'Ether type',
        'Protocol',
        'Source type',
        'Source name',
        'Destination type',
        'Destination name',
        'Source port',
        'Destination port',
        'DSCP',
        'Stateful',
        'Action'
    ]

    # Starting output
    if configuration['json_output']:
        logger.debug('JSON output enabled, not setting up an output table')
        output_parser = []
    else:
        logger.debug('Setting up output table')
        output_parser = PrettyTable(output_fields)

    # Gathering Enterprises
    for enterprise in nc.user.enterprises.get():
        logger.debug('Handling enterprise {0:s}'.format(enterprise.name))

        # Handling L2 domains
        for l2_domain in enterprise.l2_domains.get():
            logger.debug('Checking if L2 domain {0:s} is connected to a Shared Network'.format(l2_domain.name))
            if l2_domain.associated_shared_network_resource_id:
                logger.info('L2 domain {0:s} is linked to a Shared Network'.format(l2_domain.name))
                for vm_interface in l2_domain.vm_interfaces.get():
                    logger.debug('Handling VM interface with MAC {0:s}'.format(vm_interface.mac))
                    handle_vm_interface(vm_interface=vm_interface, enterprise=enterprise, domain=l2_domain, domain_type='L2', nc=nc)

        # Handling L3 domains
        for domain in enterprise.domains.get():
            logger.debug('Checking if domain {0:s} has a subnet connected to a Shared Network'.format(domain.name))
            for subnet in domain.subnets.get():
                logger.debug('Checking if subnet {0:s} is connected to a Shared Network'.format(subnet.name))
                if subnet.associated_shared_network_resource_id:
                    logger.info('Subnet {0:s} is linked to a Shared Network'.format(subnet.name))
                    for vm_interface in subnet.vm_interfaces.get():
                        logger.debug('Handling VM interface with MAC {0:s}'.format(vm_interface.mac))
                        handle_vm_interface(vm_interface=vm_interface, enterprise=enterprise, domain=domain, domain_type='L3', nc=nc)

    logger.debug('Printing output')
    if configuration['json_output']:
        print(json.dumps(output_parser, sort_keys=True, indent=4))
    else:
        print(output_parser.get_string())

    return 0
def main():
    """
    Main function to gather the information on the VM applied policies
    """
    global configuration, logger, output_parser

    # Handling arguments
    args = get_args()
    configuration = {}
    configuration['debug'] = args.debug
    configuration['json_output'] = args.json_output
    configuration['log_file'] = None
    if args.logfile:
        configuration['log_file'] = args.logfile
    configuration['nuage_enterprise'] = args.nuage_enterprise
    configuration['nuage_host'] = args.nuage_host
    configuration['nuage_port'] = args.nuage_port
    configuration['nuage_password'] = None
    if args.nuage_password:
        configuration['nuage_password'] = args.nuage_password
    configuration['nuage_username'] = args.nuage_username
#    configuration['nosslcheck'] = args.nosslcheck
    configuration['verbose'] = args.verbose
    configuration['vm_names'] = []
    if args.vm_names:
        configuration['vm_names'] = args.vm_names

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

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

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

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

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

    # Setting output correctly
    output_fields = [
        'VM Name',
        'Interface MAC',
        'ACL type',
        'Ether type',
        'Protocol',
        'Source type',
        'Source name',
        'Destination type',
        'Destination name',
        'Source port',
        'Destination port',
        'DSCP',
        'Stateful',
        'Action'
    ]

    # Gathering VMs
    vms = []
    if configuration['vm_names']:
        for vm_name in configuration['vm_names']:
            logger.debug('Getting VMs matching the name %s' % vm_name)
            entities = nc.user.vms.get(filter='name == "%s"' % vm_name)
            vms.extend(entities)
    else:
        logger.debug('Getting all VMs')
        vms = nc.user.vms.get()

    # Gathering VM Interfaces
    vm_interfaces = []
    logger.debug('Getting all VM interfaces for the selected VMs')
    for vm in vms:
        vm_interfaces.extend(vm.vm_interfaces.get())

    # Verifying if there are enities
    if len(vm_interfaces) == 0:
        logger.critical('No matching vms found')
        return 1

    # Starting output
    if configuration['json_output']:
        logger.debug('JSON output enabled, not setting up an output table')
        output_parser = []
    else:
        logger.debug('Setting up output table')
        output_parser = PrettyTable(output_fields)

    # Gathering ACL rules and handling them
    for vm_interface in vm_interfaces:
        logger.debug('Gathering VM interface policy decisions')
        policy_decisions = vm_interface.policy_decisions.get_first()
        ingress_acl_entries = policy_decisions.ingress_acls[0]['entries']
        egress_acl_entries = policy_decisions.egress_acls[0]['entries']
        forward_acl_entries = policy_decisions.ingress_adv_fwd[0]['entries']
        logger.debug('Found %s ingress ACLs and %s egress ACLs' % (len(ingress_acl_entries), len(egress_acl_entries)))

        logger.debug('Handling Ingress ACL entries')
        for entry in ingress_acl_entries:
            acl_rule = None

            logger.debug('Using minimal information from the policy decision entry itself')
            output = {
                'VM Name': vm_interface.parent.name,
                'Interface MAC': vm_interface.mac,
                'ACL type': 'Ingress',
                'Ether type': entry['etherType'],
                'Protocol': entry['protocol'],
                'Source type': 'VM',
                'Source name': vm_interface.parent.name,
                'Destination type': entry['destinationType'],
                'Destination name': entry['destinationValue'],
                'Source port': entry['sourcePort'],
                'Destination port': entry['destinationPort'],
                'DSCP': entry['DSCP'],
                'Stateful': '',
                'Action': entry['actionDetails']['actionType']
            }

            if entry['aclTemplateEntryId']:
                logger.debug('Finding the actual Ingress ACL Template Entry to use its data')
                # We are using this approach with the Stats ID as the aclTemplateEntryId points to the stats ID of an Ingress/Egress ACL Entry Template in the current version (bug report generated)
                acl_rule = nc.user.ingress_acl_entry_templates.get_first(filter='statsID == "%s"' % entry['aclTemplateEntryId'])

            if acl_rule:
                logger.debug('Found a matching Ingress ACL Template Entry: %s' % acl_rule.description)
                output['Ether type'] = acl_rule.ether_type
                output['Protocol'] = acl_rule.protocol
                output['Source type'] = acl_rule.location_type
                if acl_rule.location_type and nc.user.fetcher_for_rest_name(acl_rule.location_type.lower()) is not None:
                    output['Source name'] = nc.user.fetcher_for_rest_name(acl_rule.location_type.lower()).get_first(filter='ID == "%s"' % acl_rule.location_id).name
                output['Destination type'] = acl_rule.network_type
                if acl_rule.network_type and nc.user.fetcher_for_rest_name(acl_rule.network_type.lower()) is not None:
                    output['Destination name'] = nc.user.fetcher_for_rest_name(acl_rule.network_type.lower()).get_first(filter='ID == "%s"' % acl_rule.network_id).name
                output['Source port'] = acl_rule.source_port
                output['Destination port'] = acl_rule.destination_port
                output['DSCP'] = acl_rule.dscp
                output['Stateful'] = acl_rule.stateful
                output['Action'] = acl_rule.action

            handle_output(output=output)

        logger.debug('Handling Egress ACL entries')
        for entry in egress_acl_entries:
            acl_rule = None

            logger.debug('Using minimal information from the policy decision entry itself')
            output = {
                'VM Name': vm_interface.parent.name,
                'Interface MAC': vm_interface.mac,
                'ACL type': 'Egress',
                'Ether type': entry['etherType'],
                'Protocol': entry['protocol'],
                'Source type': 'VM',
                'Source name': vm_interface.parent.name,
                'Destination type': entry['destinationType'],
                'Destination name': entry['destinationValue'],
                'Source port': entry['sourcePort'],
                'Destination port': entry['destinationPort'],
                'DSCP': entry['DSCP'],
                'Stateful': '',
                'Action': entry['actionDetails']['actionType']
            }

            if entry['aclTemplateEntryId']:
                logger.debug('Finding the actual Egress ACL Template Entry to use its data')
                # We are using this approach with the Stats ID as the aclTemplateEntryId points to the stats ID of an Ingress/Egress ACL Entry Template in the current version (bug report generated)
                acl_rule = nc.user.egress_acl_entry_templates.get_first(filter='statsID == "%s"' % entry['aclTemplateEntryId'])

            if acl_rule:
                logger.debug('Found a matching Egress ACL Template Entry: %s' % acl_rule.description)
                output['Ether type'] = acl_rule.ether_type
                output['Protocol'] = acl_rule.protocol
                output['Source type'] = acl_rule.location_type
                if acl_rule.location_type and nc.user.fetcher_for_rest_name(acl_rule.location_type.lower()) is not None:
                    output['Source name'] = nc.user.fetcher_for_rest_name(acl_rule.location_type.lower()).get_first(filter='ID == "%s"' % acl_rule.location_id).name
                output['Destination type'] = acl_rule.network_type
                if acl_rule.network_type and nc.user.fetcher_for_rest_name(acl_rule.network_type.lower()) is not None:
                    output['Destination name'] = nc.user.fetcher_for_rest_name(acl_rule.network_type.lower()).get_first(filter='ID == "%s"' % acl_rule.network_id).name
                output['Source port'] = acl_rule.source_port
                output['Destination port'] = acl_rule.destination_port
                output['DSCP'] = acl_rule.dscp
                output['Stateful'] = acl_rule.stateful
                output['Action'] = acl_rule.action

            handle_output(output=output)

        logger.debug('Handling Redirect policies entries')
        for entry in forward_acl_entries:
            acl_rule = None

            logger.debug('Using minimal information from the policy decision entry itself')
            output = {
                'VM Name': vm_interface.parent.name,
                'Interface MAC': vm_interface.mac,
                'ACL type': 'Forward',
                'Ether type': entry['etherType'],
                'Protocol': entry['protocol'],
                'Source type': 'VM',
                'Source name': vm_interface.parent.name,
                'Destination type': entry['destinationType'],
                'Destination name': entry['destinationValue'],
                'Source port': entry['sourcePort'],
                'Destination port': entry['destinationPort'],
                'DSCP': entry['DSCP'],
                'Stateful': '',
                'Action': entry['actionDetails']['actionType']
            }

            if entry['ingressAdvFwdTemplateEntryId']:
                logger.debug('Finding the actual Ingress Advanced ACL Template Entry to use its data')
                # We are using this approach with the Stats ID as the ingressAdvFwdTemplateEntryId points to the stats ID of an Ingress/Egress ACL Entry Template in the current version (bug report generated)
                acl_rule = nc.user.ingress_adv_fwd_entry_templates.get_first(filter='statsID == "%s"' % entry['ingressAdvFwdTemplateEntryId'])

            if acl_rule:
                logger.debug('Found a matching Ingress Advanced ACL Template Entry: %s' % acl_rule.description)
                output['Ether type'] = acl_rule.ether_type
                output['Protocol'] = acl_rule.protocol
                output['Source type'] = acl_rule.location_type
                if acl_rule.location_type and nc.user.fetcher_for_rest_name(acl_rule.location_type.lower()) is not None:
                    output['Source name'] = nc.user.fetcher_for_rest_name(acl_rule.location_type.lower()).get_first(filter='ID == "%s"' % acl_rule.location_id).name
                output['Destination type'] = acl_rule.network_type
                if acl_rule.network_type and nc.user.fetcher_for_rest_name(acl_rule.network_type.lower()) is not None:
                    output['Destination name'] = nc.user.fetcher_for_rest_name(acl_rule.network_type.lower()).get_first(filter='ID == "%s"' % acl_rule.network_id).name
                output['Source port'] = acl_rule.source_port
                output['Destination port'] = acl_rule.destination_port
                output['DSCP'] = acl_rule.dscp
                output['Action'] = acl_rule.action

            handle_output(output=output)

    logger.debug('Printing output')
    if configuration['json_output']:
        print(json.dumps(output_parser, sort_keys=True, indent=4))
    else:
        print(output_parser.get_string())

    return 0
from __future__ import print_function
import logging

from vspk import v6 as vsdk
from vspk.utils import set_log_level

set_log_level(logging.ERROR)

session = vsdk.NUVSDSession(username='******', password='******', enterprise='csp', api_url='https://localhost:8443')
session.start()
csproot = session.user

# Count will make a request to the backend to retrieve the number of enterprises
(_, _, nb_enterprises) = csproot.enterprises.count()
print('Number of enterprises to retrieve = %s' % nb_enterprises)

# Fetch will get all information of each enterprise from the server
csproot.enterprises.fetch()

for enterprise in csproot.enterprises:
    print(enterprise.name)
def did_receive_push(data):
    """ Receive delegate
    """
    import pprint
    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(data)


if __name__ == '__main__':

    import sys
    sys.setrecursionlimit(50)

    # create a user session for user csproot
    session = vsdk.NUVSDSession(username="******",
                                password="******",
                                enterprise="csp",
                                api_url="https://localhost:8443")

    # start the session
    # now session contains a push center and the connected user
    session.start()

    session.reset()
    session.start()

    # we get the push center from the session
    push_center = session.push_center

    # we register our delegate that will be called on each event
    push_center.add_delegate(did_receive_push)