def enterprises_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, callback=None, **kwargs): group_by = [] if group_by is None else group_by if 'unknown' in filter: return [] result = [vsdk.NUEnterprise(id='enterprise-id', name='test-enterprise')] if filter == '' or filter == 'name == "test%"': result.append(vsdk.NUEnterprise(id='enterprise-id-2', name='test-enterprise-2')) return result
def create_enterprise(csproot, name): enterprise = csproot.enterprises.get_first("name is '%s'" % name) if enterprise is None: enterprise = VSPK.NUEnterprise(name=name) csproot.create_child(enterprise) return enterprise
def main(): # Handling arguments args = get_args() debug = args.debug verbose = args.verbose log_file = args.logfile nuage_organization = args.nuage_organization nuage_host = args.nuage_host nuage_port = args.nuage_port nuage_password = args.nuage_password nuage_username = args.nuage_username nuage_myEnterprise = args.nuage_myEnterprise MyCmsName = 'CMS-scripts' MyDescription = "plateforme " + nuage_myEnterprise """ # Bouchonnage arguments debug = False verbose = False log_file = 'Nuage-log.txt' nuage_organization = 'TEST' nuage_host = '127.1.1.2' nuage_port = '8443' nuage_password = '******' nuage_username = '******' nuage_myEnterprise = 'TEST' nuage_myDomainTemplate = 'L3_PXY-RBD_FRT' nuage_myDomain = 'myTestDomain' nuage_myDomainDesc = 'DMZ TEST' """ # Logging settings logger = setup_logging(debug, verbose, log_file) # Getting user password for Nuage connection if nuage_password is None: logger.debug( 'No command line Nuage password received, requesting Nuage password from user' ) nuage_password = getpass.getpass( prompt='Enter password for Nuage host %s for user %s: ' % (nuage_host, nuage_username)) # Connection to VSD nc = start_nuage_connection(nuage_host, nuage_port, nuage_username, nuage_password, nuage_organization, logger) # Execute action myEnterprise = vsdk.NUEnterprise(name=nuage_myEnterprise, description=MyDescription, external_id=MyCmsName) nc.create_child(myEnterprise, async=True, callback=mycallback) logger.warning('Entreprise %s is created' % (myEnterprise.name))
def create_proxy_user(module, session): zfb_proxy_user = module.params['zfb_proxy_user'] zfb_constants = module.params['zfb_constants'] # Create proxy user if not present cspenterprise = VSPK.NUEnterprise() cspenterprise.id = session.me.enterprise_id csp_users = cspenterprise.users.get() lst_users = [usr.user_name for usr in csp_users] if zfb_constants['proxy_user'] not in lst_users: proxy_user = VSPK.NUUser(first_name=zfb_proxy_user['firstName'], last_name=zfb_proxy_user['lastName'], user_name=zfb_constants['proxy_user'], email=zfb_proxy_user['email'], password=zfb_proxy_user['password']) cspenterprise.create_child(proxy_user) csprootuser = VSPK.NUUser(id=session.me.id) csprootuser.fetch() # Add proxy user to root group csprootgroup = cspenterprise.groups.get_first(filter="name ==\ 'Root Group'") csprootgroup.assign([proxy_user, csprootuser], VSPK.NUUser)
logger.critical('Caught exception: %s' % str(e)) return 1 # Finding domain logger.debug('Finding domain %s' % configuration['nuage_domain']) nc_domain = nc.user.domains.get_first(filter="name == '%s'" % configuration['nuage_domain']) if nc_domain is None: logger.critical('Unable to find domain %s, quiting' % configuration['nuage_domain']) return 1 logger.info('Found domain %s' % nc_domain.name) # Getting enterprise logger.debug('Getting enterprise for domain %s' % nc_domain.name) nc_enterprise = vsdk.NUEnterprise(id=nc_domain.parent_id) nc_enterprise.fetch() if configuration['acl_type'] == 'SUBNET' or configuration[ 'acl_type'] == 'ZONE': # Mapping subnets logger.debug('Mapping subnets for domain %s' % nc_domain.name) for nc_subnet in nc_domain.subnets.get(): logger.debug( 'Found subnet with network %s/%s in domain %s' % (nc_subnet.address, nc_subnet.netmask, nc_domain.name)) nc_subnetmap[nc_subnet.id] = { 'id': nc_subnet.id, 'address': nc_subnet.address, 'netmask': nc_subnet.netmask, 'zone': nc_subnet.parent_id
api_url="https://portalproxy.lab.local") try: session.start() except: logging.error('Failed to start the session') return session.user # we assume we have the setup_logging() and start_csproot_session() methods # showed in the previous example from vspk import v5_0 as vspk setup_logging() csproot = start_csproot_session() # Create a new enterprise object. The only mandatory parameter is the name, # so we give it directly to the contructor new_enterprise = vspk.NUEnterprise(name="new-corp8") # Create the enterprise on VSD. csproot.create_child(new_enterprise) # Create a new domain object. new_domain = vspk.NUDomain() # The attributes can also be set on the object directly new_domain.name = "new-dom" #new_domain.template_id = "98088286-9bc5-4898-b5e5-ea7e8d99ff98" # Create the domain on VSD. new_enterprise.create_child(new_domain)
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))
from vspk import v5_0 as vspk def setup_logging(): import logging from vspk.utils import set_log_level set_log_level(logging.DEBUG, logging.StreamHandler()) 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 setup_logging() csproot = start_csproot_session() # Create an enterprise asynchronously enterprise = vspk.NUEnterprise(name="Test Enterprise") csproot.create_child(enterprise)
def create_vsd_managed_tenant(self, tenant_name): self.logger.info("Creating VSD Managed Tenant: {0}".format(tenant_name)) # Check if Nuage enterprise already exists enterprise = self.vsd_user.enterprises.get_first(filter='name==\"{0}\"'.format(tenant_name)) if enterprise is not None: self.logger.info("Enterprise {0} already exist".format(tenant_name)) # Check if project already exists try: project = self.keystone.projects.find(name="{0}".format(tenant_name)) except keystone_NotFound: project = None else: self.logger.warn("OpenStack project {0} already exist ".format(tenant_name)) if enterprise is not None or project is not None: var = raw_input("Either the Nuage enterprise or OpenStack project already exist. " "Do you want to continue and use these Enterprise/project? (y/n)") if var != "y": return # Create project if project is None: self.logger.info("Creating Keystone Tenant: {0}".format(tenant_name)) project = self.keystone.projects.create(name="{0}".format(tenant_name), domain=self.cfg.get_value("openstack", "project_domain_id"), description="VSD Managed Openstack Tenant", enabled=True) # get admin role try: admin_role = self.keystone.roles.find(name='admin') except Exception as e: self.logger.error("Cannot find admin role in keystone") self.logger.error(repr(e)) return # get admin user try: os_admin = self.keystone.users.find(name=self.cfg.get_value('openstack', 'admin_username')) except Exception as e: self.logger.error("Cannot find user {0} in keystone". format(self.cfg.get_value('openstack', 'admin_username'))) self.logger.error(repr(e)) return # add admin role for admin user to project try: self.logger.info("Adding admin role for user {0} in tenant {1} in keystone".format( self.cfg.get_value('openstack', 'admin_username'), tenant_name)) # will not throw an error if the role was already added self.keystone.roles.grant(role=admin_role, user=os_admin, project=project) except Exception as e: self.logger.error("Cannot add admin role for user {0} in tenant {1} in keystone".format( self.cfg.get_value('openstack', 'admin_username'), tenant_name)) self.logger.error(repr(e)) return # Create the netpartition # TODO: What if netpartition already exist in the neutron database, but the Enterprise does not exist try: self.logger.info("Creating Net-Partition: {0}".format(tenant_name)) body_netpart = { "net_partition": { "name": tenant_name } } self.neutron.create_net_partition(body=body_netpart) except neutron_NotFound: self.logger.info("Cannot create netpartition: {0}. Ignore this message if you are using the ML2 plugin. " "Creating VSD enterprise....".format(tenant_name)) # If this is the case, manually create the enterprise if enterprise is None: ent = vspk.NUEnterprise(name=tenant_name) self.vsd_user.create_child(ent) except Exception as e: self.logger.warn("Cannot create netpartition: {0}. ".format(tenant_name)) self.logger.error(repr(e)) self.logger.info("Finished Creating VSD Managed Tenant: {0}".format(tenant_name))
def enterprises_get_first(self, filter=None, order_by=None, group_by=None, query_parameters=None, commit=False, callback=None, **kwargs): group_by = [] if group_by is None else group_by if filter == 'name == "test-enterprise-create"' or 'unknown' in filter: return None return vsdk.NUEnterprise(id='enterprise-id', name='test-enterprise')