4576a2e2eb5756d75bc226d10ebb90b538d4230c
[invirt/packages/invirt-web.git] / code / controls.py
1 import validation
2 from invirt.common import CodeError, InvalidInput
3 import random
4 import sys
5 import time
6 import re
7 import cache_acls
8 import yaml
9
10 from invirt.config import structs as config
11 from invirt.database import Machine, Disk, Type, NIC, CDROM, session, meta
12 from invirt.remctl import remctl
13
14 # ... and stolen from xend/uuid.py
15 def randomUUID():
16     """Generate a random UUID."""
17
18     return [ random.randint(0, 255) for _ in range(0, 16) ]
19
20 def uuidToString(u):
21     """Turn a numeric UUID to a hyphen-seperated one."""
22     return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
23                      "%02x" * 6]) % tuple(u)
24 # end stolen code
25
26 def lvcreate(machine, disk):
27     """Create a single disk for a machine"""
28     remctl('web', 'lvcreate', machine.name,
29            disk.guest_device_name, str(disk.size))
30     
31 def makeDisks(machine):
32     """Update the lvm partitions to add a disk."""
33     for disk in machine.disks:
34         lvcreate(machine, disk)
35
36 def getswap(disksize, memsize):
37     """Returns the recommended swap partition size."""
38     return int(min(disksize / 4, memsize * 1.5))
39
40 def lvinstall(machine, autoinstall):
41     disksize = machine.disks[0].size
42     memsize = machine.memory
43     swapsize = getswap(disksize, memsize)
44     imagesize = disksize - swapsize
45     ip = machine.nics[0].ip
46     remctl('control', machine.name, 'install', 
47            'dist=%s' % autoinstall.distribution,
48            'mirror=%s' % autoinstall.mirror,
49            'imagesize=%s' % imagesize)
50
51 def lvcopy(machine_orig_name, machine, rootpw):
52     """Copy a golden image onto a machine's disk"""
53     remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
54
55 def bootMachine(machine, cdtype):
56     """Boot a machine with a given boot CD.
57
58     If cdtype is None, give no boot cd.  Otherwise, it is the string
59     id of the CD (e.g. 'gutsy_i386')
60     """
61     if cdtype is not None:
62         out, err = remctl('control', machine.name, 'create', 
63                           cdtype, err=True)
64     else:
65         out, err = remctl('control', machine.name, 'create',
66                           err=True)
67     if 'already running' in err:
68         raise InvalidInput('action', 'create',
69                            'VM %s is already on' % machine.name)
70     elif err:
71         raise CodeError('"%s" on "control %s create %s' 
72                         % (err, machine.name, cdtype))
73
74 def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
75     """Create a VM and put it in the database"""
76     # put stuff in the table
77     session.begin()
78     try:
79         validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
80         machine = Machine()
81         machine.name = name
82         machine.description = description
83         machine.memory = memory
84         machine.owner = owner
85         machine.administrator = owner
86         machine.contact = contact
87         machine.uuid = uuidToString(randomUUID())
88         machine.boot_off_cd = True
89         machine.type = machine_type
90         session.save_or_update(machine)
91         disk = Disk(machine=machine,
92                     guest_device_name='hda', size=disksize)
93         nic = NIC.query().filter_by(machine_id=None).first()
94         if not nic: #No IPs left!
95             raise CodeError("No IP addresses left!  "
96                             "Contact %s." % config.web.errormail)
97         nic.machine = machine
98         nic.hostname = name
99         session.save_or_update(nic)
100         session.save_or_update(disk)
101         cache_acls.refreshMachine(machine)
102         session.commit()
103     except:
104         session.rollback()
105         raise
106     makeDisks(machine)
107     if autoinstall:
108         lvinstall(machine, autoinstall)
109     else:
110         # tell it to boot with cdrom
111         bootMachine(machine, cdrom)
112     return machine
113
114 def getList():
115     """Return a dictionary mapping machine names to dicts."""
116     value_string = remctl('web', 'listvms')
117     value_dict = yaml.load(value_string, yaml.CSafeLoader)
118     return value_dict
119
120 def parseStatus(s):
121     """Parse a status string into nested tuples of strings.
122
123     s = output of xm list --long <machine_name>
124     """
125     values = re.split('([()])', s)
126     stack = [[]]
127     for v in values[2:-2]: #remove initial and final '()'
128         if not v:
129             continue
130         v = v.strip()
131         if v == '(':
132             stack.append([])
133         elif v == ')':
134             if len(stack[-1]) == 1:
135                 stack[-1].append('')
136             stack[-2].append(stack[-1])
137             stack.pop()
138         else:
139             if not v:
140                 continue
141             stack[-1].extend(v.split())
142     return stack[-1]
143
144 def statusInfo(machine):
145     """Return the status list for a given machine.
146
147     Gets and parses xm list --long
148     """
149     value_string, err_string = remctl('control', machine.name, 'list-long', 
150                                       err=True)
151     if 'Unknown command' in err_string:
152         raise CodeError("ERROR in remctl list-long %s is not registered" % 
153                         (machine.name,))
154     elif 'is not on' in err_string:
155         return None
156     elif err_string:
157         raise CodeError("ERROR in remctl list-long %s:  %s" % 
158                         (machine.name, err_string))
159     status = parseStatus(value_string)
160     return status
161
162 def listHost(machine):
163     """Return the host a machine is running on"""
164     out, err = remctl('control', machine.name, 'listhost', err=True)
165     if err:
166         return None
167     return out.strip()
168
169 def deleteVM(machine):
170     """Delete a VM."""
171     remctl('control', machine.name, 'destroy', err=True)
172     session.begin()
173     delete_disk_pairs = [(machine.name, d.guest_device_name) 
174                          for d in machine.disks]
175     try:
176         for mname, dname in delete_disk_pairs:
177             remctl('web', 'lvremove', mname, dname)
178         for nic in machine.nics:
179             nic.machine_id = None
180             nic.hostname = None
181             session.save_or_update(nic)
182         for disk in machine.disks:
183             session.delete(disk)
184         session.delete(machine)
185         session.commit()
186     except:
187         session.rollback()
188         raise
189
190 def commandResult(username, state, fields):
191     start_time = 0
192     machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
193     action = fields.getfirst('action')
194     cdrom = fields.getfirst('cdrom')
195     if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
196         raise CodeError("Invalid cdrom type '%s'" % cdrom)    
197     if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', 
198                       'Delete VM'):
199         raise CodeError("Invalid action '%s'" % action)
200     if action == 'Reboot':
201         if cdrom is not None:
202             out, err = remctl('control', machine.name, 'reboot', cdrom,
203                               err=True)
204         else:
205             out, err = remctl('control', machine.name, 'reboot',
206                               err=True)
207         if err:
208             if re.match("machine '.*' is not on", err):
209                 raise InvalidInput("action", "reboot", 
210                                    "Machine is not on")
211             else:
212                 print >> sys.stderr, 'Error on reboot:'
213                 print >> sys.stderr, err
214                 raise CodeError('ERROR on remctl')
215                 
216     elif action == 'Power on':
217         if validation.maxMemory(username, state, machine) < machine.memory:
218             raise InvalidInput('action', 'Power on',
219                                "You don't have enough free RAM quota "
220                                "to turn on this machine.")
221         bootMachine(machine, cdrom)
222     elif action == 'Power off':
223         out, err = remctl('control', machine.name, 'destroy', err=True)
224         if err:
225             if re.match("machine '.*' is not on", err):
226                 raise InvalidInput("action", "Power off", 
227                                    "Machine is not on.")
228             else:
229                 print >> sys.stderr, 'Error on power off:'
230                 print >> sys.stderr, err
231                 raise CodeError('ERROR on remctl')
232     elif action == 'Shutdown':
233         out, err = remctl('control', machine.name, 'shutdown', err=True)
234         if err:
235             if re.match("machine '.*' is not on", err):
236                 raise InvalidInput("action", "Shutdown", 
237                                    "Machine is not on.")
238             else:
239                 print >> sys.stderr, 'Error on Shutdown:'
240                 print >> sys.stderr, err
241                 raise CodeError('ERROR on remctl')
242     elif action == 'Delete VM':
243         deleteVM(machine)
244
245     d = dict(user=username,
246              command=action,
247              machine=machine)
248     return d
249
250 def resizeDisk(machine_name, disk_name, new_size):
251     remctl("web", "lvresize", machine_name, disk_name, new_size)
252
253 def renameMachine(machine, old_name, new_name):
254     for disk in machine.disks:
255         remctl("web", "lvrename", old_name, 
256                disk.guest_device_name, new_name)
257