예제 #1
0
 def process_event(self, body, message):
     """
     This function analyzes ``body`` and calls
     heart_request_interceptors.
     """
     method = body.get("method", None)
     heart_request = None
     for interceptor in self.heart_request_interceptors:
         heart_request = interceptor(method, body)
         if heart_request is not None:
             heart_request.setdefault(
                 "datetime",
                 utils.datetime_to_str(self.get_event_datetime(body)))
             heart_request.setdefault("account",
                                      body["_context_project_id"])
             try:
                 self.billing_heart.event(heart_request)
             except socket.error as ex:
                 LOG.error("cannot post event to the Heart: %s" % str(ex))
             except:
                 LOG.exception("cannot post event to the Heart")
             break
     try:
         routing_key = message.delivery_info["routing_key"]
     except AttributeError, KeyError:
         routing_key = "<unknown>"
예제 #2
0
 def __call__(self, req):
     resp = req.get_response(self.application)
     path_info = req.environ.get("PATH_INFO", "/")
     if not path_info.startswith("/images"):
         return resp
     method = req.environ.get("REQUEST_METHOD", "GET")
     if method == "PUT" or method == "POST":
         try:
             resp_json = json.loads(resp.body)
             img_id, img_size = resp_json["image"]["id"], resp_json[
                 "image"]["size"]
         except KeyError:
             return resp
         heart_request = {"name": img_id, "linear": img_size / (1024.0**3)}
     elif method == "DELETE":
         heart_request = {
             "name": path_info[len("/images/"):],
             "fixed": None
         }
     else:
         heart_request = None
     if heart_request is not None:
         heart_request["rtype"] = "glance/image"
         heart_request["account"] = req.headers["X-Tenant-Id"]
         heart_request["datetime"] = utils.datetime_to_str(utils.now())
         try:
             self.billing_heart.event.create(heart_request)
         except:
             LOG.exception("cannot report image info for billing")
     return resp
예제 #3
0
 def __call__(self, req):
     resp = req.get_response(self.application)
     path_info = req.environ.get("PATH_INFO", "/")
     if not path_info.startswith("/images"):
         return resp
     method = req.environ.get("REQUEST_METHOD", "GET")
     if method == "PUT" or method == "POST":
         try:
             resp_json = json.loads(resp.body)
             img_id, img_size = resp_json["image"]["id"], resp_json["image"]["size"]
         except KeyError:
             return resp
         heart_request = {"name": img_id,
                          "linear": img_size / (1024.0 ** 3)}
     elif method == "DELETE":
         heart_request = {"name": path_info[len("/images/"):],
                          "fixed": None}
     else:
         heart_request = None
     if heart_request is not None:
         heart_request["rtype"] = "glance/image"
         heart_request["account"] = req.headers["X-Tenant-Id"]
         heart_request["datetime"] = utils.datetime_to_str(utils.now())
         try:
             self.billing_heart.event.create(heart_request)
         except:
             LOG.exception("cannot report image info for billing")
     return resp
예제 #4
0
파일: amqp.py 프로젝트: altai/nova-billing
 def process_event(self, body, message):
     """
     This function analyzes ``body`` and calls
     heart_request_interceptors.
     """
     method = body.get("method", None)
     heart_request = None
     for interceptor in self.heart_request_interceptors:
         heart_request = interceptor(method, body)
         if heart_request is not None:
             heart_request.setdefault("datetime", utils.datetime_to_str(self.get_event_datetime(body)))
             heart_request.setdefault("account", body["_context_project_id"])
             LOG.debug("posting event to the Heart: %s" % heart_request)
             try:
                 self.billing_heart.event.create(heart_request)
             except socket.error as ex:
                 LOG.error("cannot post event to the Heart: %s" % str(ex))
             except:
                 LOG.exception("cannot post event to the Heart")
             break
     try:
         routing_key = message.delivery_info["routing_key"]
     except AttributeError, KeyError:
         routing_key = "<unknown>"
예제 #5
0
    def __call__(self, req):
        """
        Determine period start and stop, ask db api, and return JSON report.
        """
        arg_dict = req.environ['wsgiorg.routing_args'][1]

        STATISTICS_NONE = 0
        STATISTICS_SHORT = 1
        STATISTICS_LONG = 2

        queried_tenant_id = arg_dict.get("project_id", None)
        roles = [r.strip()
                 for r in req.headers.get('X_ROLE', '').split(',')]
        is_admin = "Admin" in roles
        if not is_admin:
            if queried_tenant_id:
                if req.headers.get('X_TENANT_ID', '') != queried_tenant_id:
                    raise webob.exc.HTTPUnauthorized()
            else:
                queried_tenant_id = req.headers.get('X_TENANT_ID', '-1')

        auth_token = req.headers.get('X_AUTH_TOKEN', '')

        period_start, period_end = self.get_period(req)
        statistics = {"instances": STATISTICS_NONE,
                      "images": STATISTICS_NONE}
        try:
            include = req.GET["include"]
        except KeyError:
            statistics["instances"] = (STATISTICS_LONG
                if period_end - period_start <= datetime.timedelta(days=31)
                    and queried_tenant_id
                else STATISTICS_SHORT)
        else:
            include = include.strip(",")
            for key in "images", "instances":
                if (key + "-long") in include:
                    statistics[key] = STATISTICS_LONG
                elif key in include:
                    statistics[key] = STATISTICS_SHORT

        if is_admin:
            tenants = keystone_utils.KeystoneTenants().\
                    get_tenants(auth_token)
            reported_projects = set([tenant.id for tenant in tenants])
            if queried_tenant_id:
                if queried_tenant_id in reported_projects:
                    reported_projects = set([queried_tenant_id])
                else:
                    raise webob.exc.HTTPNotFound()
        else:
            reported_projects = set([queried_tenant_id])

        projects = {}
        for project_id in reported_projects:
            projects[project_id] = {
                "id": str(project_id),
                "url": "http://%s:%s/projects/%s" %
                       (req.environ["SERVER_NAME"],
                        req.environ["SERVER_PORT"],
                        project_id),
            }
        now = utils.now()
        for statistics_key in "images", "instances":
            if not statistics[statistics_key]:
                continue
            show_items = statistics[statistics_key] == STATISTICS_LONG
            if statistics_key == "images":
                total_statistics = glance_utils.images_on_interval(
                    period_start, period_end,
                    auth_token, queried_tenant_id)
            else:
                total_statistics = db_api.instances_on_interval(
                    period_start, period_end, queried_tenant_id)
            for project_id in projects:
                project_statistics = total_statistics.get(project_id, {})
                project_dict = {
                    "count": len(project_statistics),
                }
                project_usage = {}
                items = []
                for item_id, item_statistics in project_statistics.items():
                    utils.dict_add(project_usage, item_statistics["usage"])
                    if show_items:
                        lifetime = utils.total_seconds(
                            min(item_statistics["destroyed_at"] or now, period_end) -
                            max(item_statistics["created_at"], period_start))
                        item_dict = {
                            "id": item_id,
                            "lifetime_sec": lifetime,
                            "usage": utils.usage_to_hours(item_statistics["usage"]),
                            "name": item_statistics.get("name", None),
                        }
                        for key in "created_at", "destroyed_at":
                            item_dict[key] = utils.datetime_to_str(item_statistics[key])
                        items.append(item_dict)

                if show_items:
                    project_dict["items"] = items
                project_dict["usage"] = utils.usage_to_hours(project_usage)
                projects[project_id][statistics_key] = project_dict

        ans_dict = {
            "period_start": utils.datetime_to_str(period_start),
            "period_end": utils.datetime_to_str(period_end),
            "projects": projects.values(),
        }
        return webob.Response(json.dumps(ans_dict),
                              content_type='application/json')