Statistics
| Branch: | Tag: | Revision:

root / logic / utils.py @ fc30c430

History | View | Annotate | Download (2.3 kB)

1
#
2
# Utility functions
3
#
4
# Various functions
5
#
6
# Copyright 2010 Greek Research and Technology Network
7
#
8

    
9
from synnefo.db.models import VirtualMachine
10
from synnefo.logic import credits
11

    
12
import synnefo.settings as settings
13

    
14
def id_from_instance_name(name):
15
    """Returns VirtualMachine's Django id, given a ganeti machine name.
16

17
    Strips the ganeti prefix atm. Needs a better name!
18

19
    """
20
    if not str(name).startswith(settings.BACKEND_PREFIX_ID):
21
        raise VirtualMachine.InvalidBackendIdError(str(name))
22
    ns = str(name).lstrip(settings.BACKEND_PREFIX_ID)
23
    if not ns.isdigit():
24
        raise VirtualMachine.InvalidBackendIdError(str(name))
25

    
26
    return int(ns)
27

    
28
def get_rsapi_state(vm):
29
    """Returns the API state for a virtual machine
30
    
31
    The API state for an instance of VirtualMachine is derived as follows:
32

33
    * If the deleted flag has been set, it is "DELETED".
34
    * Otherwise, it is a mapping of the last state reported by Ganeti
35
      (vm.operstate) through the RSAPI_STATE_FROM_OPER_STATE dictionary.
36
      
37
      The last state reported by Ganeti is set whenever Ganeti reports
38
      successful completion of an operation. If Ganeti says an OP_INSTANCE_STARTUP
39
      operation succeeded, vm.operstate is set to "STARTED".
40

41
    * To support any transitive states defined by the API (only REBOOT for the time
42
      being) this mapping is amended with information reported by Ganeti regarding
43
      any outstanding operation. If an OP_INSTANCE_STARTUP had succeeded previously
44
      and an OP_INSTANCE_REBOOT has been reported as in progress, the API state is
45
      "REBOOT".
46

47
    """
48
    try:
49
        r = VirtualMachine.RSAPI_STATE_FROM_OPER_STATE[vm.operstate]
50
    except KeyError:
51
        return "UNKNOWN"
52
    # A machine is DELETED if the deleted flag has been set
53
    if vm.deleted:
54
        return "DELETED"
55
    # A machine is in REBOOT if an OP_INSTANCE_REBOOT request is in progress
56
    if r == 'ACTIVE' and vm.backendopcode == 'OP_INSTANCE_REBOOT' and \
57
        vm.backendjobstatus in ('queued', 'waiting', 'running'):
58
        return "REBOOT"
59
    return r
60

    
61
def update_state(vm, new_operstate):
62
    """Wrapper around updates of the VirtualMachine.operstate field"""
63

    
64
    # Call charge() unconditionally before any change of
65
    # internal state.
66
    credits.charge(vm)
67
    vm.operstate = new_operstate