Ejemplo n.º 1
0
def main():
    CONF(sys.argv[1:], project='get_auth_token')

    user = CONF.username or CONF.os_admin_username
    password = CONF.password or CONF.os_admin_password
    tenant = CONF.tenant or CONF.os_admin_tenant_name

    protocol = CONF.os_auth_protocol
    host = CONF.os_auth_host
    port = CONF.os_auth_port

    auth_url = "%s://%s:%s/v2.0/" % (protocol, host, port)

    print "User: %s" % user
    print "Password: %s" % password
    print "Tenant: %s" % tenant
    print "Auth URL: %s" % auth_url

    keystone = keystone_client(
        username=user,
        password=password,
        tenant_name=tenant,
        auth_url=auth_url
    )

    result = keystone.authenticate()

    print "Auth succeed: %s" % result
    print "Auth token: %s" % keystone.auth_token
    print "Tenant [%s] id: %s" % (tenant, keystone.tenant_id)
Ejemplo n.º 2
0
def main():
    dev_conf = os.path.join(possible_topdir, "etc", "sahara", "sahara.conf")
    config_files = None
    if os.path.exists(dev_conf):
        config_files = [dev_conf]

    CONF(sys.argv[1:], project="get_auth_token", default_config_files=config_files)

    auth_uri = CONF.keystone_authtoken.auth_uri
    user = CONF.username or CONF.keystone_authtoken.admin_user
    password = CONF.password or CONF.keystone_authtoken.admin_password
    tenant = CONF.tenant or CONF.keystone_authtoken.admin_tenant_name

    print "User: %s" % user
    print "Password: %s" % password
    print "Tenant: %s" % tenant
    print "Auth URI: %s" % auth_uri

    keystone = keystone_client(username=user, password=password, tenant_name=tenant, auth_url=auth_uri)

    result = keystone.authenticate()

    print "Auth succeed: %s" % result
    print "Auth token: %s" % keystone.auth_token
    print "Tenant [%s] id: %s" % (tenant, keystone.tenant_id)
    print "For bash:"
    print "export TOKEN=%s" % keystone.auth_token
    print "export TENANT_ID=%s" % keystone.tenant_id
Ejemplo n.º 3
0
def main():
    dev_conf = os.path.join(possible_topdir, 'etc', 'sahara', 'sahara.conf')
    config_files = None
    if os.path.exists(dev_conf):
        config_files = [dev_conf]

    CONF(sys.argv[1:],
         project='get_auth_token',
         default_config_files=config_files)

    auth_uri = CONF.keystone_authtoken.auth_uri
    user = CONF.username or CONF.keystone_authtoken.admin_user
    password = CONF.password or CONF.keystone_authtoken.admin_password
    tenant = CONF.tenant or CONF.keystone_authtoken.admin_tenant_name

    print "User: %s" % user
    print "Password: %s" % password
    print "Tenant: %s" % tenant
    print "Auth URI: %s" % auth_uri

    keystone = keystone_client(username=user,
                               password=password,
                               tenant_name=tenant,
                               auth_url=auth_uri)

    result = keystone.authenticate()

    print "Auth succeed: %s" % result
    print "Auth token: %s" % keystone.auth_token
    print "Tenant [%s] id: %s" % (tenant, keystone.tenant_id)
    print "For bash:"
    print "export TOKEN=%s" % keystone.auth_token
    print "export TENANT_ID=%s" % keystone.tenant_id
Ejemplo n.º 4
0
def main():
    dev_conf = os.path.join(possible_topdir, 'etc', 'savanna', 'savanna.conf')
    config_files = None
    if os.path.exists(dev_conf):
        config_files = [dev_conf]

    CONF(sys.argv[1:],
         project='get_auth_token',
         default_config_files=config_files)

    user = CONF.username or CONF.os_admin_username
    password = CONF.password or CONF.os_admin_password
    tenant = CONF.tenant or CONF.os_admin_tenant_name

    protocol = CONF.os_auth_protocol
    host = CONF.os_auth_host
    port = CONF.os_auth_port

    auth_url = "%s://%s:%s/v2.0/" % (protocol, host, port)

    print "User: %s" % user
    print "Password: %s" % password
    print "Tenant: %s" % tenant
    print "Auth URL: %s" % auth_url

    keystone = keystone_client(username=user,
                               password=password,
                               tenant_name=tenant,
                               auth_url=auth_url)

    result = keystone.authenticate()

    print "Auth succeed: %s" % result
    print "Auth token: %s" % keystone.auth_token
    print "Tenant [%s] id: %s" % (tenant, keystone.tenant_id)
Ejemplo n.º 5
0
 def keystone(self):
     ''' Keystone client '''
     if self._keystone is None:
         self._keystone = keystone_client(auth_url=self.auth_url,
                                          tenant_id=self.tenant_id(),
                                          token=self.auth_token())
     return self._keystone
Ejemplo n.º 6
0
def tenants_create_tenant(request):
    if request.method == "GET":
        return render(request,
                      'create_tenant.html',
                      {
                      })
    elif request.method == "POST":
        auth_ref = request.session.get('auth_ref', None)
        username = request.session.get('username', None)
        password = request.session.get('password', None)
        current_project_name = request.session.get('project_name', None)

        input_name = request.POST.get('inputName', None)
        input_description = request.POST.get('inputDescription', None)

        try:
            keystone_client_1 = \
                    keystone_client(username=username,
                                    password=password,
                                    tenant_name=current_project_name,
                                    auth_url=AUTH_URL_V2)
            tenant_1 = keystone_client_1.tenants.create(input_name,
                                             input_description,
                                             True)
        except Exception, e:
            print e.message
            retval = {'retval':'failed', 'data':'failed'}

        retval = {'retval':'success', 'data':'ok'}
        return HttpResponse(json.dumps(retval, ensure_ascii=False))
Ejemplo n.º 7
0
def project(request, optype):
    """project request"""
    username = request.session.get("username", None)
    password = request.session.get("password", None)
    tenant_name = request.session.get("tenant_name", None)
    # print username, password, tenant_name

    try:
        keystone_client_1 = keystone_client(
            username=username,
            password=password,
            tenant_name=tenant_name,
            auth_url=AUTH_URL_V2)
    except Exception as exc:
        print exc.message

        django_messages.add_message(
            request,
            50,
            "Permission deny! ",
            extra_tags="danger")
        return redirect(reverse(
            'dashboard_auth:login') +
            "?redirect=" + request.build_absolute_uri())

    return route_to(
        optype, request, "project.html", {
            "username": username,
            "tenant_name": tenant_name,
            "keystone_client": keystone_client_1,
        })

    """
Ejemplo n.º 8
0
def users_create_user(request):
    """创建用户"""
    if request.method == "POST":
        input_name = request.POST.get('inputName', None)
        input_email = request.POST.get('inputEmail', None)
        input_tenant = request.POST.get('inputTenant', None)

        auth_ref = request.session.get('auth_ref', None)
        username = request.session.get('username', None)
        password = request.session.get('password', None)
        current_project_name = request.session.get('project_name', None)

        try:
            keystone_client_1 = keystone_client(username=username,
                                               password=password,
                                               tenant_name=current_project_name,
                                               auth_url=AUTH_URL_V2)
            user_manager_1 = keystone_client_1.users
            user1 = user_manager_1.create(name=input_name,
                                  password="******",
                                  tenant_id=input_tenant,
                                  email=input_email)
            retval = {'retval':'success', 'data':'ok'}
        except Exception, e:
            retval = {'retval':'failed', 'data':'create user failed'}
            print e.message


        return HttpResponse(json.dumps(retval, ensure_ascii=False))
Ejemplo n.º 9
0
def tenants_delete_tenant(request):
    """delete tenant """
    if request.method == "POST":
        username = request.session.get("username", None)
        password = request.session.get("password", None)
        current_project_name = \
            request.session.get("project_name", None)
        keystone_client_1 = \
            keystone_client(username=username,
                            password=password,
                            tenant_name=current_project_name,
                            auth_url=AUTH_URL_V2)
        for tenant_id in request.POST.getlist("selectuser", None):
            keystone_client_1.tenants.delete(tenant_id)

        retval = {'retval':'success', 'data':'ok'}
        return HttpResponse(json.dumps(retval, ensure_ascii=False))
Ejemplo n.º 10
0
def main():
    if len(sys.argv) > 1 and len(sys.argv) != 4:
      print "You must either specify no parameters or exactly 3: <username> <password> <tenant>.\n" \
            "If you specify no parameters, credentials and tenant will be taken from config"
      exit

    scriptDir = os.path.dirname(os.path.realpath(__file__))
    config = Config(scriptDir + '/../etc')
    config.from_pyfile('local.cfg')

    print "Configuration has been loaded from 'etc/local.cfg'"

    if len(sys.argv) == 4:
        user = sys.argv[1]
        password = sys.argv[2]
        tenant = sys.argv[3]
    else:
        print "You didn't provided credentials, using ones found in config"
        user = config['OS_ADMIN_USER']
        password = config['OS_ADMIN_PASSWORD']
        tenant = config['OS_ADMIN_TENANT']

    protocol = config['OS_AUTH_PROTOCOL']
    host = config['OS_AUTH_HOST']
    port = config['OS_AUTH_PORT']

    auth_url = "%s://%s:%s/v2.0/" % (protocol, host, port)

    print "User: %s" % user
    print "Password: %s" % password
    print "Tenant: %s" % tenant
    print "Auth URL: %s" % auth_url

    keystone = keystone_client(
        username=user,
        password=password,
        tenant_name=tenant,
        auth_url=auth_url
    )

    result = keystone.authenticate()

    print "Auth succeed: %s" % result
    print "Auth token: %s" % keystone.auth_token
    print "Tenant [%s] id: %s" % (tenant, keystone.tenant_id)
Ejemplo n.º 11
0
def main():
    dev_conf = os.path.join(possible_topdir,
                            'etc',
                            'sahara',
                            'sahara.conf')
    config_files = None
    if os.path.exists(dev_conf):
        config_files = [dev_conf]

    CONF(sys.argv[1:], project='get_auth_token',
         default_config_files=config_files)

    user = CONF.username or CONF.os_admin_username
    password = CONF.password or CONF.os_admin_password
    tenant = CONF.tenant or CONF.os_admin_tenant_name

    protocol = CONF.os_auth_protocol
    host = CONF.os_auth_host
    port = CONF.os_auth_port

    auth_url = "%s://%s:%s/v2.0/" % (protocol, host, port)

    print "User: %s" % user
    print "Password: %s" % password
    print "Tenant: %s" % tenant
    print "Auth URL: %s" % auth_url

    keystone = keystone_client(
        username=user,
        password=password,
        tenant_name=tenant,
        auth_url=auth_url
    )

    result = keystone.authenticate()

    print "Auth succeed: %s" % result
    print "Auth token: %s" % keystone.auth_token
    print "Tenant [%s] id: %s" % (tenant, keystone.tenant_id)
Ejemplo n.º 12
0

def _get_conf(key, default):
    return getattr(_CONF, key) if _CONF and hasattr(_CONF, key) else default

OS_USERNAME = _get_conf("OS_USERNAME", "admin")
OS_PASSWORD = _get_conf("OS_PASSWORD", "nova")
OS_TENANT_NAME = _get_conf("OS_TENANT_NAME", "admin")
OS_AUTH_URL = _get_conf("OS_AUTH_URL", "http://localhost:35357/v2.0/")
SAVANNA_HOST = _get_conf("SAVANNA_HOST", "192.168.1.1")
SAVANNA_PORT = _get_conf("SAVANNA_PORT", "8080")
SAVANNA_IMAGE_ID = _get_conf("SAVANNA_IMAGE_ID", "42")

keystone = keystone_client(
    username=OS_USERNAME,
    password=OS_PASSWORD,
    tenant_name=OS_TENANT_NAME,
    auth_url=OS_AUTH_URL
)


class ValidationTestCase(unittest.TestCase):
    def setUp(self):
        self.host = SAVANNA_HOST
        self.maxDiff = None
        self.port = SAVANNA_PORT
        self.baseurl = 'http://' + self.host + ':' + self.port
        self.tenant = keystone.tenant_id
        self.token = keystone.auth_token
        self.flavor_id = 'm1.medium'
        self.image_id = SAVANNA_IMAGE_ID
        self.url_nt = '/v0.2/%s/node-templates' % self.tenant
Ejemplo n.º 13
0
def token_request():
    ''' Intercept a token request and use that to talk to multiple clouds
    based on values stored in the database.

    request data format will be:

    {"auth": {"passwordCredentials": {
        "password": "******",
        "username": "******"
    }}}

    tukeyPassword is a password shared between the middleware and the portal to
    prevent anyone from talking to the middleware and impersonating users.

    method can be shibboleth or openid.
    identifier is looked up in the tukey auth db which stores users openstack
    credentials. Those credentials are used to talk to the Keystone service
    for each cloud. The auth tokens from each keystone request are stored in
    memcached with one of the tokens used as the key and returned back to
    Horizon. '''

    token_store = TokenStore(memcache.Client(['127.0.0.1:11211']))
    logger = utils.get_logger()

    try:
        token_id = flask.request.headers["x-auth-token"]
        token_info = token_store.get(str(token_id))
        return json.dumps(token_info["__tukey_internal"])
    except KeyError:
        pass

    pw_creds = json.loads(flask.request.data)["auth"]["passwordCredentials"]

    # string equality in Python is probably a side-channel vector
    if pw_creds["password"] != settings["shared_password"]:
        return ("Wrong credentials", 401)

    method, userid = pw_creds["username"].split()

    user_info_query = '''
        select username, password, cloud_name, display_name, auth_url, login_url,
            instance_keypairs.cloud_id
        from
        login join
        login_enabled on login.id = login_enabled.login_id join
        login_identifier on login.userid = login_identifier.userid join
        login_identifier_enabled on login_identifier.id =
            login_identifier_enabled.login_identifier_id join
        login_method on login_method.method_id = login_identifier.method_id
            join
        cloud on cloud.cloud_id = login.cloud_id
            left outer join
        instance_keypairs on instance_keypairs.cloud_id = cloud.cloud_id
        where login_method.method_name='%(method)s'
            and LOWER(login_identifier.identifier)=LOWER('%(id)s');
    ''' % {"method": method, "id": userid}

    engine = sqlalchemy.create_engine(settings["auth_db_str"])
    with engine.begin() as connection:
        results = connection.execute(sqlalchemy.text(user_info_query))

    roles = []
    info_by_cloud = {}
    tenant = None

    endpoints = {}

    for (_username, password, cloud, display_name, auth_url, login_url,
            instance_keypairs) in results:
        if auth_url:
            try:
                try:
                    ksc = keystone_client(auth_url=auth_url, username=_username,
                        password=password)
                except keystoneclient.apiclient.exceptions.Unauthorized:
                    # this should be a valid username so let Horizon know
                    logger.info(("Cloud %s Keystone at %s ",
                            "rejected username password: %s %s"), cloud,
                            auth_url, _username, password)
                    # this is probably not the best or clearest, just different
                    flask.abort(403)

                tenants = [t for t in ksc.tenants.list() if t.enabled]

                if len(tenants) < 1:
                    logger.info("Cloud %s username: %s has no tenants", cloud,
                            _username)
                    continue

                for tenant in tenants:
                    if tenant.name == _username:
                        break

                token_response = ksc.get_raw_token_from_identity_service(
                        auth_url, username=_username, password=password,
                        tenant_name=tenant.name)

                try:
                    # this should work if keystoneclient version <= 0.6.0
                    response, raw_token = token_response
                    response_status = response.status_code
                except ValueError:
                    # this should work if keystoneclient version >= 0.7.0
                    raw_token = token_response
                    response_status = 200

                # handle changes between 0.6.0 and 0.7.0
                if "access" not in raw_token:
                    raw_token = {"access": raw_token}

                if response_status != 200:
                    logger.info(("Cloud %s Keystone at %s ",
                            "rejected username: %s with status code: %s"),
                            cloud, auth_url, _username, response_status)
                    flask.abort(403)

                # add enpoints
                for endpoint in raw_token["access"]["serviceCatalog"]:
                    endpoints[endpoint["type"]] = endpoint["name"]

                token_id = ksc.auth_token
                user_id = ksc.user_id
                username = _username
                raw_token["cloud"] = display_name
                if instance_keypairs:
                    raw_token["instance_keypairs"] = True
                info_by_cloud[cloud] = raw_token
                info_by_cloud["login" + cloud] = login_url

                roles += raw_token["access"]["user"]["roles"]
                raw_token["cloud"] = display_name
            except AuthorizationFailure:
                logger.info("Keystone failed for %s", cloud)
        else:
            info_by_cloud[cloud] = {"username": _username,
                    "cloud": display_name,
                    "instance_keypairs": True if instance_keypairs else False}
            info_by_cloud["login" + cloud] = login_url

    if tenant is None:
        logger.info("Login failed for %s using method %s", userid, method)
        flask.abort(401)

    region = "RegionOne"
    host, port = "localhost", LOCAL_PORT

    allowed_services = ['compute', 'image', 'volume', 'object-store']

    # glance assumes that it is at /v1 so we will give it that
    #service_paths = {k: K for k in allowed_services}
    #service_paths["image"] = "v1"

    services = [("http://%s:%s/%s/%s" % (host, port, service, tenant.id),
                    service, service_name)
            for service, service_name in endpoints.items()
                if service in allowed_services]

    services += [("http://%s:%s/v2.0" % (host, port), "identity", "keystone")]

    catalog = {
        "access": {
            "token": {
                "expires": expiration(43200),
                "id": token_id,
                "tenant": format_tenant(tenant.name, tenant.id)
            },
            "serviceCatalog": [
                service_catalog_entry(url, region, url, url, service_type, name)
                    for url, service_type, name in services] + [
                service_catalog_entry(
                        "http://%s:%s/services/Admin" % (host, port), region,
                        "http://%s:%s/services/Cloud" % (host, port),
                        "http://%s:%s/services/Cloud" % (host, port), "ec2",
                        "ec2")],
            "user": {
                "username": username,
                "roles_links": [],
                "id": user_id,
                "roles": roles,
                "name": username
            }},
            "path": "", "host": host, "port": port}

    info_by_cloud["__tukey_internal"] = catalog

    # TODO:
    # see what the shortest expiration is in the set of expirations
    # then set the returned expiration to that and make sure that
    # the memcache expiration is greater than that but has a value so
    # that memcached entries don't fill everything up

    token_store.set(str(token_id), info_by_cloud, 172800)
    logger.info("Login succeeded for %s using method %s" % (userid, method))

    return json.dumps(catalog)
Ejemplo n.º 14
0
    def setUp(self):
        self.host = SAVANNA_HOST
        self.maxDiff = None
        self.port = SAVANNA_PORT
        self.baseurl = 'http://' + self.host + ':' + self.port
        self.keystone = keystone_client(
            username=OS_USERNAME,
            password=OS_PASSWORD,
            tenant_name=OS_TENANT_NAME,
            auth_url=OS_AUTH_URL
        )
        self.tenant = self.keystone.tenant_id
        self.token = self.keystone.auth_token
        self.flavor_id = 'm1.medium'
        self.image_id = SAVANNA_IMAGE_ID
        self.url_nt = '/v0.2/%s/node-templates' % self.tenant
        self.url_nt_not_json = '/v0.2/%s/node-templates/' % self.tenant

#----------------------add_value_for_node_templates----------------------------

        self.jtnn = dict(
            node_template=dict(
                name='test-template-1',
                node_type='JT+NN',
                flavor_id=self.flavor_id,
                job_tracker={
                    'heap_size': '1234'
                },
                name_node={
                    'heap_size': '2345'
                }
            ))
        self.ttdn = dict(
            node_template=dict(
                name='test-template-2',
                node_type='TT+DN',
                flavor_id=self.flavor_id,
                task_tracker={
                    'heap_size': '1234'
                },
                data_node={
                    'heap_size': '2345'
                }
            ))
        self.jt = dict(
            node_template=dict(
                name='test-template-3',
                node_type='JT',
                flavor_id=self.flavor_id,
                job_tracker={
                    'heap_size': '1234'
                }
            ))
        self.nn = dict(
            node_template=dict(
                name='test-template-4',
                node_type='NN',
                flavor_id=self.flavor_id,
                name_node={
                    'heap_size': '2345'
                }
            ))
        self.tt = dict(
            node_template=dict(
                name='test-template-5',
                node_type='TT',
                flavor_id=self.flavor_id,
                task_tracker={
                    'heap_size': '2345'
                }
            ))
        self.dn = dict(
            node_template=dict(
                name='test-template-6',
                node_type='DN',
                flavor_id=self.flavor_id,
                data_node={
                    'heap_size': '2345'
                }
            ))

        self.get_ttdn = {
            u'name': u'test-template-2',
            u'data_node': {u'heap_size': u'2345'},
            u'task_tracker': {u'heap_size': u'1234'},
            u'node_type': {
                u'processes': [u'task_tracker',
                               u'data_node'],
                u'name': u'TT+DN'},
            u'flavor_id': u'm1.medium'
        }

        self.get_jtnn = {
            u'name': u'test-template-1',
            u'name_node': {u'heap_size': u'2345'},
            u'job_tracker': {u'heap_size': u'1234'},
            u'node_type': {
                u'processes': [u'job_tracker',
                               u'name_node'],
                u'name': u'JT+NN'},
            u'flavor_id': u'm1.medium'
        }

        self.get_nn = {
            u'name': u'test-template-4',
            u'name_node': {u'heap_size': u'2345'},
            u'node_type': {
                u'processes': [u'name_node'],
                u'name': u'NN'},
            u'flavor_id': u'm1.medium'
        }

        self.get_jt = {
            u'name': u'test-template-3',
            u'job_tracker': {u'heap_size': u'1234'},
            u'node_type': {
                u'processes': [u'job_tracker'],
                u'name': u'JT'},
            u'flavor_id': u'm1.medium'
        }

#----------------------add_value_for_clusters----------------------------------

        self.url_cluster = '/v0.2/%s/clusters' % self.tenant
        self.url_cluster_without_json = '/v0.2/%s/clusters/' % self.tenant

        self.cluster_data_jtnn_ttdn = dict(
            cluster=dict(
                name='QA-test-cluster',
                base_image_id=self.image_id,
                node_templates={
                    'jt_nn.medium': 1,
                    'tt_dn.medium': 2
                }
            ))

        self.cluster_data_jtnn_ttdn_small = dict(
            cluster=dict(
                name='QA-test-cluster',
                base_image_id=self.image_id,
                node_templates={
                    'jt_nn.small': 1,
                    'tt_dn.small': 1
                }
            ))

        self.cluster_data_jtnn = dict(
            cluster=dict(
                name='test-cluster',
                base_image_id=self.image_id,
                node_templates={
                    'jt_nn.medium': 1
                }
            ))

        self.get_cluster_data_jtnn_ttdn = {
            u'status': u'Starting',
            u'service_urls': {},
            u'name': u'QA-test-cluster',
            u'base_image_id': u'%s' % self.image_id,
            u'node_templates':
            {
                u'jt_nn.medium': 1,
                u'tt_dn.medium': 2
            },
            u'nodes': []
        }

        self.get_cluster_data_jtnn_ttdn_small = {
            u'status': u'Starting',
            u'service_urls': {},
            u'name': u'QA-test-cluster',
            u'base_image_id': u'%s' % self.image_id,
            u'node_templates':
            {
                u'jt_nn.small': 1,
                u'tt_dn.small': 1
            },
            u'nodes': []
        }

        self.get_cluster_data_jtnn = {
            u'status': u'Starting',
            u'service_urls': {},
            u'name': u'test-cluster',
            u'base_image_id': u'%s' % self.image_id,
            u'node_templates':
            {
                u'jt_nn.medium': 1
            },
            u'nodes': []
        }