-
Notifications
You must be signed in to change notification settings - Fork 478
/
vm.py
342 lines (287 loc) · 11.6 KB
/
vm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
from middlewared.schema import accepts, Int, Str, Dict, List, Bool, Patch
from middlewared.service import filterable, CRUDService, private
from middlewared.utils import Nid, Popen
import errno
import gevent
import netif
import os
import subprocess
import sysctl
class VMManager(object):
def __init__(self, service):
self.service = service
self.logger = self.service.logger
self._vm = {}
def start(self, id):
vm = self.service.query([('id', '=', id)], {'get': True})
self._vm[id] = VMSupervisor(self, vm)
try:
gevent.spawn(self._vm[id].run)
return True
except:
raise
def stop(self, id):
supervisor = self._vm.get(id)
if not supervisor:
return False
return supervisor.stop()
def status(self, id):
supervisor = self._vm.get(id)
if supervisor and supervisor.running():
return {
'state': 'RUNNING',
}
else:
return {
'state': 'STOPPED',
}
class VMSupervisor(object):
def __init__(self, manager, vm):
self.manager = manager
self.logger = self.manager.logger
self.vm = vm
self.proc = None
self.taps = []
self.bhyve_error = None
def run(self):
args = [
'bhyve',
'-A',
'-P',
'-H',
'-c', str(self.vm['vcpus']),
'-m', str(self.vm['memory']),
'-s', '0:0,hostbridge',
'-s', '31,lpc',
'-l', 'com1,/dev/nmdm{}A'.format(self.vm['id']),
]
if self.vm['bootloader'] in ('UEFI', 'UEFI_CSM'):
args += [
'-l', 'bootrom,/usr/local/share/uefi-firmware/BHYVE_UEFI{}.fd'.format('_CSM' if self.vm['bootloader'] == 'UEFI_CSM' else ''),
]
nid = Nid(3)
for device in self.vm['devices']:
if device['dtype'] == 'DISK':
if device['attributes'].get('type') == 'AHCI':
args += ['-s', '{},ahci-hd,{}'.format(nid(), device['attributes']['path'])]
else:
args += ['-s', '{},virtio-blk,{}'.format(nid(), device['attributes']['path'])]
elif device['dtype'] == 'CDROM':
args += ['-s', '{},ahci-cd,{}'.format(nid(), device['attributes']['path'])]
elif device['dtype'] == 'NIC':
tapname = netif.create_interface('tap')
tap = netif.get_interface(tapname)
tap.up()
self.taps.append(tapname)
# If Bridge
if True:
bridge = None
for name, iface in list(netif.list_interfaces().items()):
if name.startswith('bridge'):
bridge = iface
break
if not bridge:
bridge = netif.get_interface(netif.create_interface('bridge'))
bridge.add_member(tapname)
defiface = Popen("route -nv show default|grep -w interface|awk '{ print $2 }'", stdout=subprocess.PIPE, shell=True).communicate()[0].strip()
if defiface and defiface not in bridge.members:
bridge.add_member(defiface)
bridge.up()
if device['attributes'].get('type') == 'VIRTIO':
nictype = 'virtio-net'
else:
nictype = 'e1000'
mac_address = device['attributes'].get('mac')
if mac_address == '00:a0:98:FF:FF:FF':
args += ['-s', '{},{},{}'.format(nid(), nictype, tapname)]
else:
args += ['-s', '{},{},{},mac={}'.format(nid(), nictype, tapname, mac_address)]
elif device['dtype'] == 'VNC':
if device['attributes'].get('wait'):
wait = 'wait'
else:
wait = ''
vnc_resolution = device['attributes'].get('vnc_resolution').split('x')
width = vnc_resolution[0]
height = vnc_resolution[1]
vnc_port = int(device['attributes'].get('vnc_port', 5900 + self.vm['id']))
args += [
'-s', '29,fbuf,tcp=0.0.0.0:{},w={},h={},{}'.format(vnc_port, width, height, wait),
'-s', '30,xhci,tablet',
]
args.append(self.vm['name'])
self.logger.debug('Starting bhyve: {}'.format(' '.join(args)))
self.proc = Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in self.proc.stdout:
self.logger.debug('{}: {}'.format(self.vm['name'], line))
# bhyve returns the following status code:
# 0 - VM has been reset
# 1 - VM has been powered off
# 2 - VM has been halted
# 3 - VM generated a triple fault
# all other non-zero status codes are errors
self.bhyve_error = self.proc.wait()
if self.bhyve_error == 0:
self.logger.info("===> REBOOTING VM: {0} ID: {1} BHYVE_CODE: {2}".format(self.vm['name'], self.vm['id'], self.bhyve_error))
self.manager.stop(self.vm['id'])
self.manager.start(self.vm['id'])
elif self.bhyve_error in (1, 2, 3):
self.logger.info("===> STOPPING VM: {0} ID: {1} BHYVE_CODE: {2}".format(self.vm['name'], self.vm['id'], self.bhyve_error))
self.manager.stop(self.vm['id'])
elif self.bhyve_error not in (0, 1, 2, 3, None):
self.logger.info("===> ERROR VM: {0} ID: {1} BHYVE_CODE: {2}".format(self.vm['name'], self.vm['id'], self.bhyve_error))
self.destroy_vm()
def destroy_vm(self):
self.logger.warn("===> DESTROYING VM: {0} ID: {1} BHYVE_CODE: {2}".format(self.vm['name'], self.vm['id'], self.bhyve_error))
# XXX: We need to catch the bhyvectl return error.
bhyve_error = Popen(['bhyvectl', '--destroy', '--vm={}'.format(self.vm['name'])], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait()
self.manager._vm.pop(self.vm['id'], None)
self.destroy_tap()
def destroy_tap(self):
while self.taps:
netif.destroy_interface(self.taps.pop())
def stop(self):
if self.proc:
try:
os.kill(self.proc.pid, 15)
except ProcessLookupError as e:
# Already stopped, process do not exist anymore
if e.errno != errno.ESRCH:
raise
# XXX: For now we destroy the VM, but we need to be able to wake up it after stop.
self.destroy_vm()
return True
def running(self):
if self.proc:
try:
os.kill(self.proc.pid, 0)
except OSError:
return False
return True
return False
class VMService(CRUDService):
class Config:
namespace = 'vm'
def __init__(self, *args, **kwargs):
super(VMService, self).__init__(*args, **kwargs)
self._manager = VMManager(self)
@accepts()
def flags(self):
"""Returns a dictionary with CPU flags for bhyve."""
data = {}
vmx = sysctl.filter('hw.vmm.vmx.initialized')
data['intel_vmx'] = True if vmx and vmx[0].value else False
ug = sysctl.filter('hw.vmm.vmx.cap.unrestricted_guest')
data['unrestricted_guest'] = True if ug and ug[0].value else False
rvi = sysctl.filter('hw.vmm.svm.features')
data['amd_rvi'] = True if rvi and rvi[0].value != 0 else False
asids = sysctl.filter('hw.vmm.svm.num_asids')
data['amd_asids'] = True if asids and asids[0].value != 0 else False
return data
@filterable
def query(self, filters=None, options=None):
options = options or {}
options['extend'] = 'vm._extend_vm'
return self.middleware.call('datastore.query', 'vm.vm', filters, options)
def _extend_vm(self, vm):
vm['devices'] = []
for device in self.middleware.call('datastore.query', 'vm.device', [('vm__id', '=', vm['id'])]):
device.pop('id', None)
device.pop('vm', None)
vm['devices'].append(device)
return vm
@accepts(Dict(
'vm_create',
Str('name'),
Str('description'),
Int('vcpus'),
Int('memory'),
Str('bootloader'),
List('devices'),
Bool('autostart'),
register=True,
))
def do_create(self, data):
"""Create a VM."""
devices = data.pop('devices')
pk = self.middleware.call('datastore.insert', 'vm.vm', data)
for device in devices:
device['vm'] = pk
self.middleware.call('datastore.insert', 'vm.device', device)
return pk
@private
def do_update_devices(self, id, devices):
if devices and isinstance(devices, list) is True:
device_query = self.middleware.call('datastore.query', 'vm.device', [('vm__id', '=', int(id))])
# Make sure both list has the same size.
if len(device_query) != len(devices):
return False
get_devices = []
for q in device_query:
q.pop('vm')
get_devices.append(q)
while len(devices) > 0:
update_item = devices.pop(0)
old_item = get_devices.pop(0)
if old_item['dtype'] == update_item['dtype']:
old_item['attributes'] = update_item['attributes']
device_id = old_item.pop('id')
self.middleware.call('datastore.update', 'vm.device', device_id, old_item)
return True
@accepts(Int('id'), Patch(
'vm_create',
'vm_update',
('attr', {'update': True}),
))
def do_update(self, id, data):
"""Update all information of a specific VM."""
devices = data.pop('devices', None)
if devices:
update_devices = self.do_update_devices(id, devices)
if data:
return self.middleware.call('datastore.update', 'vm.vm', id, data)
else:
return update_devices
@accepts(Int('id'))
def do_delete(self, id):
"""Delete a VM."""
return self.middleware.call('datastore.delete', 'vm.vm', id)
@accepts(Int('id'))
def start(self, id):
"""Start a VM."""
return self._manager.start(id)
@accepts(Int('id'))
def stop(self, id):
"""Stop a VM."""
return self._manager.stop(id)
@accepts(Int('id'))
def status(self, id):
"""Get the status of a VM, if it is RUNNING or STOPPED."""
return self._manager.status(id)
@accepts(Int('id'))
def restart(self, id):
""" Restart a VM."""
stop_vm = self.stop(id)
if stop_vm is True:
start_vm = self.start(id)
return start_vm
else:
return stop_vm
def kmod_load():
kldstat = Popen(['/sbin/kldstat'], stdout=subprocess.PIPE).communicate()[0]
if 'vmm.ko' not in kldstat:
Popen(['/sbin/kldload', 'vmm'])
if 'nmdm.ko' not in kldstat:
Popen(['/sbin/kldload', 'nmdm'])
def _event_system_ready(middleware, event_type, args):
"""
Method called when system is ready, supposed to start VMs
flagged that way.
"""
if args['id'] != 'ready':
return
for vm in middleware.call('vm.query', [('autostart', '=', True)]):
middleware.call('vm.start', vm['id'])
def setup(middleware):
gevent.spawn(kmod_load)
middleware.event_subscribe('system', _event_system_ready)