~ubuntu-branches/ubuntu/quantal/nova/quantal-proposed

« back to all changes in this revision

Viewing changes to nova/api/openstack/compute/contrib/instance_usage_audit_log.py

  • Committer: Package Import Robot
  • Author(s): Chuck Short
  • Date: 2012-08-16 14:04:11 UTC
  • mto: This revision was merged to the branch mainline in revision 84.
  • Revision ID: package-import@ubuntu.com-20120816140411-0mr4n241wmk30t9l
Tags: upstream-2012.2~f3
ImportĀ upstreamĀ versionĀ 2012.2~f3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
 
2
 
 
3
# Copyright 2012 OpenStack LLC.
 
4
# All Rights Reserved.
 
5
#
 
6
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
 
7
#    not use this file except in compliance with the License. You may obtain
 
8
#    a copy of the License at
 
9
#
 
10
#         http://www.apache.org/licenses/LICENSE-2.0
 
11
#
 
12
#    Unless required by applicable law or agreed to in writing, software
 
13
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 
14
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 
15
#    License for the specific language governing permissions and limitations
 
16
#    under the License.
 
17
 
 
18
 
 
19
import datetime
 
20
 
 
21
from nova.api.openstack import extensions
 
22
from nova import db
 
23
from nova import flags
 
24
from nova import utils
 
25
 
 
26
FLAGS = flags.FLAGS
 
27
 
 
28
 
 
29
authorize = extensions.extension_authorizer('compute',
 
30
                           'instance_usage_audit_log')
 
31
 
 
32
 
 
33
class InstanceUsageAuditLogController(object):
 
34
 
 
35
    def index(self, req):
 
36
        context = req.environ['nova.context']
 
37
        authorize(context)
 
38
        task_log = self._get_audit_task_logs(context)
 
39
        return {'instance_usage_audit_logs': task_log}
 
40
 
 
41
    def show(self, req, id):
 
42
        context = req.environ['nova.context']
 
43
        authorize(context)
 
44
        try:
 
45
            if '.' in id:
 
46
                before_date = datetime.datetime.strptime(str(id),
 
47
                                                "%Y-%m-%d %H:%M:%S.%f")
 
48
            else:
 
49
                before_date = datetime.datetime.strptime(str(id),
 
50
                                                "%Y-%m-%d %H:%M:%S")
 
51
        except ValueError:
 
52
            msg = _("Invalid timestamp for date %s") % id
 
53
            raise webob.exc.HTTPBadRequest(explanation=msg)
 
54
        task_log = self._get_audit_task_logs(context,
 
55
                                                     before=before_date)
 
56
        return {'instance_usage_audit_log': task_log}
 
57
 
 
58
    def _get_audit_task_logs(self, context, begin=None, end=None,
 
59
                             before=None):
 
60
        """Returns a full log for all instance usage audit tasks on all
 
61
           computes.
 
62
 
 
63
        :param begin: datetime beginning of audit period to get logs for,
 
64
            Defaults to the beginning of the most recently completed
 
65
            audit period prior to the 'before' date.
 
66
        :param end: datetime ending of audit period to get logs for,
 
67
            Defaults to the ending of the most recently completed
 
68
            audit period prior to the 'before' date.
 
69
        :param before: By default we look for the audit period most recently
 
70
            completed before this datetime. Has no effect if both begin and end
 
71
            are specified.
 
72
        """
 
73
        defbegin, defend = utils.last_completed_audit_period(before=before)
 
74
        if begin is None:
 
75
            begin = defbegin
 
76
        if end is None:
 
77
            end = defend
 
78
        task_logs = db.task_log_get_all(context, "instance_usage_audit",
 
79
                                        begin, end)
 
80
        # We do this this way to include disabled compute services,
 
81
        # which can have instances on them. (mdragon)
 
82
        services = [svc for svc in db.service_get_all(context)
 
83
                    if svc['topic'] == 'compute']
 
84
        hosts = set(serv['host'] for serv in services)
 
85
        seen_hosts = set()
 
86
        done_hosts = set()
 
87
        running_hosts = set()
 
88
        total_errors = 0
 
89
        total_items = 0
 
90
        for tlog in task_logs:
 
91
            seen_hosts.add(tlog['host'])
 
92
            if tlog['state'] == "DONE":
 
93
                done_hosts.add(tlog['host'])
 
94
            if tlog['state'] == "RUNNING":
 
95
                running_hosts.add(tlog['host'])
 
96
            total_errors += tlog['errors']
 
97
            total_items += tlog['task_items']
 
98
        log = dict((tl['host'], dict(state=tl['state'],
 
99
                                  instances=tl['task_items'],
 
100
                                  errors=tl['errors'],
 
101
                                  message=tl['message']))
 
102
                  for tl in task_logs)
 
103
        missing_hosts = hosts - seen_hosts
 
104
        overall_status = "%s hosts done. %s errors." % (
 
105
                    'ALL' if len(done_hosts) == len(hosts)
 
106
                    else "%s of %s" % (len(done_hosts), len(hosts)),
 
107
                    total_errors)
 
108
        return dict(period_beginning=str(begin),
 
109
                    period_ending=str(end),
 
110
                    num_hosts=len(hosts),
 
111
                    num_hosts_done=len(done_hosts),
 
112
                    num_hosts_running=len(running_hosts),
 
113
                    num_hosts_not_run=len(missing_hosts),
 
114
                    hosts_not_run=list(missing_hosts),
 
115
                    total_instances=total_items,
 
116
                    total_errors=total_errors,
 
117
                    overall_status=overall_status,
 
118
                    log=log)
 
119
 
 
120
 
 
121
class Instance_usage_audit_log(extensions.ExtensionDescriptor):
 
122
    """Admin-only Task Log Monitoring"""
 
123
    name = "OSInstanceUsageAuditLog"
 
124
    alias = "os-instance_usage_audit_log"
 
125
    namespace = "http://docs.openstack.org/ext/services/api/v1.1"
 
126
    updated = "2012-07-06T01:00:00+00:00"
 
127
 
 
128
    def get_resources(self):
 
129
        ext = extensions.ResourceExtension('os-instance_usage_audit_log',
 
130
                                           InstanceUsageAuditLogController())
 
131
        return [ext]