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