graph.py 8.67 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import absolute_import, unicode_literals

import logging
import requests

from django.conf import settings
24
from django.core.exceptions import PermissionDenied
25
from django.http import HttpResponse, Http404
26
from django.utils.translation import ugettext_lazy as _
27 28
from django.views.generic import View

29
from braces.views import LoginRequiredMixin
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

from vm.models import Instance, Node


logger = logging.getLogger(__name__)


def register_graph(metric_cls, graph_name, graphview_cls):
    if not hasattr(graphview_cls, 'metrics'):
        graphview_cls.metrics = {}
    graphview_cls.metrics[graph_name] = metric_cls


class GraphViewBase(LoginRequiredMixin, View):
    def create_class(self, cls):
        return type(str(cls.__name__ + 'Metric'), (cls, self.base), {})

    def get(self, request, pk, metric, time, *args, **kwargs):
        graphite_url = settings.GRAPHITE_URL
        if graphite_url is None:
            raise Http404()

        try:
            metric = self.metrics[metric]
        except KeyError:
55
            raise Http404()
56 57 58 59 60 61 62 63 64

        try:
            instance = self.get_object(request, pk)
        except self.model.DoesNotExist:
            raise Http404()

        metric = self.create_class(metric)(instance)

        return HttpResponse(metric.get_graph(graphite_url, time),
Bach Dániel committed
65
                            content_type="image/png")
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

    def get_object(self, request, pk):
        instance = self.model.objects.get(id=pk)
        if not instance.has_level(request.user, 'user'):
            raise PermissionDenied()
        return instance


class Metric(object):
    cacti_style = True
    derivative = False
    scale_to_seconds = None
    metric_name = None
    title = None
    label = None

    def __init__(self, obj, metric_name=None):
        self.obj = obj
        self.metric_name = (
            metric_name or self.metric_name or self.__class__.__name__.lower())

    def get_metric_name(self):
        return self.metric_name

    def get_label(self):
        return self.label or self.get_metric_name()

    def get_title(self):
        return self.title or self.get_metric_name()

    def get_minmax(self):
        return (None, None)

    def get_target(self):
        target = '%s.%s' % (self.obj.metric_prefix, self.get_metric_name())
        if self.derivative:
            target = 'nonNegativeDerivative(%s)' % target
        if self.scale_to_seconds:
            target = 'scaleToSeconds(%s, %d)' % (target, self.scale_to_seconds)
        target = 'alias(%s, "%s")' % (target, self.get_label())
        if self.cacti_style:
            target = 'cactiStyle(%s)' % target
        return target

    def get_graph(self, graphite_url, time, width=500, height=200):
        params = {'target': self.get_target(),
                  'from': '-%s' % time,
                  'title': self.get_title().encode('UTF-8'),
                  'width': width,
                  'height': height}

        ymin, ymax = self.get_minmax()
        if ymin is not None:
            params['yMin'] = ymin
        if ymax is not None:
            params['yMax'] = ymax

        logger.debug('%s %s', graphite_url, params)
        response = requests.get('%s/render/' % graphite_url, params=params)
        return response.content


class VmMetric(Metric):
    def get_title(self):
        title = super(VmMetric, self).get_title()
        return '%s (%s) - %s' % (self.obj.name, self.obj.vm_name, title)


class NodeMetric(Metric):
    def get_title(self):
        title = super(NodeMetric, self).get_title()
        return '%s (%s) - %s' % (self.obj.name, self.obj.host.hostname, title)


class VmGraphView(GraphViewBase):
    model = Instance
    base = VmMetric


145
class NodeGraphView(GraphViewBase):
146 147 148 149
    model = Node
    base = NodeMetric

    def get_object(self, request, pk):
150 151
        if not self.request.user.has_perm('vm.view_statistics'):
            raise PermissionDenied()
152 153 154
        return self.model.objects.get(id=pk)


155
class NodeListGraphView(GraphViewBase):
156 157 158 159
    model = Node
    base = Metric

    def get_object(self, request, pk):
160 161
        if not self.request.user.has_perm('vm.view_statistics'):
            raise PermissionDenied()
162 163 164
        return Node.objects.filter(enabled=True)

    def get(self, request, metric, time, *args, **kwargs):
165 166
        if not self.request.user.has_perm('vm.view_statistics'):
            raise PermissionDenied()
167 168 169 170 171
        return super(NodeListGraphView, self).get(request, None, metric, time)


class Ram(object):
    metric_name = "memory.usage"
172 173
    title = _("RAM usage (%)")
    label = _("RAM usage (%)")
174 175 176 177 178 179 180 181 182 183

    def get_minmax(self):
        return (0, 105)

register_graph(Ram, 'memory', VmGraphView)
register_graph(Ram, 'memory', NodeGraphView)


class Cpu(object):
    metric_name = "cpu.percent"
184 185
    title = _("CPU usage (%)")
    label = _("CPU usage (%)")
186 187 188 189 190 191 192 193 194 195 196 197

    def get_minmax(self):
        if isinstance(self.obj, Node):
            return (0, 105)
        else:
            return (0, self.obj.num_cores * 100 + 5)

register_graph(Cpu, 'cpu', VmGraphView)
register_graph(Cpu, 'cpu', NodeGraphView)


class VmNetwork(object):
198
    title = _("Network")
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

    def get_minmax(self):
        return (0, None)

    def get_target(self):
        metrics = []
        for n in self.obj.interface_set.all():
            params = (self.obj.metric_prefix, n.vlan.vid, n.vlan.name)
            metrics.append(
                'alias(scaleToSeconds(nonNegativeDerivative('
                '%s.network.bytes_recv-%s), 10), "out - %s (bits/s)")' % (
                    params))
            metrics.append(
                'alias(scaleToSeconds(nonNegativeDerivative('
                '%s.network.bytes_sent-%s), 10), "in - %s (bits/s)")' % (
                    params))
        return 'group(%s)' % ','.join(metrics)

register_graph(VmNetwork, 'network', VmGraphView)


class NodeNetwork(object):
221
    title = _("Network")
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

    def get_minmax(self):
        return (0, None)

    def get_target(self):
        return (
            'aliasSub(scaleToSeconds(nonNegativeDerivative(%s.network.b*),'
            '10), ".*\.bytes_(sent|recv)-([a-zA-Z0-9]+).*", "\\2 \\1")' % (
                self.obj.metric_prefix))

register_graph(NodeNetwork, 'network', NodeGraphView)


class NodeVms(object):
    metric_name = "vmcount"
237 238
    title = _("Instance count")
    label = _("instance count")
239 240 241 242 243 244 245 246

    def get_minmax(self):
        return (0, None)

register_graph(NodeVms, 'vm', NodeGraphView)


class NodeAllocated(object):
247
    title = _("Allocated memory (bytes)")
248 249 250

    def get_target(self):
        prefix = self.obj.metric_prefix
251
        if self.obj.online and self.obj.enabled:
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
            ram_size = self.obj.ram_size
        else:
            ram_size = 0
        used = 'alias(%s.memory.used_bytes, "used")' % prefix
        allocated = 'alias(%s.memory.allocated, "allocated")' % prefix
        max = 'threshold(%d, "max")' % ram_size
        return 'cactiStyle(group(%s, %s, %s))' % (used, allocated, max)

    def get_minmax(self):
        return (0, None)

register_graph(NodeAllocated, 'alloc', NodeGraphView)


class NodeListAllocated(object):
267
    title = _("Allocated memory (bytes)")
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

    def get_target(self):
        nodes = self.obj
        used = ','.join('%s.memory.used_bytes' % n.metric_prefix
                        for n in nodes)
        allocated = 'alias(sumSeries(%s), "allocated")' % ','.join(
            '%s.memory.allocated' % n.metric_prefix for n in nodes)
        max = 'threshold(%d, "max")' % sum(
            n.ram_size for n in nodes if n.online)
        return ('group(aliasSub(aliasByNode(stacked(group(%s)), 1), "$",'
                '"  (used)"), %s, %s)' % (used, allocated, max))

    def get_minmax(self):
        return (0, None)

register_graph(NodeListAllocated, 'alloc', NodeListGraphView)


class NodeListVms(object):
287
    title = _("Instance count")
288 289 290 291 292 293 294 295 296

    def get_target(self):
        vmcount = ','.join('%s.vmcount' % n.metric_prefix for n in self.obj)
        return 'group(aliasByNode(stacked(group(%s)), 1))' % vmcount

    def get_minmax(self):
        return (0, None)

register_graph(NodeListVms, 'vm', NodeListGraphView)