예제 #1
0
 def __init__(self):
     username = User_Name
     password = Password
     tenant_name = Tenant
     project_name = Project_Name
     project_domain_id = User_Domain_ID
     user_domain_id = User_Domain_ID
     keystone_version = Keysstone_Version
     if keystone_version == 'v3':
         auth_url = 'http://' + Host_IP + ':5000/v3'
         VERSION = '2'
         auth = identity.Password(auth_url=auth_url,
                                  username=username,
                                  password=password,
                                  project_name=project_name,
                                  project_domain_id=project_domain_id,
                                  user_domain_id=user_domain_id)
         sess = session.Session(auth=auth)
         self.neutron = client.Client(session=sess)
         self.nova_client = Client(VERSION, session=sess)
     else:
         auth_url = 'http://' + Host_IP + ':5000/v2.0'
         VERSION = '2'
         auth = identity.Password(auth_url=auth_url,
                                  tenant_name=tenant_name,
                                  username=username,
                                  password=password)
         sess = session.Session(auth=auth)
         self.neutron = client.Client(session=sess)
         self.nova_client = Client(VERSION, session=sess)
예제 #2
0
 def discover(self, region):
     issues = []
     auth = identity.Password(**region["credentials"])
     sess_kwargs = {"auth": auth}
     insecure = region.get("insecure")
     if insecure:
         sess_kwargs["verify"] = False
     else:
         cacert = region.get("cacert")
         if cacert:
             sess_kwargs["verify"] = cacert
     sess = session.Session(**sess_kwargs)
     neutron = client.Client(session=sess)
     for sg in neutron.list_security_groups()["security_groups"]:
         LOG.debug("Checking security group %s", sg["name"])
         for rule in sg["security_group_rules"]:
             fmt = ("Rule %(direction)s [%(ethertype)s/%(protocol)s] "
                    "%(remote_ip_prefix)s "
                    "%(port_range_min)s:%(port_range_max)s")
             LOG.debug(fmt, rule)
             for pattern in UNSAFE_RULES:
                 if match_rule(pattern, rule):
                     LOG.info("Unsafe rule found")
                     issue = base.Issue(rule["id"], "SecurityGroupTooOpen",
                                        region["name"],
                                        "Security group too open",
                                        tenant_id=rule["tenant_id"])
                     issues.append(issue)
     return issues
예제 #3
0
    def __init__(
        self,
        auth_url,
        username,
        password,
        project_name,
        project_domain_id,
        user_domain_id
    ):
        self._auth_url = auth_url
        self._username = username
        self._password = password
        self._project_name = project_name
        self._project_domain_id = project_domain_id
        self._user_domain_id = user_domain_id

        self.auth = identity.Password(
            auth_url=self._auth_url,
            username=self._username,
            password=self._password,
            project_name=self._project_name,
            project_domain_id=self._project_domain_id,
            user_domain_id=self._user_domain_id
        )
        self.sess = session.Session(auth=self.auth)
        self.nova = client.Client(
            DEFAULT_NOVA_CLIENT_VERSION,
            session=self.sess
        )
예제 #4
0
def list_ips():
    user = User.query.get_or_404(current_user.id)
    provider = Provider.query.get_or_404("1")
    auth = identity.Password(auth_url=provider.url,
                             username=user.username,
                             password=user.provider_password,
                             project_name=user.username,
                             project_domain_name='Default',
                             user_domain_name='Default')
    sess = session.Session(auth=auth)
    neutron = client.Client(session=sess)
    nova = client_nova.Client('2', session=sess)
    networks = neutron.list_networks()
    subnets = neutron.list_subnets()
    routers = neutron.list_routers()
    floatingips = neutron.list_floatingips()
    ports = neutron.list_ports()
    return render_template('network/list_ips.html',
                           title="List Networks",
                           block_description="manage all of your networks",
                           user=user,
                           provider=provider,
                           neutron=neutron,
                           nova=nova,
                           networks=networks,
                           subnets=subnets,
                           routers=routers,
                           floatingips=floatingips,
                           ports=ports,
                           sess=sess)
예제 #5
0
def novaclient(context, privileged_user=False, timeout=None, api_version=None):
    """Returns a Nova client

    @param privileged_user:
        If True, use the account from configuration
        (requires 'auth_type' and the other usual Keystone authentication
        options to be set in the [nova] section)
    @param timeout:
        Number of seconds to wait for an answer before raising a
        Timeout exception (None to disable)
    @param api_version:
        api version of nova
    """

    if privileged_user and CONF[NOVA_GROUP].auth_type:
        LOG.debug('Creating Keystone auth plugin from conf')
        n_auth = ks_loading.load_auth_from_conf_options(CONF, NOVA_GROUP)
    elif privileged_user and CONF.os_privileged_user_name:
        # Fall back to the deprecated os_privileged_xxx settings.
        # TODO(gyurco): Remove it after Pike.
        if CONF.os_privileged_user_auth_url:
            url = CONF.os_privileged_user_auth_url
        else:
            url = _get_identity_endpoint_from_sc(context)
        LOG.debug(
            'Creating Keystone password plugin from legacy settings '
            'using URL: %s', url)
        n_auth = identity.Password(auth_url=url,
                                   username=CONF.os_privileged_user_name,
                                   password=CONF.os_privileged_user_password,
                                   project_name=CONF.os_privileged_user_tenant,
                                   project_domain_id=context.project_domain,
                                   user_domain_id=context.user_domain)
    else:
        if CONF[NOVA_GROUP].token_auth_url:
            url = CONF[NOVA_GROUP].token_auth_url
        else:
            url = _get_identity_endpoint_from_sc(context)
        LOG.debug('Creating Keystone token plugin using URL: %s', url)
        n_auth = identity.Token(auth_url=url,
                                token=context.auth_token,
                                project_name=context.project_name,
                                project_domain_id=context.project_domain)

    keystone_session = ks_loading.load_session_from_conf_options(CONF,
                                                                 NOVA_GROUP,
                                                                 auth=n_auth)

    c = nova_client.Client(api_versions.APIVersion(api_version
                                                   or NOVA_API_VERSION),
                           session=keystone_session,
                           insecure=CONF[NOVA_GROUP].insecure,
                           timeout=timeout,
                           region_name=CONF[NOVA_GROUP].region_name,
                           endpoint_type=CONF[NOVA_GROUP].interface,
                           cacert=CONF[NOVA_GROUP].cafile,
                           global_request_id=context.global_id,
                           extensions=nova_extensions)

    return c
    def probe(self):
        try:
            auth = identity.Password(
                username=self.openstack['username'],
                password=self.openstack['password'],
                project_name=self.openstack['project_name'],
                user_domain_name=self.openstack['user_domain_name'],
                project_domain_name=self.openstack['project_domain_name'],
                auth_url=self.openstack['auth_url'])
            sess = session.Session(auth=auth)
        except Exception as e:
            self.exit_error('cannot get token ' + str(e))

        try:
            neutron = client.Client(session=sess)
        except Exception as e:
            self.exit_error('cannot load ' + str(e))

        try:
            result = neutron.show_network_ip_availability(self.network_uuid)
        except Exception as e:
            self.exit_error(str(e))

        net_ip = result['network_ip_availability']

        stati = dict(total=0, used=0)
        stati['total'] = net_ip['total_ips']
        stati['used'] = net_ip['used_ips']

        for r in stati.keys():
            yield osnag.Metric(r, stati[r], min=0)
예제 #7
0
    def __init__(self,
                 controllerIp,
                 cntrlr_uname='heat-admin',
                 cntrlr_passwd='noir0123',
                 keystone_user='******',
                 keystone_password='******',
                 tenant='admin'):
        self.cntrlrip = controllerIp
        self.username = cntrlr_uname
        self.password = cntrlr_passwd
        self.cred = {}
        self.cred['version'] = '2'
        self.cred['username'] = keystone_user
        self.cred['password'] = keystone_password
        self.cred['project_name'] = tenant
        self.cred['auth_url'] = "http://%s:5000/v2.0/" % self.cntrlrip
        self.cred['auth_url'] = "http://%s:5000/v3/" % self.cntrlrip
        auth = identity.Password(auth_url=self.cred['auth_url'],
                                 username='******',
                                 password=self.cred['password'],
                                 project_name=self.cred['project_name'],
                                 project_domain_name='Default',
                                 user_domain_name='Default')
        sess = session.Session(auth=auth)

        self.nova = Client("2", session=sess)
        self.err_strings = [
            'Unable', 'Conflict', 'Bad Request', 'Error', 'Unknown',
            'Exception'
        ]
예제 #8
0
    def server_action(self, provider, server_name, action):
        """ Performs server actions using a nova client. """
        try:
            message = "Action %s performed on %s successfuly. " % (action,
                                                                   server_name)
            provider_url = 'http://' + provider['provider_ip'] + '/v2.0'
            auth = identity.Password(auth_url=provider_url,
                                     username=provider['username'],
                                     password=provider['password'],
                                     project_name=provider['tenant'])
            sess = session.Session(auth=auth, verify=False)
            nova = client.Client(2, session=sess)
            #            nova = client.Client('2', provider['username'], provider['password'], provider['tenant'], provider_url)
            servers = nova.servers.list()
            server = [x for x in servers if x.name == server_name][0]
        except Exception as e:
            import traceback
            traceback.print_exc()

            raise Exception('Could not get server' + server_name + '. ' +
                            e.message)
        try:
            success = getattr(server, action)()
        except Exception as e:
            import traceback
            traceback.print_exc()

            raise Exception('Action ' + action + ' was not performed on ' +
                            server_name + '. Reason: ' + e.message)

        raise tornado.gen.Return({
            'success': True,
            'message': message,
            'data': {}
        })
예제 #9
0
def get_manila_client_from_env():
    # We should catch KeyError exception with the purpose of
    # source or configure openrc file.
    auth_url = os.environ['OS_AUTH_URL']
    username = os.environ['OS_USERNAME']
    password = os.environ['OS_PASSWORD']
    project_name = os.environ['OS_PROJECT_NAME']

    # Either project(user)_domain_name or project(user)_domain_id
    # would be acceptable.
    project_domain_name = os.environ.get("OS_PROJECT_DOMAIN_NAME")
    project_domain_id = os.environ.get("OS_PROJECT_DOMAIN_ID")
    user_domain_name = os.environ.get("OS_USER_DOMAIN_NAME")
    user_domain_id = os.environ.get("OS_USER_DOMAIN_ID")

    auth = identity.Password(auth_url=auth_url,
                             username=username,
                             password=password,
                             project_name=project_name,
                             project_domain_id=project_domain_id,
                             project_domain_name=project_domain_name,
                             user_domain_id=user_domain_id,
                             user_domain_name=user_domain_name)
    session = ks.Session(auth=auth)
    return manila_client.Client(session=session, client_version='2')
예제 #10
0
def register(datasource):
    """Register tables in datasource

    It registers table that can be retrieved either from the OpenStack client
    or the Neutron client (firewall mainly)

    :param datasource: The datasource object to enrich.
    """
    openstack_conf = cfg.CONF.openstack
    if not openstack_conf.enabled:
        return
    if datasource.use_cache():
        openstack_cnx = None
        neutron_cnx = None
    else:
        password = openstack_conf.password
        if password == "":
            password = getpass.getpass()
        auth_args = {
            'auth_url': openstack_conf.www_authenticate_uri,
            'project_name': openstack_conf.project_name,
            'username': openstack_conf.user_name,
            'password': password,
            'user_domain_name': openstack_conf.user_domain_name,
            'project_domain_name': openstack_conf.project_domain_name,
        }
        if not openstack_conf.verify:
            urllib3.disable_warnings()
        auth = identity.Password(**auth_args)
        sess = session.Session(auth=auth, verify=openstack_conf.verify)
        openstack_cnx = connection.Connection(session=sess,
                                              identity_api_version='3')
        neutron_cnx = neutronclient.Client(session=sess)
    datasource.register(neutron_cnx, NEUTRON_TABLES)
    datasource.register(openstack_cnx, OPENSTACK_TABLES)
예제 #11
0
    def __init__(self):
        self.db = sqlite3.connect(':memory:')
        self.cur = self.db.cursor()
        self.init_db()
        self.user = CONF.CREDENTIALS.username
        self.pwd = CONF.CREDENTIALS.password
        self.url = CONF.CREDENTIALS.url
        self.tenant = CONF.CREDENTIALS.tenant
        self.novc = novaclient.Client(2,
                                      self.user,
                                      self.pwd,
                                      self.tenant,
                                      auth_url=self.url)
        self.cinc = cinderclient.Client('2',
                                        self.user,
                                        self.pwd,
                                        self.tenant,
                                        auth_url=self.url)

        self.auth = identity.Password(auth_url=self.url,
                                      username=self.user,
                                      password=self.pwd,
                                      project_name=self.tenant)
        self.sess = session.Session(auth=self.auth)
        self.neuc = neutronclient.Client(session=self.sess)
        self.keystone = idclient.Client(session=self.sess)
예제 #12
0
def _get_keystone_auth(trust_id=None):
    if not cfg.CONF[CFG_KEYSTONE_GROUP].auth_type:
        # Fallback to legacy v2 options if no auth_type is set.
        # If auth_type is set, it is possible to use the auth loader
        # from keystoneauth1. This is the same fallback as keystonemiddleware
        # uses.
        kwargs = {
            'auth_url':
            cfg.CONF[CFG_KEYSTONE_GROUP].auth_uri.replace('v2.0', 'v3'),
            'username': cfg.CONF[CFG_KEYSTONE_GROUP].admin_user,
            'password': cfg.CONF[CFG_KEYSTONE_GROUP].admin_password,
            'user_domain_name': "Default"
        }
        if not trust_id:
            kwargs['project_name'] = \
                cfg.CONF[CFG_KEYSTONE_GROUP].admin_tenant_name
            kwargs['project_domain_name'] = "Default"
        else:
            kwargs['trust_id'] = trust_id
        auth = identity.Password(**kwargs)
    else:
        kwargs = {}
        if trust_id:
            # Remove project_name and project_id, since we need a trust scoped
            # auth object
            kwargs['project_name'] = None
            kwargs['project_domain_name'] = None
            kwargs['project_id'] = None
            kwargs['trust_id'] = trust_id
        auth = ka_loading.load_auth_from_conf_options(cfg.CONF,
                                                      CFG_KEYSTONE_GROUP,
                                                      **kwargs)
    return auth
예제 #13
0
def create_network(args, name, subnetname, cidr):
    '''buat network'''
    '''namanetwork namasubnet networkaddress'''
    #  network_name = 'int_network1'
    ui.info_section(f'== Create Network {name}== \n')
    auth = identity.Password(auth_url=auth_url,
                             username=username,
                             password=password,
                             project_name=project_name,
                             project_domain_name=project_domain_name,
                             user_domain_name=user_domain_name)
    sess = session.Session(auth=auth)
    neutron = nwclient.Client(session=sess)
    try:
        body_sample = {'network': {'name': name,
                                   'admin_state_up': True}}

        netw = neutron.create_network(body=body_sample)
        net_dict = netw['network']
        network_id = net_dict['id']
        ui.info_3('Network %s created' % network_id, ui.check)

        body_create_subnet = {'subnets':
                              [{'cidr': cidr, 'name': subnetname,
                                'ip_version': 4, 'network_id': network_id}]}

        subnet = neutron.create_subnet(body=body_create_subnet)
        ui.info_3('Created subnet %s' % subnet, ui.check)
    finally:
        ui.info_3("Execution completed", ui.check)
    def probe(self):
        try:
            auth = identity.Password(username    = self.openstack['username'],
                                    password    = self.openstack['password'],
                                    project_name=self.openstack['project_name'],
                                    user_domain_name=self.openstack['user_domain_name'],
                                    project_domain_name=self.openstack['project_domain_name'],
                                    auth_url=self.openstack['auth_url'])
            sess = session.Session(auth=auth)
        except Exception as e:
            self.exit_error('cannot get token ' + str(e))
         
        try:
            neutron = client.Client(session=sess)
        except Exception as e:
           self.exit_error('cannot load ' + str(e))

        try:
           result=neutron.list_floatingips()
        except Exception as e:
           self.exit_error(str(e))

        stati=dict(assigned=0, used=0)

        for floatingip in result['floatingips']:
           stati['assigned'] += 1
           if floatingip['fixed_ip_address']:
             stati['used'] += 1

        for r in stati.keys():
           yield osnag.Metric(r, stati[r], min=0)
예제 #15
0
def list_networks(args, nama=None):
    '''List Network'''
    auth = identity.Password(auth_url=auth_url,
                             username=username,
                             password=password,
                             project_name=project_name,
                             project_domain_name=project_domain_name,
                             user_domain_name=user_domain_name)
    sess = session.Session(auth=auth)
    neutron = nwclient.Client(session=sess)
    if nama is None:
        '''JIka nama tidak dimasukkan'''
        ui.info_section(f'== List Network == \n')
        list = neutron.list_networks()
        for list in neutron.list_networks()['networks']:
            print(list['name'])
        # coba = json.dumps(list, sort_keys=True, indent=2)
        # print(coba)
    else:
        '''menampilkan satu list nama'''
        try:
            ui.info_section(f'== Detail Network {nama}== \n')
            neutron = nwclient.Client(session=sess)
            list = neutron.list_networks(name=nama)

            coba = json.dumps(list, sort_keys=True, indent=2)
            print(coba)
        except Exception as e:
            '''jika tidak ada nama'''
            ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
예제 #16
0
    def __init__(self, auth_url, username, password, project_name,
                 project_domain_id, user_domain_id, region_name, ssl_verify,
                 http_timeout):
        self._auth_url = auth_url
        self._username = username
        self._password = password
        self._project_name = project_name
        self._project_domain_id = project_domain_id
        self._user_domain_id = user_domain_id
        self._region_name = region_name
        self._ssl_verify = ssl_verify

        self.auth = identity.Password(
            auth_url=self._auth_url,
            username=self._username,
            password=self._password,
            project_name=self._project_name,
            project_domain_id=self._project_domain_id,
            user_domain_id=self._user_domain_id)
        self.sess = session.Session(auth=self.auth,
                                    verify=self._ssl_verify,
                                    timeout=http_timeout)
        self.cinder = client.Client(DEFAULT_CINDER_CLIENT_VERSION,
                                    session=self.sess,
                                    region_name=self._region_name)
예제 #17
0
def _get_auth_handler(kwargs):
    if 'token' in kwargs:
        auth = identity.Token(
            auth_url=kwargs.get('auth_url', None),
            token=kwargs.get('token', None),
            project_id=kwargs.get('project_id', None),
            project_name=kwargs.get('project_name', None),
            project_domain_id=kwargs.get('project_domain_id', None),
            project_domain_name=kwargs.get('project_domain_name', None))
    elif {'username', 'password'} <= set(kwargs):
        auth = identity.Password(
            auth_url=kwargs.get('auth_url', None),
            username=kwargs.get('username', None),
            password=kwargs.get('password', None),
            project_id=kwargs.get('project_id', None),
            project_name=kwargs.get('project_name', None),
            project_domain_id=kwargs.get('project_domain_id', None),
            project_domain_name=kwargs.get('project_domain_name', None),
            user_domain_id=kwargs.get('user_domain_id', None),
            user_domain_name=kwargs.get('user_domain_name', None))
    else:
        raise Exception('monascaclient can be configured with either '
                        '"token" or "username:password" but neither of '
                        'them was found in passed arguments.')
    return auth
예제 #18
0
    def probe(self):
        try:
            auth = identity.Password(
                username=self.openstack['username'],
                password=self.openstack['password'],
                project_name=self.openstack['project_name'],
                user_domain_name=self.openstack['user_domain_name'],
                project_domain_name=self.openstack['project_domain_name'],
                auth_url=self.openstack['auth_url'])
            sess = session.Session(auth=auth)
        except Exception as e:
            self.exit_error('cannot get token ' + str(e))

        try:
            neutron = client.Client(session=sess)
        except Exception as e:
            self.exit_error('cannot load ' + str(e))

        try:
            result = neutron.list_routers()
        except Exception as e:
            self.exit_error(str(e))

        stati = dict(active=0, down=0, build=0)

        for router in result['routers']:
            if router['status'] == 'ACTIVE':
                stati['active'] += 1
            if router['status'] == 'DOWN':
                stati['down'] += 1
            if router['status'] == 'BUILD':
                stati['build'] += 1

        for r in stati.keys():
            yield osnag.Metric(r, stati[r], min=0)
예제 #19
0
 def initialize(self, auth_url, username, password, project_name):
     auth = identity.Password(auth_url=auth_url,
                              username=username,
                              password=password,
                              project_name=project_name)
     sess = session.Session(auth=auth)
     self.neutron = client.Client(session=sess)
     self.port_update_jobs = {}
예제 #20
0
def main():
    # Sample output / field mapping
    # </guest/endpoint>-<Sample_Topologies@single-server-WO9N_h>-<csr1000v-1>
    #         USER        PROJECT          TOPOLOGY         NODE
    # </guest/endpoint>-<kk-gE8P2J>-<server-3>
    prog = re.compile(r'</(.*)/endpoint>-<(.*)(-[0-9a-z]+)?>-<(.*)>',
                      re.IGNORECASE)

    # table=list()
    try:
        libvirt_uri = os.environ['LIBVIRT_DEFAULT_URI']
    except:
        print "LIBVIRT_DEFAULT_URI env not set!"
        print "Using default '" + libvirt_uri + "'"
        libvirt_uri = "qemu:///system"
    conn = libvirt.openReadOnly(libvirt_uri)

    auth = identity.Password(
        auth_url=os.environ['OS_SERVICE_ENDPOINT'],
        username=os.environ['OS_USERNAME'],
        password=os.environ['OS_PASSWORD'],
        project_name=os.environ['OS_PROJECT_NAME'],
        project_domain_id=os.environ['OS_PROJECT_DOMAIN_ID'],
        user_domain_id=os.environ['OS_USER_DOMAIN_ID'])
    sess = session.Session(auth=auth)
    nc = client.Client('2', session=sess)

    pt = prettytable.PrettyTable(
        ["Project", "Topology", "Node", "VNC", "Console", "Instance Name"])
    pt.align = "l"

    for server in nc.servers.list(search_opts={'all_tenants': True}):
        m = prog.match(server.name)
        if m:
            try:
                domain = conn.lookupByUUIDString(server.id)
            except:
                print "Domain not found / not running"
                return 1
            else:
                doc = parseString(domain.XMLDesc(flags=0))
                # get the VNC port
                port = doc.getElementsByTagName('graphics')[0].getAttribute(
                    'port')
                # get the serial console TCP port
                for i in doc.getElementsByTagName('source'):
                    if i.parentNode.nodeName == u'console':
                        console = i.getAttribute('service')
                # get the instance name
                name = doc.getElementsByTagName(
                    'name')[0].childNodes[0].nodeValue
                # add info to table
                pt.add_row(
                    [m.group(1),
                     m.group(2),
                     m.group(4), port, console, name])

    print pt.get_string(sortby="Topology")
예제 #21
0
def get_neutron_client():
    auth = identity.Password(auth_url=AUTH_URL,
                             username=USERNAME,
                             password=PASSWORD,
                             project_name=PROJECT_NAME,
                             project_domain_id=DOMAIN_ID,
                             user_domain_id=DOMAIN_ID)
    sess = session.Session(auth=auth)
    return neutronc.Client(session=sess, endpoint_type='internal')
예제 #22
0
 def lp_admin_client(self):
     if not self._lp_admin_client:
         # Create lp operator client connection to v3 API
         lp_operator_creds = self._lp_operator_creds()
         auth = identity.Password(**lp_operator_creds)
         session = ks_session.Session(auth=auth)
         c = kc_v3.Client(session=session)
         self._lp_admin_client = c
     return self._lp_admin_client
예제 #23
0
 def __init__(self):
     super(Schedule, self).__init__()
     auth = identity.Password(**get_credential(admin_openrc=admin_openrc))
     sess = session.Session(auth=auth)
     # self.glance = glance_client.Client(version='2', session=sess)
     self.nova = nova_client.Client(version='2', session=sess)
     self.zun = zun_client.Client(version='1', session=sess)
     self.neutron = neutron_client.Client(session=sess)
     self.hypervisors = self.nova.hypervisors.list()
예제 #24
0
 def admin_client(self):
     if not self._admin_client:
         # Create admin client connection to v3 API
         admin_creds = self._service_admin_creds()
         auth = identity.Password(**admin_creds)
         session = ks_session.Session(auth=auth)
         c = kc_v3.Client(session=session)
         self._admin_client = c
     return self._admin_client
예제 #25
0
def list_taps(project, fields):
    out = {}

    auth = identity.Password(auth_url=os.environ['OS_SERVICE_ENDPOINT'],
                         username=os.environ['OS_USERNAME'],
                         password=os.environ['OS_PASSWORD'],
                         project_name=os.environ['OS_PROJECT_NAME'],
                         project_domain_id=os.environ['OS_PROJECT_DOMAIN_ID'],
                         user_domain_id=os.environ['OS_USER_DOMAIN_ID'])
    sess = session.Session(auth=auth)
    nc = client.Client(session=sess)

    prog = re.compile(
        r'</(' + project + ')/endpoint>-<(.*)(?:-\w{6})?>-<(.*)>-<(.*)>')
    ports = nc.list_ports()
    for thisport in ports['ports']:
        m = prog.match(thisport['name'])
        if m:
            project, topo, node, connection = m.group(
                1), m.group(2), m.group(3), m.group(4)
            if not project in out:
                out[project] = {}
            if not topo in out[project]:
                out[project][topo] = []
            if connection == project:
                tmp = 'Management Network'
            else:
                tmp = connection
            ip = thisport['fixed_ips'][0]['ip_address']
            if ip in ['10.255.255.1', '10.255.255.2']:
                ip = ''
            out[project][topo].append({'id': thisport['id'],
                'from': node, 'to': tmp, 'mac': thisport['mac_address'], 'ip': ip})

    pt = prettytable.PrettyTable(
        ["Project", "Topology", "Node", "Link", "Interface", "MAC Address", "IP Address"])
    pt.align = "l"

    for project in out:
        projectname = project
        for topo in out[project]:
            toponame = topo
            out[project][topo].sort(key=itemgetter('from'))
            for port in out[project][topo]:
                pt.add_row([projectname, toponame, port['from'],
                    port['to'], "tap" + port['id'][0:11], port['mac'], port['ip']])
                if len(toponame) > 0:
                    toponame = ""
                    projectname = ""
        columns = pt.field_names
        if fields:
            columns = []
            for i in list(hyphen_range(fields)):
                columns.append(pt.field_names[i - 1])
    print pt.get_string(fields=columns)
    return 0
예제 #26
0
def get_session(config):
    auth = identity.Password(
        auth_url=config.get('auth_url'),
        username=config.get('username'),
        password=config.get('password'),
        project_name=config.get('project_name'),
        user_domain_name=config.get('user_domain_name', 'default'),
        project_domain_name=config.get('project_domain_name', 'default'))
    sess = session.Session(auth=auth)
    return sess
예제 #27
0
    def setUpClass(cls):
        super(WhenTestingClientConnectivity, cls).setUpClass()
        if 'v2' in CONF.identity.auth_version:
            cls.auth = identity.Password(
                auth_url=CONF.identity.uri,
                username=CONF.keymanager.username,
                password=CONF.keymanager.password,
                tenant_name=CONF.keymanager.project_name)
        else:
            cls.auth = identity.Password(
                auth_url=CONF.identity.uri,
                username=CONF.keymanager.username,
                user_domain_name=CONF.identity.domain_name,
                password=CONF.keymanager.password,
                project_name=CONF.keymanager.project_name,
                project_domain_name=CONF.keymanager.project_domain_name)

        # enables the tests in this class to share a keystone token
        cls.sess = session.Session(auth=cls.auth)
예제 #28
0
def get_client(token=None):
    auth = identity.Password(auth_url=CONF.neutron.auth_url,
                             username=CONF.neutron.username,
                             password=CONF.neutron.password,
                             project_name=CONF.neutron.project_name,
                             project_domain_id=CONF.neutron.project_domain_id,
                             user_domain_id=CONF.neutron.user_domain_id)
    sess = session.Session(auth=auth)
    neutron = clientv20.Client(session=sess)
    return neutron
예제 #29
0
 def create_auth(self):
     self._check_credentials()
     if not self.auth:
         self.auth = identity.Password(
             auth_url=os.environ['OS_AUTH_URL'],
             username=os.environ['OS_USERNAME'],
             password=os.environ['OS_PASSWORD'],
             project_name=os.environ['OS_TENANT_NAME'])
     if not self.session:
         self.session = session.Session(auth=self.auth)
예제 #30
0
 def _get_auth_sess(self):
     self.auth = identity.Password(
         auth_url=self.auth_url,
         username=self.username,
         password=self.password,
         project_name=self.project_name,
         user_domain_name=self.user_domain_name,
         project_domain_name=self.project_domain_name)
     self.sess = self._get_session(self.auth)
     return self.auth, self.sess