node.py 10.3 KB
Newer Older
1
from __future__ import absolute_import, unicode_literals
Őry Máté committed
2 3 4
from logging import getLogger

from django.db.models import (
5
    CharField, IntegerField, ForeignKey, BooleanField, ManyToManyField,
6
    FloatField, permalink,
Őry Máté committed
7 8 9 10 11 12 13
)
from django.utils.translation import ugettext_lazy as _

from celery.exceptions import TimeoutError
from model_utils.models import TimeStampedModel
from taggit.managers import TaggableManager

14
from common.models import method_cache, WorkerNotFound
Őry Máté committed
15 16
from firewall.models import Host
from ..tasks import vm_tasks
17
from .common import Trait
Őry Máté committed
18

19
from .activity import node_activity, NodeActivity
20

Gregory Nagy committed
21 22
from monitor.calvin.calvin import Query
from monitor.calvin.calvin import GraphiteHandler
23
from django.utils import timezone
24

Őry Máté committed
25 26 27
logger = getLogger(__name__)


28 29 30 31 32 33 34 35 36 37 38
def node_available(function):
    """Decorate methods to ignore disabled Nodes.
    """
    def decorate(self, *args, **kwargs):
        if self.enabled is True and self.online is True:
            return function(self, *args, **kwargs)
        else:
            return None
    return decorate


Őry Máté committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
class Node(TimeStampedModel):

    """A VM host machine, a hypervisor.
    """
    name = CharField(max_length=50, unique=True,
                     verbose_name=_('name'),
                     help_text=_('Human readable name of node.'))
    priority = IntegerField(verbose_name=_('priority'),
                            help_text=_('Node usage priority.'))
    host = ForeignKey(Host, verbose_name=_('host'),
                      help_text=_('Host in firewall.'))
    enabled = BooleanField(verbose_name=_('enabled'), default=False,
                           help_text=_('Indicates whether the node can '
                                       'be used for hosting.'))
    traits = ManyToManyField(Trait, blank=True,
                             help_text=_("Declared traits."),
                             verbose_name=_('traits'))
    tags = TaggableManager(blank=True, verbose_name=_("tags"))
    overcommit = FloatField(default=1.0, verbose_name=_("overcommit ratio"),
                            help_text=_("The ratio of total memory with "
                                        "to without overcommit."))

    class Meta:
        app_label = 'vm'
        db_table = 'vm_node'
        permissions = ()

Őry Máté committed
66 67 68
    def __unicode__(self):
        return self.name

69
    @method_cache(10)
70
    def get_online(self):
71
        """Check if the node is online.
Őry Máté committed
72

73
        Check if node is online by queue is available.
74 75
        """
        try:
76 77
            self.get_remote_queue_name("vm")
        except:
78
            return False
79 80
        else:
            return True
Őry Máté committed
81

82 83
    online = property(get_online)

84
    @node_available
Őry Máté committed
85
    @method_cache(300)
86
    def get_num_cores(self):
Őry Máté committed
87 88
        """Number of CPU threads available to the virtual machines.
        """
89

90
        return self.remote_query(vm_tasks.get_core_num, default=0)
91

92 93
    num_cores = property(get_num_cores)

94 95
    @property
    def state(self):
96
        """The state combined of online and enabled attributes.
97
        """
98
        if self.enabled and self.online:
99
            return 'ONLINE'
100
        elif self.enabled and not self.online:
101
            return 'MISSING'
102
        elif not self.enabled and self.online:
103
            return 'DISABLED'
104
        else:
105
            return 'OFFLINE'
106 107 108

    def disable(self, user=None):
        ''' Disable the node.'''
109 110 111 112
        if self.enabled is True:
            with node_activity(code_suffix='disable', node=self, user=user):
                self.enabled = False
                self.save()
113 114 115

    def enable(self, user=None):
        ''' Enable the node. '''
116 117 118 119 120 121
        if self.enabled is not True:
            with node_activity(code_suffix='enable', node=self, user=user):
                self.enabled = True
                self.save()
            self.get_num_cores(invalidate_cache=True)
            self.get_ram_size(invalidate_cache=True)
Őry Máté committed
122

123
    @node_available
Őry Máté committed
124
    @method_cache(300)
125
    def get_ram_size(self):
Őry Máté committed
126 127
        """Bytes of total memory in the node.
        """
128
        return self.remote_query(vm_tasks.get_ram_size, default=0)
Őry Máté committed
129

130 131
    ram_size = property(get_ram_size)

Őry Máté committed
132
    @property
133
    @node_available
Őry Máté committed
134 135 136 137 138
    def ram_size_with_overcommit(self):
        """Bytes of total memory including overcommit margin.
        """
        return self.ram_size * self.overcommit

139
    @method_cache(30)
Őry Máté committed
140
    def get_remote_queue_name(self, queue_id):
141 142
        """Return the name of the remote celery queue for this node.

143
        throws Exception if there is no worker on the queue.
144
        Until the cache provide reult there can be dead queues.
145
        """
146

147
        if vm_tasks.check_queue(self.host.hostname, queue_id):
148
            self.node_online()
149 150
            return self.host.hostname + "." + queue_id
        else:
151 152
            if self.enabled is True:
                self.node_offline()
153
            raise WorkerNotFound()
Őry Máté committed
154

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    def node_online(self):
        """Create activity and log entry when node reappears.
        """

        try:
            act = self.activity_log.order_by('-pk')[0]
        except IndexError:
            pass  # no monitoring activity at all
        else:
            logger.debug("The last activity was %s" % act)
            if act.activity_code.endswith("offline"):
                act = NodeActivity.create(code_suffix='monitor_succes_online',
                                          node=self, user=None)
                act.started = timezone.now()
                act.finished = timezone.now()
                act.succeeded = True
                act.save()
                logger.info("Node %s is ONLINE." % self.name)
                self.get_num_cores(invalidate_cache=True)
                self.get_ram_size(invalidate_cache=True)

    def node_offline(self):
        """Called when a node disappears.

        If the node is not already offline, record an activity and a log entry.
        """

        try:
            act = self.activity_log.order_by('-pk')[0]
        except IndexError:
            pass  # no activity at all
        else:
            logger.debug("The last activity was %s" % act)
            if act.activity_code.endswith("offline"):
                return
        act = NodeActivity.create(code_suffix='monitor_failed_offline',
                                  node=self, user=None)
        act.started = timezone.now()
        act.finished = timezone.now()
        act.succeeded = False
        act.save()
        logger.critical("Node %s is OFFLINE%s.", self.name,
                        ", but enabled" if self.enabled else "")
        # TODO: check if we should reschedule any VMs?

200
    def remote_query(self, task, timeout=30, raise_=False, default=None):
Őry Máté committed
201 202
        """Query the given task, and get the result.

203 204 205 206
        If the result is not ready or worker not reachable
        in timeout secs, return default value or raise a
        TimeoutError or WorkerNotFound exception.
        """
Őry Máté committed
207
        try:
208 209
            r = task.apply_async(
                queue=self.get_remote_queue_name('vm'), expires=timeout + 60)
Őry Máté committed
210
            return r.get(timeout=timeout)
211
        except (TimeoutError, WorkerNotFound):
Őry Máté committed
212 213 214 215 216
            if raise_:
                raise
            else:
                return default

217
    @node_available
218
    def get_monitor_info(self):
219 220
        try:
            handler = GraphiteHandler()
221 222 223
        except RuntimeError:
            return self.remote_query(vm_tasks.get_node_metrics, 30)

224
        query = Query()
Gregory Nagy committed
225 226 227
        query.set_target(self.host.hostname + ".circle")
        query.set_format("json")
        query.set_relative_start(5, "minutes")
228

229
        metrics = ["cpu.usage", "memory.usage"]
230
        for metric in metrics:
Gregory Nagy committed
231
            query.set_metric(metric)
232 233 234
            query.generate()
            handler.put(query)
            handler.send()
235 236

        collected = {}
237
        for metric in metrics:
Gregory Nagy committed
238
            response = handler.pop()
239 240 241 242
            try:
                cache = response[0]["datapoints"][-1][0]
            except (IndexError, KeyError):
                cache = 0
243 244 245 246 247
            if cache is None:
                cache = 0
            collected[metric] = cache
        return collected

248
    @property
249
    @node_available
250
    def cpu_usage(self):
251
        return float(self.get_monitor_info()["cpu.usage"]) / 100
252

253
    @property
254
    @node_available
255
    def ram_usage(self):
256
        return float(self.get_monitor_info()["memory.usage"]) / 100
257

258
    @property
259
    @node_available
260 261 262
    def byte_ram_usage(self):
        return self.ram_usage * self.ram_size

263
    @node_available
Őry Máté committed
264
    def update_vm_states(self):
265 266 267 268 269
        """Update state of Instances running on this Node.

        Query state of all libvirt domains, and notify Instances by their
        vm_state_changed hook.
        """
Őry Máté committed
270
        domains = {}
271 272 273 274 275
        domain_list = self.remote_query(vm_tasks.list_domains_info, timeout=5)
        if domain_list is None:
            logger.info("Monitoring failed at: %s", self.name)
            return
        for i in domain_list:
Őry Máté committed
276 277 278 279 280 281 282 283
            # [{'name': 'cloud-1234', 'state': 'RUNNING', ...}, ...]
            try:
                id = int(i['name'].split('-')[1])
            except:
                pass  # name format doesn't match
            else:
                domains[id] = i['state']

284 285
        instances = [{'id': i.id, 'state': i.state}
                     for i in self.instance_set.order_by('id').all()]
Őry Máté committed
286 287 288 289 290 291
        for i in instances:
            try:
                d = domains[i['id']]
            except KeyError:
                logger.info('Node %s update: instance %s missing from '
                            'libvirt', self, i['id'])
292 293
                # Set state to STOPPED when instance is missing
                self.instance_set.get(id=i['id']).vm_state_changed('STOPPED')
Őry Máté committed
294 295 296 297 298
            else:
                if d != i['state']:
                    logger.info('Node %s update: instance %s state changed '
                                '(libvirt: %s, db: %s)',
                                self, i['id'], d, i['state'])
299
                    self.instance_set.get(id=i['id']).vm_state_changed(d)
Őry Máté committed
300 301 302 303 304

                del domains[i['id']]
        for i in domains.keys():
            logger.info('Node %s update: domain %s in libvirt but not in db.',
                        self, i)
305 306 307

    @classmethod
    def get_state_count(cls, online, enabled):
308 309
        return len([1 for i in cls.objects.filter(enabled=enabled).all()
                    if i.online == online])
310 311 312 313

    @permalink
    def get_absolute_url(self):
        return ('dashboard.views.node-detail', None, {'pk': self.id})