Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / utils.py @ ce55f724

History | View | Annotate | Download (5.6 kB)

1
# Copyright 2011 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or without
4
# modification, are permitted provided that the following conditions
5
# are met:
6
#
7
#   1. Redistributions of source code must retain the above copyright
8
#      notice, this list of conditions and the following disclaimer.
9
#
10
#  2. Redistributions in binary form must reproduce the above copyright
11
#     notice, this list of conditions and the following disclaimer in the
12
#     documentation and/or other materials provided with the distribution.
13
#
14
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24
# SUCH DAMAGE.
25
#
26
# The views and conclusions contained in the software and documentation are
27
# those of the authors and should not be interpreted as representing official
28
# policies, either expressed or implied, of GRNET S.A.
29

    
30
# Utility functions
31

    
32
from synnefo.db.models import VirtualMachine, Network
33
from django.conf import settings
34
from copy import deepcopy
35

    
36

    
37
def id_from_instance_name(name):
38
    """Returns VirtualMachine's Django id, given a ganeti machine name.
39

40
    Strips the ganeti prefix atm. Needs a better name!
41

42
    """
43
    sname = str(name)
44
    if not sname.startswith(settings.BACKEND_PREFIX_ID):
45
        raise VirtualMachine.InvalidBackendIdError(sname)
46
    ns = sname.replace(settings.BACKEND_PREFIX_ID, "", 1)
47
    if not ns.isdigit():
48
        raise VirtualMachine.InvalidBackendIdError(sname)
49

    
50
    return int(ns)
51

    
52

    
53
def id_to_instance_name(id):
54
    return "%s%s" % (settings.BACKEND_PREFIX_ID, str(id))
55

    
56

    
57
def id_from_network_name(name):
58
    """Returns Network's Django id, given a ganeti machine name.
59

60
    Strips the ganeti prefix atm. Needs a better name!
61

62
    """
63
    if not str(name).startswith(settings.BACKEND_PREFIX_ID):
64
        raise Network.InvalidBackendIdError(str(name))
65
    ns = str(name).replace(settings.BACKEND_PREFIX_ID + 'net-', "", 1)
66
    if not ns.isdigit():
67
        raise Network.InvalidBackendIdError(str(name))
68

    
69
    return int(ns)
70

    
71

    
72
def id_to_network_name(id):
73
    return "%snet-%s" % (settings.BACKEND_PREFIX_ID, str(id))
74

    
75

    
76
def get_rsapi_state(vm):
77
    """Returns the API state for a virtual machine
78

79
    The API state for an instance of VirtualMachine is derived as follows:
80

81
    * If the deleted flag has been set, it is "DELETED".
82
    * Otherwise, it is a mapping of the last state reported by Ganeti
83
      (vm.operstate) through the RSAPI_STATE_FROM_OPER_STATE dictionary.
84

85
      The last state reported by Ganeti is set whenever Ganeti reports
86
      successful completion of an operation. If Ganeti says an
87
      OP_INSTANCE_STARTUP operation succeeded, vm.operstate is set to
88
      "STARTED".
89

90
    * To support any transitional states defined by the API (only REBOOT for
91
    the time being) this mapping is amended with information reported by Ganeti
92
    regarding any outstanding operation. If an OP_INSTANCE_STARTUP had
93
    succeeded previously and an OP_INSTANCE_REBOOT has been reported as in
94
    progress, the API state is "REBOOT".
95

96
    """
97
    try:
98
        r = VirtualMachine.RSAPI_STATE_FROM_OPER_STATE[vm.operstate]
99
    except KeyError:
100
        return "UNKNOWN"
101
    # A machine is DELETED if the deleted flag has been set
102
    if vm.deleted:
103
        return "DELETED"
104
    # A machine is in REBOOT if an OP_INSTANCE_REBOOT request is in progress
105
    in_reboot = (r == "ACTIVE") and\
106
                (vm.backendopcode == "OP_INSTANCE_REBOOT") and\
107
                (vm.backendjobstatus in ("queued", "waiting", "running"))
108
    if in_reboot:
109
        return "REBOOT"
110
    in_resize = (r == "STOPPED") and\
111
                (vm.backendopcode == "OP_INSTANCE_MODIFY") and\
112
                (vm.task == "RESIZE") and \
113
                (vm.backendjobstatus in ("queued", "waiting", "running"))
114
    if in_resize:
115
        return "RESIZE"
116
    return r
117

    
118

    
119
TASK_STATE_FROM_ACTION = {
120
    "BUILD": "BULDING",
121
    "START": "STARTING",
122
    "STOP": "STOPPING",
123
    "REBOOT": "REBOOTING",
124
    "DESTROY": "DESTROYING",
125
    "RESIZE": "RESIZING",
126
    "CONNECT": "CONNECTING",
127
    "DISCONNECT": "DISCONNECTING"}
128

    
129

    
130
def get_task_state(vm):
131
    if vm.task is None:
132
        return ""
133
    try:
134
        return TASK_STATE_FROM_ACTION[vm.task]
135
    except KeyError:
136
        return "UNKNOWN"
137

    
138

    
139
OPCODE_TO_ACTION = {
140
    "OP_INSTANCE_CREATE": "BUILD",
141
    "OP_INSTANCE_START": "START",
142
    "OP_INSTANCE_STOP": "STOP",
143
    "OP_INSTANCE_REBOOT": "REBOOT",
144
    "OP_INSTANCE_REMOVE": "DESTROY"}
145

    
146

    
147
def get_action_from_opcode(opcode, job_fields):
148
    if opcode == "OP_INSTANCE_SET_PARAMS":
149
        nics = job_fields.get("nics")
150
        beparams = job_fields.get("beparams")
151
        if nics:
152
            #TODO: check the nic format
153
            return "CONNECT" or "DISCONNECT"
154
        elif beparams:
155
            return "RESIZE"
156
        else:
157
            return None
158
    else:
159
        return OPCODE_TO_ACTION.get(opcode, None)
160

    
161

    
162
def hide_pass(kw):
163
    if 'osparams' in kw and 'img_passwd' in kw['osparams']:
164
        kw1 = deepcopy(kw)
165
        kw1['osparams']['img_passwd'] = 'x' * 8
166
        return kw1
167
    else:
168
        return kw