Example #1
0
File: api.py Project: xww/umbrella
def get_user(user_id, auth_token):
    """
    return sample as:
    {'email': '*****@*****.**',
    'tenantName':'openstackDemo',
    'name': 'zsy',
    'enabled': True,
    'id': '771ac76cb3464a6580cdfe3d59351f37',
    'tenantId': 'f5d0a72747f34b2591aa9be636f15668'}
    """
    cache = local.dict_store()
    user = cache.get_item("user", user_id)
    if user is not None:
        return user
    c = client.KeystoneAdminClient()
    try:
        result, headers = c.response("GET", "/users/%s" % user_id, params={}, headers={"x-auth-token": auth_token})
    except exc.HTTPNotFound:
        result = {"user": {"email": "", "tenantName": "", "name": "", "enabled": False, "id": "", "tenantId": ""}}
    try:
        result = result["user"]
    except KeyError:
        raise exc.HTTPFailedDependency(_("Keystone method deprecated."))
    tenant_id = result["tenantId"]
    try:
        tenant = get_tenant(tenant_id, auth_token)
        result.update(tenantName=tenant["name"])
    except exc.HTTPNotFound:
        LOG.warn("user %s has no tenant associated." % user_id)
        pass
    cache.save_item("user", user_id, result, timeout=CONF.user_cache_timeout)
    return result
Example #2
0
 def save_setting(self, req, body, uuid=None):
     if not uuid:
         setting = self.db_api.setting_create(body)
     else:
         setting = self.db_api.setting_update(uuid, body)
     #save setting in local dict store
     local_dict = local.dict_store()
     local_dict.save_setting(setting.level, setting.type, setting)
     return make_setting_dict(setting)
Example #3
0
File: api.py Project: xww/umbrella
def get_all_tenants(auth_token=None):
    cache = local.dict_store()
    auth_token = auth_token or request_admin_token()
    auth_token = normal_token(auth_token)
    c = client.KeystoneAdminClient()
    result, headers = c.response("GET", "/tenants", params={}, headers={"x-auth-token": auth_token})
    for tenant in result["tenants"]:
        tenant_id = tenant["id"]
        standardize_tenant_name(tenant)
        cache.save_item("tenant", tenant_id, tenant, timeout=CONF.user_cache_timeout)
    return result
Example #4
0
File: api.py Project: xww/umbrella
def get_detault_quotas(tenant_id, target_id, auth_token):
    cache = local.dict_store()
    # Note(hzzhoushaoyu): Save for who request quota default(tenant_id),
    # not whose quota default(target_id).
    quota_default = cache.get_item("quota_default", tenant_id)
    if quota_default is not None:
        return quota_default
    c = client.NovaClient()
    result, headers = c.response(
        "GET", "/%s/os-quota-sets/%s/defaults" % (tenant_id, target_id), params={}, headers={"x-auth-token": auth_token}
    )
    cache.save_item("quota_default", tenant_id, result, timeout=CONF.quota_default_cache_timeout)
    return result
Example #5
0
File: api.py Project: xww/umbrella
def get_all_users(auth_token=None):
    cache = local.dict_store()
    auth_token = auth_token or request_admin_token()
    auth_token = normal_token(auth_token)
    c = client.KeystoneAdminClient()
    result, headers = c.response("GET", "/users", params={}, headers={"x-auth-token": auth_token})
    for user in result["users"]:
        user_id = user["id"]
        tenant_id = user["tenantId"]
        try:
            tenant = get_tenant(tenant_id, auth_token)
            user.update(tenantName=tenant["name"])
        except exc.HTTPNotFound:
            LOG.warn("user %s has no tenant associated." % user_id)
            pass
        cache.save_item("user", user_id, user, timeout=CONF.user_cache_timeout)
    return result
Example #6
0
File: api.py Project: xww/umbrella
def get_flavor(tenant_id, auth_token, flavor_id):
    cache = local.dict_store()
    flavor = cache.get_item("flavor", flavor_id)
    if flavor is not None:
        return flavor
    c = client.NovaClient()
    try:
        result, headers = c.response(
            "GET", "/%s/flavors/%s" % (tenant_id, flavor_id), params={}, headers={"x-auth-token": auth_token}
        )
    except exc.HTTPNotFound:
        return None

    result = get_extra_specs(c, result, tenant_id, auth_token, flavor_id)
    if result is not None:
        cache.save_item("flavor", flavor_id, result, timeout=CONF.flavor_cache_timeout)
    return result
Example #7
0
    def check_type_usage(self, level, setting_type, type_usage):
        '''
        check specify setting type usage in specify level
        '''
        store = local.dict_store()
        expire = CONF.no_replicate_alarm_seconds
        alarm_replicate = CONF.alarm_replicate_usage_changed
        # check whether need alarm replicated in expire seconds
        latest_alarm_usage = store.get_alarming(level, setting_type,
                                                type_usage, expire)
        if latest_alarm_usage is not None:
            if not (latest_alarm_usage != type_usage and alarm_replicate):
                # if usage not change, not alarm;
                # if changed but not need alarm, not alarm.
                LOG.debug(_("Has alarmed in %(expire)s seconds for "
                            "level %(level)s and setting type %(setting_type)s"
                            " and usage %(type_usage)s..."), locals())
                return
        # need alarm and search for settings
        setting = store.get_setting(level, setting_type)
        if not setting:
            self.db_api.configure_db()
            try:
                setting = self.db_api.setting_get_by_lever_type(level,
                                                                setting_type)
                store.save_setting(level, setting_type, setting)
            except exception.NotFound:
                setting = None
        if not setting or setting.capacity <= 0 or setting.threshold <= 0.0:
            # Note(hzzhoushaoyu): no valid setting has been found in cache
            # and DB return for no alarming
            LOG.info(_("NO setting found for level %(level)s "
                    "and type %(setting_type)s"),
                locals())
            return

        if type_usage > setting.capacity * setting.threshold / 100:
            LOG.debug(_("saving alarming for level %(level)s "
                        "and type %(setting_type)s....."), locals())
            alarming_dict = {
                             "settings_uuid": setting.uuid,
                             "usage": type_usage,
                             }
            self.db_api.alarming_create(alarming_dict)
            store.save_alarming(level, setting_type, type_usage)
Example #8
0
File: api.py Project: xww/umbrella
def get_image(auth_token, image_id):
    cache = local.dict_store()
    image = cache.get_item("image", image_id)
    if image is not None:
        return image
    c = client.GlanceClient()
    try:
        result, headers = c.response("HEAD", "/images/%s" % image_id, params={}, headers={"x-auth-token": auth_token})
    except exc.HTTPNotFound:
        return None
    image = {}
    for k, v in headers:
        if k.lower().startswith("x-image-meta"):
            k = k.lower().replace("x-image-meta", "image")
            image.update({k: v})
    image_owner = image.get("image-owner")
    if image_owner is not None:
        tenant = get_tenant(image_owner, auth_token)
        tenant_name = tenant["name"]
        image.update({"image-owner-name": tenant_name})
    cache.save_item("image", image_id, image, timeout=CONF.image_cache_timeout)
    return image
Example #9
0
File: api.py Project: xww/umbrella
def request_admin_token(search_cache=True):
    """Retrieve new token as admin user from keystone.

    :return token id upon success
    :raises ServerError when unable to communicate with keystone

    """
    admin_user = CONF.get("admin_user")
    admin_password = CONF.get("admin_password")
    admin_tenant_name = CONF.get("admin_tenant_name")
    keystone_client = client.KeystonePublicClient()
    local_store = local.dict_store()
    if search_cache and hasattr(local_store, "admin_token"):
        token = local_store.admin_token
        expires = timeutils.parse_isotime(token["expires"])
        if not timeutils.is_older_than(timeutils.normalize_time(expires), 0):
            LOG.debug(_("Get token from local store."))
            return token
    params = {
        "auth": {
            "passwordCredentials": {"username": admin_user, "password": admin_password},
            "tenantName": admin_tenant_name,
        }
    }

    data, headers = keystone_client.response(
        "POST", "/tokens", headers={"content-type": "application/json"}, body=params
    )

    try:
        token = data["access"]["token"]
        assert token
        local_store.admin_token = token
        LOG.debug(_("Request for admin token and save to local store."))
        return token
    except (AssertionError, KeyError):
        LOG.warn("Unexpected response from keystone service: %s", data)
        raise
Example #10
0
File: api.py Project: xww/umbrella
def get_tenant(tenant_id, auth_token):
    """
    return sample as:
    {'id': '4142dc247de848c58364d958a208d516',
    'enabled': True,
    'description': None,
    'name': 'demo'}
    """
    cache = local.dict_store()
    tenant = cache.get_item("tenant", tenant_id)
    if tenant is not None:
        return tenant
    c = client.KeystoneAdminClient()
    try:
        result, headers = c.response("GET", "/tenants/%s" % tenant_id, params={}, headers={"x-auth-token": auth_token})
    except exc.HTTPNotFound:
        result = {"tenant": {"id": "", "enabled": False, "description": None, "name": ""}}
    try:
        result = result["tenant"]
        standardize_tenant_name(result)
    except KeyError:
        raise exc.HTTPFailedDependency(_("Keystone method deprecated."))
    cache.save_item("tenant", tenant_id, result, timeout=CONF.user_cache_timeout)
    return result
Example #11
0
 def tearDown(self):
     base.IsolatedUnitTest.tearDown(self)
     self.db_api.alarming_clear()
     local.dict_store().store_dict = {}