Example #1
0
def main(args):
    api_url = "https://"+str(args['--vsd'])+":8443"
    try:
        session = vsdk.NUVSDSession(username='******', password='******', enterprise='csp', api_url=api_url)
        session.start()
        csproot = session.user
    except:
        print("ERROR: Could not establish connection to VSD API")
        sys.exit(1)

    print("Reading IP list from file ...")
    with open(str(args['--ipfile'])) as f:
        addresses = f.read().splitlines()
    print(" --- DONE\n")

    print("Fetching Enterprise object ...")
    filter_str = 'name == "'+str(args['--enterprise'])+'"'
    enterprise_test = csproot.enterprises.get_first(filter=filter_str)
    print(" --- DONE\n")

    print("Creating Network Macro Group ...")
    networkMacroGroupName = str(args['--ipfile'])
    networkMacroGroupName = networkMacroGroupName.replace('.txt','')
    networkMacroGroup = create_networkMacroGroup(enterprise_test,networkMacroGroupName)
    print(" --- DONE\n")

    print("Creating Network Macros and attaching them to the Network Macro Group ...")
    for address in addresses:
        networkMacro = create_networkMacro(enterprise_test,ipaddr.IPv4Network(address))
        assign_networkMacro_to_networkMacroGroup(networkMacroGroup,networkMacro)
    print(" --- DONE\n")
def start_nuage_connection(nuage_host, nuage_port, nuage_username,
                           nuage_password, nuage_organization, logger):

    logger.info('Connecting to Nuage server %s:%s with username %s' %
                (nuage_host, nuage_port, nuage_username))

    session = vsdk.NUVSDSession(username=nuage_username,
                                password=nuage_password,
                                enterprise=nuage_organization,
                                api_url="https://%s:%s" %
                                (nuage_host, nuage_port))

    # Connecting to Nuage

    try:

        session.start()

    except:

        logger.error(
            'Could not connect to Nuage host %s with user %s, enterprise %s and specified password'
            % (nuage_host, nuage_username, nuage_enterprise))

    return session.user
Example #3
0
def login(nuage_host, nuage_port, nuage_username, nuage_password,
          nuage_organization):
    """ Start Nuage connection

    """

    # Getting user password for Nuage connection
    if nuage_password is None:
        import getpass
        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))

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

    # Connecting to Nuage
    try:
        session.start()
    except:
        logger.error(
            'Could not connect to Nuage host %s with user %s, enterprise %s and specified password'
            % (nuage_host, nuage_username, nuage_organization))
        raise

    return session
Example #4
0
def start_csproot_session():
    session = vspk.NUVSDSession(username='******',
                                password='******',
                                enterprise='csp',
                                api_url="https://portalproxy.lab.local")
    try:
        session.start()
    except:
        logging.error('Failed to start the session')
    return session.user
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__)

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

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

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

    except Exception, 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
Example #6
0
    def __init__(self, config):
        self.cfg = config
        self.logger = logging.getLogger('nuage-neutron-sync')

        auth = identity.Password(**self.cfg.get_keystone_creds())
        sess = session.Session(auth=auth)
        self.neutron = neutron_client.Client(session=sess)
        self.keystone = keystone_client.Client(session=sess)
        self.nova = nova_client.Client(2, session=sess)

        # Set up connection to the VSD
        vsd_session = vspk.NUVSDSession(**self.cfg.get_vsd_creds())
        vsd_session.start()
        self.vsd_user = vsd_session.user
Example #7
0
 def set_up_connections(self):
     auth = identity.Password(**self.cfg.get_keystone_creds())
     sess = session.Session(auth=auth)
     self.neutron = neutron_client.Client(session=sess)
     self.keystone = keystone_client.Client(session=sess)
     # Set up connection to the VSD
     vsd_session = vspk.NUVSDSession(**self.cfg.get_vsd_creds())
     vsd_session.start()
     self.vsd_user = vsd_session.user
     self.mysql_con = mdb.connect(
         self.cfg.get_value('db_neutron', 'db_hostname'),
         self.cfg.get_value('db_neutron', 'db_username'),
         self.cfg.get_value('db_neutron', 'db_password'),
         self.cfg.get_value('db_neutron', 'db_name'))
Example #8
0
    def login(self):
        self.logger.info('Connecting to Nuage server %s:%s with username %s' % (self.host, self.port,
                                                                                self.username))
        self.session = vsdk.NUVSDSession(username=self.username,
                                         password=self.password,
                                         enterprise=self.organization,
                                         api_url="https://%s:%s" % (self.host, self.port))

        # Connecting to Nuage
        try:
            self.session.start()
        except Exception as e:
            self.logger.error('Could not connect to Nuage host %s with user %s, enterprise %s and specified password' %
                              (self.host, self.username, self.password))
            raise
Example #9
0
def nuage_connect(nuage_username, nuage_password, nuage_enterprise, nuage_host,
                  nuage_port):
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    try:
        nc = None
        print '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://%s:%s" %
                               (nuage_host, nuage_port))
        nc.start()
        print '[CONNECTED]'
        return nc
    except:
        print '[ERROR: Could not connect]'
Example #10
0
 def connect_vspk(self):
     """
     Connects to a Nuage API endpoint
     """
     try:
         # Connecting to Nuage
         self.nuage_connection = vsdk.NUVSDSession(
             username=self.api_username,
             password=self.api_password,
             enterprise=self.api_enterprise,
             api_url=self.api_url)
         self.nuage_connection.start()
     except BambouHTTPError as e:
         self.module.fail_json(
             msg=
             'Unable to connect to the API URL with given username, password and enterprise: {0}'
             .format(e))
    def forceDeploy(self, gatewayName, gatewayID, event=None):
        n_gatewayName = gatewayName
        my_event = event

        self.LOG.info("Geting The Session")

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

        me = nuage_session.start().user

        gateway = me.gateways.get_first(
            filter='name == "{}"'.format(n_gatewayName))

        self.LOG.info('Got the Gateway: {}'.format(gateway.name))

        if gateway:
            self.LOG.info('Got the Gateway: {}'.format(gateway.name))

        RG = me.redundancy_groups.get()

        ##find if GW is part of RG
        for RG in RG:
            if (RG.gateway_peer1_name
                    == n_gatewayName) or (RG.gateway_peer2_name
                                          == n_gatewayName):
                self.LOG.info('Should Sync the RG: {}'.format(RG.name))
                gateway = RG

        job = vspk.NUJob(command='NETCONF_FORCE_DEPLOY')

        self.LOG.info('Starting {} job for the {} Gateway'.format(
            'NETCONF_FORCE_DEPLOY', gateway.name))

        gateway.create_child(job)
        self.is_job_ready(job, 600, gateway.name, my_event)
def main():
    """
    Manage the activation of a vSphere VM
    """
    # Handling arguments
    args = get_args()

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

    mode = args.mode

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

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

    if not log_level:
        log_level = 'ERROR'

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

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

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

    try:
        vc = None
        nc = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        clear()

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

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

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

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

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

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

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

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

    except vmodl.MethodFault, e:
        logging.critical('Caught vmodl fault: {0:s}'.format(e.msg))
        return 1
Example #13
0
        '--xlsx',
        help='create report in XLSX format, file name should be provided',
        action='append')
    parser.add_argument('--show',
                        help='show pretty text report in stdout',
                        action='store_true')
    args = parser.parse_args()

    # Disable exceptions related to incorrect SSL certificates
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    api_base = nu_build_api_url('https://' + args.v[0] + ':8443')
    # Prints current API URL
    main_logger.debug('Current API URL: ' + api_base)

    api_session = vspk.NUVSDSession(username=args.l[0],
                                    password=args.p[0],
                                    enterprise='csp',
                                    api_url='https://' + args.v[0] + ':8443')

    # Actively connecting to the VSD API
    main_logger.debug("Actively connecting to the VSD API")
    try:
        api_session.start()
    except bambou.exceptions.BambouHTTPError as err:
        response = err.connection.response
        if response.status_code == 409:
            # The entity probably already exists, so we just ignore this error:
            pass
        else:
            main_logger.error("Failed to start session! Exiting...")
            # re-raise the exception
            raise
Example #14
0
# -*- coding: utf-8 -*-
"""
A simple script that will print out a tree structure for each enterprise the user has access to.

--- Usage ---
python list_enterprises_domains_vms_structure_acls.py

--- Author ---
Philippe Dellaert <*****@*****.**>
"""
from vspk import v5_0 as vsdk

session = vsdk.NUVSDSession(username='******',
                            password='******',
                            enterprise='csp',
                            api_url='https://VSD-IP:8443')

session.start()

user = session.user

for cur_ent in user.enterprises.get():
    print('VMs inside Enterprise %s' % cur_ent.name)
    for cur_vm in cur_ent.vms.get():
        print('|- %s' % cur_vm.name)

    print('\nDomains inside Enterprise %s' % cur_ent.name)
    for cur_domain in cur_ent.domains.get():
        print('|- Domain: %s' % cur_domain.name)
        for cur_zone in cur_domain.zones.get():
            print('    |- Zone: %s' % cur_zone.name)
Example #15
0
def main():
    """
    Main function to handle statistics
    """

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

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

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

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

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

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

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

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

    logger.info('Deleted VM %s' % vmid)
    return 0
Example #16
0
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)

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

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

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

    except Exception, 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
def main(args):
    vsd_ip = str(args['--vsd'])
    api_url = "https://" + vsd_ip + ":8443"
    try:
        session = vsdk.NUVSDSession(username=username,
                                    password=password,
                                    enterprise=login_enterprise,
                                    api_url=api_url)
        session.start()
        csproot = session.user
    except:
        print("ERROR: Could not establish connection to VSD API")
        sys.exit(1)

    enterprise_name = str(args['--enterprise'])
    enterprise_filter_str = 'name == "' + enterprise_name + '"'
    enterprise = csproot.enterprises.get_first(filter=enterprise_filter_str)

    if enterprise == None:
        print("ERROR: Could not find enterprise with name " + enterprise_name)
        sys.exit(1)

    #Get NSG object based on Name
    nsg_name = str(args['--nsg-name'])
    nsg_filter_str = 'name == "' + nsg_name + '"'
    nsg = enterprise.ns_gateways.get_first(filter=nsg_filter_str)

    if nsg == None:
        print("ERROR: Could not find NSG with name " + nsg_name)
        sys.exit(1)

    if nsg.bootstrap_status == "ACTIVE" or nsg.bootstrap_status == "CERTIFICATE_SIGNED":
        print(
            "ERROR: NSG is already in a state where a URL can't be extracted")
        sys.exit(1)

    bootstraps = nsg.bootstraps.get()
    bootstrap = bootstraps[0]

    if bootstrap.installer_id == None:
        #print("Installer ID not defined ")
        existing_user = enterprise.users.get_first(filter="dummy")
        #print(str(existing_user.to_dict()))
        if existing_user == None:
            new_user = vsdk.NUUser(email="*****@*****.**",
                                   first_name="dummy",
                                   last_name="dummy",
                                   user_name="dummy",
                                   password="******",
                                   mobileNumber="+32444444444")
            enterprise.create_child(new_user)
            bootstrap.installer_id = new_user.id
            bootstrap.save()
        else:
            bootstrap.installer_id = existing_user.id
            bootstrap.save()

    #Starting the AMQP Client to capture the event
    t = threading.Thread(target=ampqWorker,
                         args=(
                             username,
                             password,
                             login_enterprise,
                             vsd_ip,
                         ))
    t.start()

    #Sleep 1s before triggering the NOTIFY event
    time.sleep(1)

    #Create job object to trigger notify_nsg_registration
    job = vsdk.NUJob(command="NOTIFY_NSG_REGISTRATION")
    #Trigger Job on NSG object
    nsg.create_child(job)
Example #18
0
def main():
    """
    Manage the vCenter Integration Node configuration
    """

    # Handling arguments
    args = get_args()
    all_clusters = args.all_clusters
    all_datacenters = args.all_datacenters
    all_hosts = args.all_hosts
    clusters = []
    if args.clusters:
        clusters = args.clusters
    debug = args.debug
    allow_fqdn = args.allow_fqdn
    datacenters = []
    if args.datacenters:
        datacenters = args.datacenters
    hosts = []
    if args.hosts:
        hosts = args.hosts
    host_configure_agent = args.host_configure_agent
    hosts_file = None
    if args.hosts_file:
        hosts_file = args.hosts_file
    hv_username = None
    if args.hv_username:
        hv_username = args.hv_username
    hv_password = None
    if args.hv_password:
        hv_password = args.hv_password
    hv_management_network = None
    if args.hv_management_network:
        hv_management_network = args.hv_management_network
    hv_data_network = None
    if args.hv_data_network:
        hv_data_network = args.hv_data_network
    hv_vm_network = None
    if args.hv_vm_network:
        hv_vm_network = args.hv_vm_network
    hv_mc_network = None
    if args.hv_mc_network:
        hv_mc_network = args.hv_mc_network
    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
    nuage_vrs_ovf = None
    if args.nuage_vrs_ovf:
        nuage_vrs_ovf = args.nuage_vrs_ovf
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    vcenter_host = args.vcenter_host
    vcenter_name = vcenter_host
    if args.vcenter_name:
        vcenter_name = args.vcenter_name
    vcenter_https_port = args.vcenter_https_port
    vcenter_http_port = args.vcenter_http_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__)

    # Input checking
    if not all_datacenters and len(datacenters) < 1:
        logger.critical('Not all datacenters have to be present in the Nuage Deployment tool (--all-datacenters option NOT enabled), but also no datacenters specified (at least one --datacenter)')
        return 1
    if not all_clusters and len(clusters) < 1:
        logger.critical('Not all clusters have to be present in the Nuage Deployment tool (--all-clusters option NOT enabled), but also no clusters specified (at least one --cluster)')
        return 1
    if not all_hosts and len(hosts) < 1 and not hosts_file:
        logger.critical('Not all hosts have to be present in the Nuage Deployment tool (--all-hosts option NOT enabled), but also no hosts specified (at least one --host or specify a file with the host information via --hosts-file)')
        return 1
    if all_datacenters and len(datacenters) > 0:
        logger.warning('You enabled all datacenters and added individual datacenter options, --all-datacenters takes precendence and overwrites the specified datacenters.')
        datacenters = []
    if all_clusters and len(clusters) > 0:
        logger.warning('You enabled all clusters and added individual cluster options, --all-clusters takes precendence and overwrites the specified clusters.')
        clusters = []
    if all_hosts and len(hosts) > 0 and not hosts_file:
        logger.warning('You enabled all hosts and added individual hosts options, --all-hosts takes precendence and overwrites the specified hosts.')
        hosts = []
    elif all_hosts and len(hosts) < 1 and hosts_file:
        logger.warning('You enabled all hosts and provided a hosts file, the hosts file takes precendence over the --all-hosts flag and this flag will be ignored.')
        all_hosts = False
    elif not all_hosts and len(hosts) > 0 and hosts_file:
        logger.warning('You specified host with the --host argument and provided a hosts file, the hosts file takes precendence over the --host paramerters and these will be ignored.')
        hosts = []

    # CSV Handling
    hosts_list = None
    if hosts_file:
        hosts_list = {}
        # CSV fields:
        # VM Name, Resource Pool, Folder, MAC Address, Post Script
        logger.debug('Parsing csv %s' % hosts_file)

        if not os.path.isfile(hosts_file):
            logger.critical('CSV file %s does not exist, exiting' % hosts_file)
            return 1

        with open(hosts_file, 'rb') as hostlist:
            hosts_list_raw = csv.reader(hostlist, delimiter=',', quotechar='"')
            for row in hosts_list_raw:
                logger.debug('Found CSV row: %s' % ','.join(row))
                # Adding IP to the hosts variable so it can also be used in further handling if it's a valid IP
                if allow_fqdn or ip_address_is_valid(row[0]):
                    hosts_list[row[0]] = row
                    hosts.append(row[0])
                else:
                    logger.warning('Found an invalid IP %s in the hosts file and FQDNs are not allowed, skipping line' % row[0])

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

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

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

    # Getting user password for hosts
    if hv_password is None:
        logger.debug('No command line Host password received, requesting Host password from user')
        hv_password = getpass.getpass(prompt='Enter password for the hosts inside vCenter %s for user %s: ' % (vcenter_host, hv_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, e:
            pass

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

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

        except IOError, e:
            pass
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__)

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

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host {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 ssl_context:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_https_port),
                                  sslContext=ssl_context)
            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, e:
        logger.critical('Caught vmodl fault: {0:s}'.format(e.msg))
        return 1
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__)

    # Disabling SSL verification if set
    #if configuration['nosslcheck']:
    #    logger.debug('Disabling SSL certificate verification.')
    #    requests.packages.urllib3.disable_warnings()

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

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

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

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

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

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

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

    try:
        vc = None
        nc = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        logger.info(
            'Succesfully attached VM %s to Nuage subnet %s, in mode %s' %
            (vcenter_vm, nuage_vm_subnet, mode))
Example #22
0
def main(args):
    date = datetime.datetime.now()
    logger = logging.getLogger('nuage-audit')
    logfile_name = 'nuage-audit-' + str(date.day) + '-' + str(
        date.month) + '-' + str(date.year)
    hdlr = logging.FileHandler(logfile_name)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    api_url = "https://" + str(args['--vsd']) + ":8443"
    try:
        session = vsdk.NUVSDSession(username='******',
                                    password='******',
                                    enterprise='csp',
                                    api_url=api_url)
        session.start()
        csproot = session.user
    except:
        print("ERROR: Could not establish connection to VSD API")
        sys.exit(1)

    enterprise_filter_str = 'name == "' + str(args['--enterprise']) + '"'
    enterprise = csproot.enterprises.get_first(filter=enterprise_filter_str)
    domains = enterprise.domains.get()

    logger.info('VSD-Audit is starting ...')
    print("--------------------------")
    print("Printing VSD Audit Summary")
    print("--------------------------")
    print("Enterprise Name: " + "\033[1m" + enterprise.name + "\033[0m")
    print("Number of L3 domains: " + "\033[1m" + str(len(domains)) + "\033[0m")
    print("L3 Domain details: ")
    logger.info(enterprise.to_dict())
    for domain in domains:
        logger.info(domain.to_dict())
        print("\t" + domain.name + " :")
        zones = domain.zones.get()
        for zone in zones:
            logger.info(zone.to_dict())
        subnets = domain.subnets.get()
        for subnet in subnets:
            logger.info(subnet.to_dict())
        vports = domain.vports.get()
        number_bridge_vports = 0
        number_host_vports = 0
        for vport in vports:
            logger.info(vport.to_dict())
            if vport.type == 'BRIDGE':
                number_bridge_vports += 1
            elif vport.type == 'HOST':
                number_host_vports += 1

        print("\t\t Zones: " + "\033[1m" + str(len(zones)) + "\033[0m")
        print("\t\t Subnets: " + "\033[1m" + str(len(subnets)) + "\033[0m")
        print("\t\t Number of vPorts: " + "\033[1m" + str(len(vports)) +
              "\033[0m" + " (Type Bridge: " + "\033[1m" +
              str(number_bridge_vports) + "\033[0m" + " Type Host: " +
              "\033[1m" + str(number_host_vports) + "\033[0m" + ")")
        print("\t\t Underlay Breakout settings: Underlay Enabled: " +
              "\033[1m" + domain.underlay_enabled + "\033[0m" +
              " PAT Enabled: " + "\033[1m" + domain.pat_enabled + "\033[0m")
        print("\t\t DPI Setting: " + "\033[1m" + domain.dpi + "\033[0m")

        ingress_acl_templates = domain.ingress_acl_templates.get()
        print("\t\t Ingress ACL Rules:")
        if len(ingress_acl_templates) == 0:
            print("\t\t\t \033[1m None Defined \033[0m")
        for ingress_acl_template in ingress_acl_templates:
            logger.info(ingress_acl_template.to_dict())
            print("\t\t\t Name: " + "\033[1m" + ingress_acl_template.name +
                  "\033[0m" + " Active: " + "\033[1m" +
                  str(ingress_acl_template.active) + "\033[0m" +
                  " Default Allow IP: " + "\033[1m" +
                  str(ingress_acl_template.default_allow_ip) + "\033[0m" +
                  " Default Allow Non IP: " + "\033[1m" +
                  str(ingress_acl_template.default_allow_non_ip) + "\033[0m" +
                  " Allow Address Spoofing: " + "\033[1m" +
                  str(ingress_acl_template.allow_address_spoof) + "\033[0m")
            ingress_acl_entry_templates = ingress_acl_template.ingress_acl_entry_templates.get(
            )
            for ingress_acl_entry_template in ingress_acl_entry_templates:
                logger.info(ingress_acl_entry_template.to_dict())
                if ingress_acl_entry_template.associated_l7_application_signature_id == None:
                    if ingress_acl_entry_template.protocol == 'ANY':
                        print("\t\t\t\t Priority: " + "\033[1m" +
                              str(ingress_acl_entry_template.priority) +
                              "\033[0m" + " Description: " + "\033[1m" +
                              str(ingress_acl_entry_template.description) +
                              "\033[0m" + " Source: " + "\033[1m" +
                              str(ingress_acl_entry_template.network_type) +
                              "\033[0m" + " Destination: " + "\033[1m" +
                              str(ingress_acl_entry_template.location_type) +
                              "\033[0m" + " Protocol: " + "\033[1m" +
                              str(ingress_acl_entry_template.protocol) +
                              "\033[0m")
                        print("\t\t\t\t Action: " + "\033[1m" +
                              str(ingress_acl_entry_template.action) +
                              "\033[0m")
                        print("\t\t\t\t Stateful: " + "\033[1m" +
                              str(ingress_acl_entry_template.stateful) +
                              "\033[0m" + " Stats Logging Enabled: " +
                              "\033[1m" + str(ingress_acl_entry_template.
                                              stats_logging_enabled) +
                              "\033[0m" + " Flow Logging Enabled: " +
                              "\033[1m" + str(ingress_acl_entry_template.
                                              flow_logging_enabled) +
                              "\033[0m" + "\n")
                    else:
                        print("\t\t\t\t Priority: " + "\033[1m" +
                              str(ingress_acl_entry_template.priority) +
                              "\033[0m" + " Description: " + "\033[1m" +
                              str(ingress_acl_entry_template.description) +
                              "\033[0m" + " Source: " + "\033[1m" +
                              str(ingress_acl_entry_template.network_type) +
                              "\033[0m" + " Destination: " + "\033[1m" +
                              str(ingress_acl_entry_template.location_type) +
                              "\033[0m" + " Protocol: " + "\033[1m" +
                              str(ingress_acl_entry_template.protocol) +
                              "\033[0m")
                        print("\t\t\t\t Source Port: " + "\033[1m" +
                              str(ingress_acl_entry_template.source_port) +
                              "\033[0m" + " Destination Port: " + "\033[1m" +
                              ingress_acl_entry_template.destination_port +
                              "\033[0m" + " Action: " + "\033[1m" +
                              str(ingress_acl_entry_template.action) +
                              "\033[0m")
                        print("\t\t\t\t Stateful: " + "\033[1m" +
                              str(ingress_acl_entry_template.stateful) +
                              "\033[0m" + " Stats Logging Enabled: " +
                              "\033[1m" + str(ingress_acl_entry_template.
                                              stats_logging_enabled) +
                              "\033[0m" + " Flow Logging Enabled: " +
                              "\033[1m" + str(ingress_acl_entry_template.
                                              flow_logging_enabled) +
                              "\033[0m" + "\n")

        egress_acl_templates = domain.egress_acl_templates.get()
        print("\t\t Egress ACL Rules:")
        if len(egress_acl_templates) == 0:
            print("\t\t\t \033[1m None Defined \033[0m")
        for egress_acl_template in egress_acl_templates:
            logger.info(egress_acl_template.to_dict())
            print("\t\t\t Name: " + "\033[1m" + egress_acl_template.name +
                  "\033[0m" + " Active: " + "\033[1m" +
                  str(egress_acl_template.active) + "\033[0m" +
                  " Default Allow IP: " + "\033[1m" +
                  str(egress_acl_template.default_allow_ip) + "\033[0m" +
                  " Default Allow Non IP: " + "\033[1m" +
                  str(egress_acl_template.default_allow_non_ip) + "\033[0m" +
                  " Install ACL Implicit Rules: " + "\033[1m" +
                  str(egress_acl_template.default_install_acl_implicit_rules) +
                  "\033[0m")

    print("Infrastructure Details: ")
    ns_gateways = enterprise.ns_gateways.get()

    number_nsg_active = 0
    number_nsg = 0
    number_nsgbr = 0
    number_nsgubr = 0
    number_nsg_single_uplink = 0
    number_nsg_dual_uplink = 0
    number_pppoe = 0
    number_static = 0
    number_dynamic = 0
    number_lte = 0
    number_uplinks_nat_probes = 0
    number_uplinks_ubr_only = 0
    number_ike_tunnels = 0
    number_uplinks_bgp = 0
    number_uplinks_patpool = 0
    number_egressqos = 0

    for ns_gateway in ns_gateways:
        logger.info(ns_gateway.to_dict())
        if ns_gateway.bootstrap_status == 'ACTIVE':
            number_nsg_active += 1
        if ns_gateway.personality == 'NSG':
            number_nsg += 1
            if isSingleUplink(ns_gateway):
                number_nsg_single_uplink += 1
            else:
                number_nsg_dual_uplink += 1

            number_pppoe += getPPPoE(ns_gateway)
            number_static += getStatic(ns_gateway)
            number_dynamic += getDynamic(ns_gateway)
            number_lte += getLTE(ns_gateway)
            number_uplinks_patpool += getPATNAT(ns_gateway)

            ns_ports = ns_gateway.ns_ports.get()

            for ns_port in ns_ports:
                logger.info(ns_port.to_dict())
                number_egressqos += getEgressQoS(ns_port)
                number_uplinks_bgp += getBGP(ns_port)
                number_uplinks_nat_probes += getNATflag(ns_port)
                number_uplinks_ubr_only += getUBRflag(ns_port)
                number_ike_tunnels += getIKE(ns_port)

        elif ns_gateway.personality == 'NSGBR':
            number_nsgbr += 1
        elif ns_gateway.personality == 'NSGDUC':
            number_nsgubr += 1

    ## Printing output of NSG data collection
    print("\tNumber of Network Services Gateways configured: " + "\033[1m" +
          str(len(ns_gateways)) + "\033[0m" + " (Status Active: " + "\033[1m" +
          str(number_nsg_active) + "\033[0m" + " Other: " + "\033[1m" +
          str(len(ns_gateways) - number_nsg_active) + "\033[0m" + ")")
    print("\tPersonality distribution: NSG: " + "\033[1m" + str(number_nsg) +
          "\033[0m" + " NSG-BR: " + "\033[1m" + str(number_nsgbr) + "\033[0m" +
          " NSG-UBR: " + "\033[1m" + str(number_nsgubr) + "\033[0m")
    print(
        "\tSingle/Dual Uplink distribution (only including personality NSG): Single Uplink: "
        + "\033[1m" + str(number_nsg_single_uplink) + "\033[0m" +
        " Dual Uplink: " + "\033[1m" + str(number_nsg_dual_uplink) + "\033[0m")
    print(
        "\tUplink connection distribution (only including personality NSG): Dynamic: "
        + "\033[1m" + str(number_dynamic) + "\033[0m" + " Static: " +
        "\033[1m" + str(number_static) + "\033[0m" + " PPPoE: " + "\033[1m" +
        str(number_pppoe) + "\033[0m" + " LTE: " + "\033[1m" +
        str(number_lte) + "\033[0m")
    print("\tNumber of uplinks with NAT probes enabled: " + "\033[1m" +
          str(number_uplinks_nat_probes) + "\033[0m")
    print("\tNumber of uplinks with Traffic Through UBR Only flag enabled: " +
          "\033[1m" + str(number_uplinks_ubr_only) + "\033[0m")
    print("\tNumber of uplinks with an IKE tunnel configured: " + "\033[1m" +
          str(number_ike_tunnels) + "\033[0m")
    print("\tNumber of uplinks with BGP configured: " + "\033[1m" +
          str(number_uplinks_bgp) + "\033[0m")
    print("\tNumber of uplinks with a PAT Pool configured: " + "\033[1m" +
          str(number_uplinks_patpool) + "\033[0m")
    print("\tNumber of uplinks with Egress QoS Profile: " + "\033[1m" +
          str(number_egressqos) + "\033[0m")

    print("--------------------------\n")
Example #23
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

    # Disabling SSL verification if set
    ssl_context = None
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

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

    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, e:
        pass
Example #24
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__)

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

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

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

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        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, e:
            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 ssl_context:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port),
                                  sslContext=ssl_context)
            else:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port))
        except IOError, e:
            pass
Example #25
0
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__)

    # Disabling SSL verification if set
    if configuration['nosslcheck']:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # 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, 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
Example #26
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 Exception, 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]
    
            for cur_acl in cur_domain.ingress_acl_templates.get():
                print('    |- Ingress ACL: %s' % cur_acl.name)
                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='******',
Example #28
0
def main():
    """
    Main function to create Uplink subnet via REST API
    """

    # 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
    fip_net             = args.fip_net
    uplink_addr         = args.uplink_addr
    uplink_mask         = args.uplink_mask
    uplink_gw           = args.uplink_gw
    uplink_ip           = args.uplink_ip
    uplink_mac          = args.uplink_mac
    gw_name              = args.gw_name
    gw_port            = args.gw_port
    gw_vlan            = args.gw_vlan

    # 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

    nuage_user = nc.user


    # Getting the parentID of FIP subnet
    logger.debug('Getting FIP subnet parent ID')
    fip_obj = nuage_user.subnets.get_first(filter="address == '{0}'".format(fip_net))
   
    # Fail if FIP subnet object was not found
    if not fip_obj:
        logger.critical('FIP subnet {0} was not found'.format(fip_net))
        return 1

    shared_resource_id = fip_obj.parent_id
    logger.debug('FIP parent ID is: {0}'.format(shared_resource_id))


    # Locating a gateway port and creating a new VLAN
    logger.debug('Creating a new VLAN on Gateway port')
    new_vlan = vsdk.NUVLAN(value=gw_vlan)
    gw = nuage_user.gateways.get_first(filter="name == '{0}'".format(gw_name))

    # Fail if Gateway was not found
    if not gw:
        logger.critical('Gateway {0} was not found'.format(gw_name))
        return 1

    port = gw.ports.get_first(filter="name == '{0}'".format(gw_port))

    # Fail if Port requirements are not met
    if not port:
        logger.critical('Port {0} was not found on Gateway {1}'.format(gw_port, gw_name))
        return 1
    elif not port.port_type == 'ACCESS':
        logger.critical('Port {0} is not an ACCESS port type'.format(gw_port))
        return 1
    elif not int(gw_vlan) in range(*[int(x) for x in port.vlan_range.split('-')]):
        logger.critical('Vlan {0} is not part of the port vlan range: {1}'.format(gw_vlan, port.vlan_range))
        return 1
    elif port.vlans.get_first(filter="value == {0}".format(gw_vlan)):
        logger.critical('Vlan {0} already exists on port {1}'.format(gw_vlan, gw_port))
        return 1

    port.create_child(new_vlan)
    vlan_id = new_vlan.id
    logger.debug('New VLAN ID is: {0}'.format(vlan_id))


    # Constructing an Uplink Subnet object
    logger.debug('Creating an Uplink Subnet')
    shared_subnet = vsdk.NUSharedNetworkResource(name='uplink subnet {0}'.format(uplink_addr.replace('.','-')), \
        description='Uplink subnet to Gateway {0}'.format(gw_name.replace('.','-')), \
        address=uplink_addr, \
        netmask=uplink_mask, \
        gateway=uplink_gw, \
        type=UPLINK_TYPE, \
        uplink_interface_ip=uplink_ip, \
        uplink_interface_mac=uplink_mac, \
        uplink_gw_vlan_attachment_id=vlan_id, \
        shared_resource_parent_id=shared_resource_id, \
        uplink_vport_name = 'uplink vport {0} Vlan{1}'.format(gw_port, gw_vlan))

    # Creating a subnet on VSD
    nuage_user.create_child(shared_subnet)

    logger.info('Uplink Subnet is created')
    return 0
Example #29
0
def main():
    arg_spec = dict(nsgv_path=dict(required=False, type='str'),
                    skip_iso_create=dict(required=False, type='bool'),
                    fact_name=dict(required=False, type='str'),
                    vsd_license_file=dict(required=True, type='str'),
                    vsd_auth=dict(required=True, no_log=True, type='dict'),
                    zfb_constants=dict(required=True, type='dict'),
                    zfb_proxy_user=dict(required=True,
                                        no_log=True,
                                        type='dict'),
                    zfb_nsg=dict(required=True, type='dict'),
                    zfb_ports=dict(required=True, type='dict'),
                    zfb_nsg_infra=dict(required=True, type='dict'),
                    zfb_vsc_infra=dict(required=True, type='dict'))

    module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True)

    vsd_license_file = module.params['vsd_license_file']
    vsd_auth = module.params['vsd_auth']
    if "fact_name" in module.params:
        fact_name = module.params['fact_name']
    else:
        fact_name = "nsg_already_configured"

    # Get VSD license
    vsd_license = ""
    try:
        with open(vsd_license_file, 'r') as lf:
            vsd_license = lf.read()
    except Exception as e:
        module.fail_json(msg="ERROR: Failure reading file: %s" % e)
        return

    # Create a session as csp user
    try:
        session = VSPK.NUVSDSession(**vsd_auth)
        session.start()
        csproot = session.user
    except Exception as e:
        module.fail_json(
            msg="ERROR: Could not establish connection to VSD API "
            "using %s: %s" % (vsd_auth, str(e)))
        return

    nsg_already_configured = False

    # Create nsg templates and iso file
    if (not is_license_already_installed(csproot, vsd_license)):
        install_license(csproot, vsd_license)

    if has_nsg_configuration(module, csproot):
        nsg_already_configured = True

    create_proxy_user(module, session)

    nsg_infra = create_nsg_infra_profile(module, csproot)
    nsg_temp = create_nsg_gateway_template(module, csproot, nsg_infra)
    vsc_infra = create_vsc_infra_profile(module, csproot)
    create_nsgv_ports(module, nsg_temp, vsc_infra)
    metro_org = create_nsg_device(module, csproot, nsg_temp)

    if ("skip_iso_create" not in module.params
            or module.params["skip_iso_create"] is not True):
        create_iso_file(module, metro_org, nsg_temp)

    module.exit_json(changed=True,
                     ansible_facts={fact_name: nsg_already_configured})
Example #30
0
def main():
    """
    Main function to handle statistics
    """

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    logger.info('Created all necessary entities in the appropriate subnets or L2 domains for VM %s' % name)
    return 0