-
Notifications
You must be signed in to change notification settings - Fork 0
/
KVM_plugin
executable file
·1150 lines (940 loc) · 55.2 KB
/
KVM_plugin
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) 2014,2020 ADLINK Technology Inc.
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors: Gabriele Baldoni, ADLINK Technology Inc. - Base plugins set
import sys
import os
import uuid
import json
import signal
import random
import time
import re
import libvirt
import ipaddress
import threading
import traceback
from mvar import MVar
from fog05_sdk import Yaks_Connector
from fog05_sdk.DLogger import DLogger
from fog05_sdk.interfaces.States import State
from fog05_sdk.interfaces.RuntimePluginFDU import *
from KVMFDU import KVMFDU
from jinja2 import Environment
from functools import partial
class KVM(RuntimePluginFDU):
def __init__(self, name, version, plugin_uuid, manifest):
super(KVM, self).__init__(name, version, plugin_uuid, manifest)
self.pid = os.getpid()
self.var = MVar()
self.wait_dependencies()
self.agent_conf = \
self.connector.loc.actual.get_node_configuration(self.node)
self.configuration = manifest.get('configuration')
self.logger.info('__init__()', ' Hello from KVM Plugin')
self.update_interval = self.configuration.get('update_interval', 10)
if self.configuration.get('emulator') is None:
raise ValueError("emulator field in configuration cannot be none, set a qemu binary eg. /usr/bin/qemu-system-x86_64")
if self.configuration.get('machine') is None:
raise ValueError("machine field in configuration cannot be none, set a qemu machine eg. pc-i440fx-2.5")
if self.configuration.get('arch') is None:
raise ValueError("arch field in configuration cannot be none, set a cpu architecture eg. x86_64")
self.BASE_DIR = os.path.join(self.agent_conf.get('agent').get('path'),'kvm')
self.DISK_DIR = 'disks'
self.IMAGE_DIR = 'images'
self.LOG_DIR = 'logs'
file_dir = os.path.dirname(__file__)
self.DIR = os.path.abspath(file_dir)
self.conn = None
self.images = {}
self.flavors = {}
self.mon_th = {}
signal.signal(signal.SIGINT, self.__catch_signal)
signal.signal(signal.SIGTERM, self.__catch_signal)
def __catch_signal(self, signal, _):
if signal in [2,15]:
self.var.put(signal)
def start_runtime(self):
self.logger.info('startRuntime()', ' KVM Plugin - Connecting to KVM')
self.conn = libvirt.open('qemu:///system')
self.logger.info('startRuntime()', '[ DONE ] KVM Plugin - Connecting to KVM')
'''check if dirs exists if not exists create'''
if self.os.dir_exists(self.BASE_DIR):
if not self.os.dir_exists(os.path.join(self.BASE_DIR, self.DISK_DIR)):
self.os.create_dir(os.path.join(self.BASE_DIR, self.DISK_DIR))
if not self.os.dir_exists(os.path.join(self.BASE_DIR, self.IMAGE_DIR)):
self.os.create_dir(os.path.join(self.BASE_DIR, self.IMAGE_DIR))
if not self.os.dir_exists(os.path.join(self.BASE_DIR, self.LOG_DIR)):
self.os.create_dir(os.path.join(self.BASE_DIR, self.LOG_DIR))
else:
self.os.create_dir(os.path.join(self.BASE_DIR))
self.os.create_dir(os.path.join(self.BASE_DIR, self.DISK_DIR))
self.os.create_dir(os.path.join(self.BASE_DIR, self.IMAGE_DIR))
self.os.create_dir(os.path.join(self.BASE_DIR, self.LOG_DIR))
self.connector.loc.desired.observe_node_runtime_fdus(self.node, self.uuid, self.__fdu_observer)
self.manifest.update({'pid': self.pid})
self.manifest.update({'status': 'running'})
self.connector.loc.actual.add_node_plugin(self.node, self.uuid, self.manifest)
self.logger.info('start_runtime()', ' KVM Plugin - Started...')
r = self.var.get()
self.stop_runtime()
self.connector.close()
exit(0)
def stop_runtime(self):
self.logger.info('stopRuntime()', ' KVM Plugin - Destroying running domains')
for k in list(self.current_fdus.keys()):
fdu = self.current_fdus.get(k)
self.__force_fdu_termination(k)
if fdu.get_status() == State.DEFINED:
self.undefine_fdu(k)
for k in list(self.images.keys()):
self.__remove_image(k)
for k in list(self.flavors.keys()):
self.__remove_flavor(k)
try:
self.conn.close()
except libvirt.libvirtError as err:
pass
self.logger.info('stopRuntime()', '[ DONE ] KVM Plugin - Bye Bye')
def get_fdus(self):
return self.current_fdus
def define_fdu(self, fdu_record):
self.logger.info('define_fdu()', ' KVM Plugin - Defining a VM')
fdu = KVMFDU(fdu_record)
entity = None
img = None
flavor = None
fdu_uuid = fdu.get_fdu_id()
instance_id = fdu.get_uuid()
if instance_id in self.current_fdus:
self.logger.error('define_fdu()', '[ ERRO ] LXD Plugin - Instance with ID {} already defined!!'.format(instance_id))
self.write_fdu_error(fdu_uuid, instance_id, 0, 'Instance with this ID {} already exists!'.format(instance_id))
if self.is_uuid(fdu.get_image_uri()):
img = self.agent.get_image_info(fdu.get_image_uri())
self.logger.info('define_fdu()', '[ INFO ] LXD Plugin - Img info: {}'.format(img))
if img is None:
self.logger.error('define_fdu()', '[ ERRO ] KVM Plugin - Cannot find image {}'.format(fdu.get_image_uri()))
self.write_fdu_error(fdu_uuid, instance_id, 0, 'Cannot find image!')
self.logger.info('define_fdu()', '[ ERRO ] KVM Plugin - VM uuid: {}'.format(instance_id))
return
fdu.set_image_uri(img.get('uri'))
fdu.set_image_uuid(img.get('uuid'))
#self.logger.warning('define_fdu()', '[ WARN ] KVM Plugin - No image id specified defining from manifest information new image id uuid:{}'.format(fdu_uuid))
if fdu.get_image_uri().startswith('http'):
image_name = os.path.join(self.BASE_DIR, self.IMAGE_DIR, fdu.get_image_uri().split('/')[-1])
self.os.download_file(fdu.get_image_uri(),image_name)
elif fdu.get_image_uri().startswith('file://'):
image_name = os.path.join(
self.BASE_DIR, self.IMAGE_DIR, fdu.get_image_uri().split('/')[-1])
cmd = 'cp {} {}'.format(fdu.get_image_uri()[len('file://'):], image_name)
self.os.execute_command(cmd, blocking=True, external=False)
img_info = {}
img_info.update({'uuid': fdu_uuid})
img_info.update({'name': '{}_img'.format(fdu.name)})
img_info.update({'base_image': image_name})
img_info.update({'type':'kvm'})
img_info.update({'format': fdu.get_image_format()})
fdu.set_image_uri(img_info.get('uri'))
fdu.set_image_uuid(img_info.get('uuid'))
self.__add_image(img_info)
img = self.images.get(fdu_uuid, None)
if img is None:
self.write_fdu_error(fdu_uuid, instance_id, 0, 'Cannot find image!')
self.logger.error('define_fdu()', '[ ERRO ] KVM Plugin - Cannot find image {}'.format(fdu_uuid))
return
self.logger.info('define_fdu()', '[ WARN ] KVM Plugin - New flavor uuid:{}'.format(fdu_uuid))
cpu = fdu.get_computation_requirements().get('cpu_min_count', 1)
mem = fdu.get_computation_requirements().get('ram_size_mb', 256)
disk_size = fdu.get_computation_requirements().get('storage_size_gb', 10)
flavor_info = {}
flavor_info.update({'name': '{}_flavor'.format(fdu.name)})
flavor_info.update({'uuid': fdu_uuid})
flavor_info.update({'cpu': cpu})
flavor_info.update({'memory': mem})
flavor_info.update({'disk_size': disk_size})
flavor_info.update({'type':'kvm'})
fdu.get_computation_requirements().update({'uuid': fdu_uuid})
self.__add_flavor(flavor_info)
flavor = self.flavors.get(fdu_uuid, None)
if flavor is None:
self.logger.error('define_fdu()', '[ ERRO ] KVM Plugin - Cannot find flavor {}'.format(fdu_uuid))
self.write_fdu_error(fdu_uuid, instance_id, 0, 'Cannot find image!')
return
fdu.on_defined()
self.current_fdus.update({instance_id: fdu})
self.update_fdu_status(fdu_uuid, instance_id, 'DEFINE')
self.logger.info('define_fdu()', '[ DONE ] KVM Plugin - VM Defined uuid: {}'.format(instance_id))
def undefine_fdu(self, instance_id):
self.logger.info('undefine_fdu()', ' KVM Plugin - Undefine a VM uuid {}'.format(instance_id))
fdu = self.current_fdus.get(instance_id, None)
if fdu is None:
self.logger.error('undefine_fdu()', 'KVM Plugin - FDU not exists')
raise FDUNotExistingException('FDU not existing', 'FDU {} not in runtime {}'.format(instance_id, self.uuid))
elif fdu.get_status() != State.DEFINED:
self.logger.error('undefine_fdu()', 'KVM Plugin - FDU state is wrong, or transition not allowed')
raise StateTransitionNotAllowedException('FDU is not in DEFINED state', 'FDU {} is not in DEFINED state'.format(instance_id))
else:
if (self.current_fdus.pop(instance_id, None)) is None:
self.logger.warning('undefine_fdu()', 'KVM Plugin - pop from entities dict returned none')
fdu_uuid = fdu.fdu_uuid
if self.get_local_instances(fdu_uuid) == 1:
image_id = fdu.image.get('uuid')
image_name = self.images.get(image_id)['base_image']
self.os.remove_file(image_name)
self.images.pop(fdu_uuid)
self.flavors.pop(fdu_uuid)
self.connector.loc.actual.remove_node_fdu(self.node, self.uuid, fdu_uuid, instance_id)
self.logger.info('undefine_fdu()', '[ DONE ] KVM Plugin - Undefine a VM uuid {} '.format(instance_id))
def configure_fdu(self, instance_uuid):
self.logger.info('configure_fdu()', ' KVM Plugin - Configure a VM uuid {} '.format(instance_uuid))
fdu = self.current_fdus.get(instance_uuid, None)
if fdu is None:
self.logger.error('configure_fdu()', 'KVM Plugin - FDU not exists')
raise FDUNotExistingException('FDU not existing', 'FDU {} not in runtime {}'.format(instance_uuid, self.uuid))
elif fdu.get_status() != State.DEFINED:
self.logger.error('configure_fdu()', 'KVM Plugin - FDU state is wrong, or transition not allowed')
raise StateTransitionNotAllowedException('FDU is not in DEFINED state', 'FDU {} is not in DEFINED state'.format(instance_uuid))
else:
fdu_uuid = fdu.get_fdu_id()
record = self.connector.loc.actual.get_node_fdu(self.node, self.uuid, fdu_uuid, instance_uuid)
name = fdu.name
flavor = self.flavors.get(fdu.get_computation_requirements().get('uuid'), None)
img = self.images.get(fdu.get_image().get('uuid'), None)
if flavor is None:
self.logger.error('configure_fdu()', '[ ERRO ] KVM Plugin - Cannot find flavor {}'.format(fdu.flavor_id))
fdu.status = 'ERROR'
self.current_fdus.update({instance_uuid: fdu})
self.write_fdu_error(fdu_uuid, instance_uuid, 2, 'Cannot find flavor')
return
if img is None:
self.logger.error('configure_fdu()', '[ ERRO ] KVM Plugin - Cannot find image {}'.format(fdu.image_id))
fdu.status = 'ERROR'
self.current_fdus.update({instance_uuid: fdu})
self.write_fdu_error(fdu_uuid, instance_uuid, 2, 'Cannot find image')
return
disk_path = '{}.{}'.format(instance_uuid, img.get('format'))
cdrom_path = '{}_config.iso'.format(instance_uuid)
disk_path = os.path.join(self.BASE_DIR, self.DISK_DIR, disk_path)
cdrom_path = os.path.join(self.BASE_DIR, self.DISK_DIR, cdrom_path)
fdu.disk = disk_path
fdu.cdrom = cdrom_path
for cp in fdu.get_connection_points():
cp_id = cp.get('uuid')
# cp_id = cp.get('uuid')
# cp_record = {
# 'cp_uuid':cp_id,
# 'status':'CREATE'
# }
self.connector.loc.desired.add_node_port(self.node, self.nm, cp_id,cp)
res = self.connector.loc.actual.get_node_port(self.node, self.nm, cp_id)
while res is None:
res = self.connector.loc.actual.get_node_port(self.node, self.nm, cp_id)
cp.update({'status':'CONNECTED'})
net_cfg = []
if fdu.get_interfaces() is not None:
for i, intf in enumerate(fdu.get_interfaces()):
intf_name = intf.get('name')
mac = intf.get('mac_address', self.__generate_random_mac())
intf.update({'mac_address': mac})
if intf.get('virtual_interface').get('intf_type').upper() in ['PHYSICAL','BRIDGED']:
real_intf_name = intf.get('phy_face')
if self.os.get_intf_type(real_intf_name) in ['ethernet']:
net_cfg.append({'name':intf_name, 'mac':mac, 'dev':real_intf_name,'type':'direct'})
self.os.set_interface_unaviable(real_intf_name)
elif self.os.get_intf_type(real_intf_name) in ['wireless']:
net_cfg.append({'name':intf_name, 'mac':mac, 'dev':real_intf_name,'type':'direct'})
self.os.set_interface_unaviable(real_intf_name)
else:
net_cfg.append({'name':intf_name, 'mac':mac, 'dev':real_intf_name})
else:
intf_id = 'kvm-{}-{}'.format(fdu.get_short_id(), i)
intf_data = self.connector.loc.actual.get_node_port(self.node, self.nm, intf.get('cp_id'))
self.logger.info('configure_fdu()',' KVM Plugin - Configuring FDU - interface data {}'.format(intf_data))
cp_data = self.agent.get_port_info(intf_data['cp_uuid'])
self.logger.info('configure_fdu()',' KVM Plugin - Configuring FDU - connection point data {}'.format(cp_data))
net_data = self.connector.loc.actual.get_node_network(self.node, self.nm, cp_data['pair_id'])
self.nm.create_virtual_interface(intf_id, intf)
#self.logger.info('configure_fdu()','KVM Plugin - Interface info {}'.format(intf_data))
#dev_name = intf_data.get('cp_name')
self.logger.info('configure_fdu()','KVM Plugin - Interface info {}'.format(net_data))
dev_name = net_data['properties']['virtual_device']
net_cfg.append({'name':intf_name, 'mac':mac, 'dev':dev_name})
vm_xml = self.__generate_dom_xml(fdu, flavor, img, net_cfg)
xml_file_name = 'kvm-{}.xml'.format(instance_uuid)
self.os.store_file(vm_xml, self.BASE_DIR, xml_file_name)
vendor_conf = self.__generate_vendor_data(instance_uuid, self.node)
vendor_filename = 'vendor_{}.yaml'.format(instance_uuid)
self.os.store_file(vendor_conf, self.BASE_DIR, vendor_filename)
vendor_filename = os.path.join(self.BASE_DIR, vendor_filename)
### creating cloud-init initial drive TODO: check all the possibilities provided by OSM
conf_cmd = '{} --hostname {} --uuid {} --vendor-data {}'.format(os.path.join(self.DIR, 'templates',
'create_config_drive.sh'), fdu.name, instance_uuid,
vendor_filename)
rm_temp_cmd = 'rm'
if fdu.get_configuration() is not None:
if fdu.get_configuration().get('conf_type') in ['CLOUD_INIT']:
c_init_file = fdu.get_configuration().get('script')
data_filename = 'userdata_{}'.format(fdu_uuid)
self.os.store_file(c_init_file, self.BASE_DIR, data_filename)
data_filename = os.path.join(self.BASE_DIR, data_filename)
conf_cmd = conf_cmd + ' --user-data {}'.format(data_filename)
if fdu.get_configuration().get('ssh_keys') is not None and len(fdu.get_configuration().get('ssh_keys')) > 0:
key_filename = 'key_{}.pub'.format(fdu_uuid)
self.os.store_file(fdu.get_configuration().get('ssh_keys')[0], self.BASE_DIR, key_filename)
key_filename = os.path.join(self.BASE_DIR, key_filename)
conf_cmd = conf_cmd + ' --ssh-key {}'.format(key_filename)
conf_cmd = conf_cmd + ' {}'.format(fdu.cdrom)
#############
qemu_cmd = 'qemu-img create -f {} {} {}G'.format(img.get('format'), fdu.disk, int(flavor.get('disk_size')))
# As in the first example, but the output format will be qcow2 instead of a raw disk:
#
# qemu-img create -f qcow2 -o preallocation=metadata newdisk.qcow2 15G
# virt-resize --expand /dev/sda2 olddisk newdisk.qcow2
dd_cmd = 'dd if={} of={}'.format(img.get('base_image'), fdu.disk)
self.os.execute_command(qemu_cmd,blocking= True)
self.os.execute_command(conf_cmd,blocking=True)
self.os.execute_command(dd_cmd, blocking=True)
# if fdu.ssh_key is not None and fdu.ssh_key != '':
# self.os.remove_file(key_filename)
# if fdu.configuration is not None:
# if fdu.configuration.get('conf_type') in ['CLOUD_INIT']:
# self.os.remove_file(data_filename)
# self.os.remove_file(vendor_filename)
try:
self.conn.defineXML(vm_xml)
except libvirt.libvirtError:
self.conn = libvirt.open('qemu:///system')
self.conn.defineXML(vm_xml)
fdu.on_configured(vm_xml)
self.current_fdus.update({instance_uuid: fdu})
# self.update_fdu_status(fdu_uuid, instance_uuid, 'CONFIGURE')
#fdu.set_status('CONFIGURE')
record = InfraFDU(record)
record.set_status('CONFIGURE')
# TODO: monitoring TBA
# this monitoring uses libvirt to get container information
mt = threading.Thread(target=self.__monitor_instance, args=(fdu_uuid, instance_uuid, fdu.name),daemon=True)
mt.start()
self.mon_th.update({instance_uuid:mt})
self.logger.info('configure_fdu()', '[ DONE ] LXD Plugin - Starting a Monitoring of {}'.format(instance_uuid))
self.logger.info('configure_fdu()', '[ INFO ] KVM Plugin - Registreting start/run/log/ls/file evals for {}'.format(instance_uuid))
start_fun = partial(self.start_fdu, instance_uuid)
run_fun = partial(self.run_fdu, instance_uuid)
log_fun = partial(self.get_log_fdu, instance_uuid)
ls_fun = partial(self.get_ls_fdu, instance_uuid)
file_fun = partial(self.get_file_fdu, instance_uuid)
try:
self.connector.loc.actual.add_plugin_fdu_start_eval(self.node, self.uuid, fdu_uuid, instance_uuid, start_fun)
self.connector.loc.actual.add_plugin_fdu_run_eval(self.node, self.uuid, fdu_uuid, instance_uuid, run_fun)
self.connector.loc.actual.add_plugin_fdu_log_eval(self.node, self.uuid, fdu_uuid, instance_uuid, log_fun)
self.connector.loc.actual.add_plugin_fdu_ls_eval(self.node, self.uuid, fdu_uuid, instance_uuid, ls_fun)
self.connector.loc.actual.add_plugin_fdu_file_eval(self.node, self.uuid, fdu_uuid, instance_uuid, file_fun)
except Exception as e:
self.logger.error('configure_fdu()', '[ ERRO ] KVM Plugin - Error in registering start/run/log/ls/file function: {}'.format(e))
traceback.print_exc()
self.connector.loc.actual.add_node_fdu(self.node, self.uuid, fdu_uuid,instance_uuid, record.to_json())
self.logger.info('configure_fdu()', '[ DONE ] KVM Plugin - Configure a VM uuid {}'.format(instance_uuid))
def clean_fdu(self, instance_uuid):
self.logger.info('clean_fdu()', ' KVM Plugin - Clean a VM uuid {} '.format(instance_uuid))
fdu = self.current_fdus.get(instance_uuid, None)
if fdu is None:
self.logger.error('clean_fdu()', 'KVM Plugin - FDU not exists')
raise FDUNotExistingException('FDU not existing', 'FDU {} not in runtime {}'.format(instance_uuid, self.uuid))
elif fdu.get_status() != State.CONFIGURED:
self.logger.error('clean_fdu()', 'KVM Plugin - FDU state is wrong, or transition not allowed')
raise StateTransitionNotAllowedException('FDU is not in CONFIGURED state', 'FDU {} is not in CONFIGURED state'.format(instance_uuid))
else:
fdu_uuid = fdu.get_fdu_id()
dom = self.__lookup_by_uuid(instance_uuid)
if dom is not None:
dom.undefine()
else:
self.logger.error('clean_fdu()', 'KVM Plugin - Domain not found!!')
vmlog = '{}_log.log'.format(instance_uuid)
self.os.remove_file(fdu.cdrom)
self.os.remove_file(fdu.disk)
self.os.remove_file(os.path.join(self.BASE_DIR, self.LOG_DIR, vmlog))
xml_file_name = 'kvm-{}.xml'.format(instance_uuid)
self.os.remove_file(os.path.join(self.BASE_DIR, xml_file_name))
for i, intf in enumerate(fdu.get_interfaces()):
intf_name = intf.get('name')
if intf.get('virtual_interface').get('intf_type').upper() not in ['PHYSICAL','BRIDGED']:
intf_id = 'kvm-{}-{}'.format(fdu.get_short_id(), i)
# self.nm.delete_virtual_interface(intf_id)
else:
real_intf_name = intf.get('phy_face')
self.os.set_interface_available(real_intf_name)
for cp in fdu.get_connection_points():
cp_id = cp.get('uuid')
cp = self.connector.loc.actual.get_node_port(self.node, self.nm, cp_id)
cp.update({'status':'DESTROY'})
self.connector.loc.desired.add_node_port(self.node, self.nm, cp_id, cp)
fdu.on_clean()
self.current_fdus.update({instance_uuid: fdu})
self.update_fdu_status(fdu_uuid, instance_uuid, 'DEFINE')
self.logger.info('clean_fdu()', '[ INFO ] KVM Plugin - Unregistering start/run/log/ls/file evals for {}'.format(instance_uuid))
self.connector.loc.actual.remove_plugin_fdu_start_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.connector.loc.actual.remove_plugin_fdu_run_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.connector.loc.actual.remove_plugin_fdu_log_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.connector.loc.actual.remove_plugin_fdu_ls_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.connector.loc.actual.remove_plugin_fdu_file_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.logger.info('clean_fdu()', '[ DONE ] KVM Plugin - Clean a VM uuid {} '.format(instance_uuid))
def start_fdu(self, instance_uuid, env):
self.logger.info('start_fdu()', 'KVM Plugin - Starting a VM uuid {}'.format(instance_uuid))
try:
fdu = self.current_fdus.get(instance_uuid, None)
if fdu is None:
self.logger.error('start_fdu()', 'KVM Plugin - FDU not exists')
return {'error': 'FDU not exists'}
elif fdu.get_status() != State.CONFIGURED:
self.logger.error('start_fdu()', 'KVM Plugin - FDU state is wrong, or transition not allowed')
return {'error': 'FDU is not in CONFIGURED state'}
else:
fdu_uuid = fdu.get_fdu_id()
self.current_fdus.update({instance_uuid: fdu})
self.update_fdu_status(fdu_uuid, instance_uuid, 'STARTING')
self.logger.info('start_fdu()', '[ INFO ] KVM Plugin - VM Name {}'.format(fdu.name))
dom = self.__lookup_by_uuid(instance_uuid)
dom.create()
while dom.state()[0] != 1:
pass
self.logger.info('start_fdu()', ' KVM Plugin - VM {} Started!'.format(instance_uuid))
fdu.on_start()
# log_filename = '{}/{}/{}_log.log'.format(self.BASE_DIR, self.LOG_DIR, instance_uuid)
# if instance.user_file is not None and instance.user_file != '':
# self.__wait_boot(log_filename, True)
# else:
# self.__wait_boot(log_filename)
self.current_fdus.update({instance_uuid: fdu})
self.update_fdu_status(fdu_uuid, instance_uuid, 'RUN')
self.logger.info('start_fdu()', '[ DONE ] KVM Plugin - Starting a VM uuid {}'.format(instance_uuid))
return {'result': instance_uuid}
except Exception as e:
self.logger.error('start_fdu()', '[ ERRO ] KVM Plugin - Error: {}'.format(e))
traceback.print_exc()
return {'error':'{}'.format(e)}
def run_fdu(self, instance_uuid, ignored):
return {'error':'KVM FDU {} cannot be run, use start instead'.format(instance_uuid)}
def stop_fdu(self, instance_uuid):
self.logger.info('stop_fdu()', ' KVM Plugin - Stop a VM uuid {}'.format(instance_uuid))
fdu = self.current_fdus.get(instance_uuid, None)
if fdu is None:
self.logger.error('stop_fdu()', 'KVM Plugin - FDU not exists')
raise FDUNotExistingException('FDU not existing', 'FDU {} not in runtime {}'.format(instance_uuid, self.uuid))
elif fdu.get_status() != State.RUNNING:
self.logger.error('stop_fdu()', 'KVM Plugin - FDU state is wrong, or transition not allowed')
raise StateTransitionNotAllowedException('FDU is not in RUNNING state', 'FDU {} is not in RUNNING state'.format(instance_uuid))
else:
fdu_uuid = fdu.get_fdu_id()
dom = self.__lookup_by_uuid(instance_uuid)
dom.shutdown()
retries = 100
for i in range(0, retries):
if dom.state()[0] != 5:
break
else:
time.sleep(0.015)
if dom.state()[0] != 5:
dom.destroy()
fdu.on_stop()
self.current_fdus.update({instance_uuid: fdu})
self.update_fdu_status(fdu_uuid, instance_uuid, 'CONFIGURE')
self.logger.info('stop_fdu()', '[ DONE ] KVM Plugin - Stop a VM uuid {}'.format(instance_uuid))
def pause_fdu(self, instance_uuid):
self.logger.info('pause_fdu()', ' KVM Plugin - Pause a VM uuid {}'.format(instance_uuid))
fdu = self.current_fdus.get(instance_uuid, None)
if fdu is None:
self.logger.error('pause_fdu()', 'KVM Plugin - FDU not exists')
raise FDUNotExistingException('FDU not existing', 'FDU {} not in runtime {}'.format(instance_uuid, self.uuid))
elif fdu.get_status() != State.RUNNING:
self.logger.error('pause_fdu()', 'KVM Plugin - FDU state is wrong, or transition not allowed')
raise StateTransitionNotAllowedException('FDU is not in RUNNING state', 'FDU {} is not in RUNNING state'.format(instance_uuid))
else:
fdu_uuid = fdu.get_fdu_id()
self.__lookup_by_uuid(instance_uuid).suspend()
fdu.on_pause()
self.current_fdus.update({instance_uuid: fdu})
self.update_fdu_status(fdu_uuid, instance_uuid, 'PAUSE')
self.logger.info('pause_fdu()', '[ DONE ] KVM Plugin - Pause a VM uuid {}'.format(fdu_uuid))
def resume_fdu(self, instance_uuid):
self.logger.info('resume_fdu()', ' KVM Plugin - Resume a VM uuid {}'.format(instance_uuid))
fdu = self.current_fdus.get(instance_uuid, None)
if fdu is None:
self.logger.error('resume_fdu()', 'KVM Plugin - FDU not exists')
raise FDUNotExistingException('FDU not existing', 'FDU {} not in runtime {}'.format(instance_uuid, self.uuid))
elif fdu.get_status() != State.PAUSED:
self.logger.error('resume_fdu()', 'KVM Plugin - FDU state is wrong, or transition not allowed')
raise StateTransitionNotAllowedException('FDU is not in PAUSED state', 'FDU {} is not in PAUSED state'.format(instance_uuid))
else:
fdu_uuid = fdu.get_fdu_id()
self.__lookup_by_uuid(instance_uuid).resume()
fdu.on_resume()
self.current_fdus.update({instance_uuid: fdu})
self.update_fdu_status(fdu_uuid, instance_uuid, 'RUN')
self.logger.info('resume_fdu()', '[ DONE ] KVM Plugin - Resume a VM uuid {}'.format(fdu_uuid))
def migrate_fdu(self, instance_uuid):
record = self.connector.loc.desired.get_node_fdu(self.node, self.uuid, '*', instance_uuid)
fdu_uuid = record.get('fdu_id')
destination = record.get_migration_properties().get('destination')
if destination != self.node:
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Source Node preparation...')
fdu = self.current_fdus.get(instance_uuid, None)
if instance_uuid is None:
self.logger.error('migrate_fdu','FDU not in Runtime!!')
fdu.ipdata('ERROR')
self.current_fdus.update({instance_uuid: fdu})
self.write_fdu_error(fdu_uuid, instance_uuid, 7, 'Instance not present in node')
return
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Source Node wait destination...')
self.wait_destination_ready(fdu_uuid, instance_uuid, destination)
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Migrating...')
# ACTUAL MIGRATION #
dom = self.__lookup_by_uuid(instance_uuid)
dst_ip = self.agent.get_node_mgmt_address(destination).get('ipv4_address')
dst_host = 'qemu+ssh://{}/system'.format(dst_ip)
dest_conn = libvirt.open(dst_host)
if dest_conn is None:
self.logger.error('migrate_fdu()', 'KVM Plugin - Before Migration Source: Error on libvirt connection')
record.pop('migration_properties')
self.write_fdu_error(fdu_uuid, instance_uuid, 10, 'Cannot connect to destination')
# record.set_status('ERROR')
# record.set_error_code(10)
# self.connector.loc.actual.add_node_fdu(self.node, self.uuid, fdu_uuid, instance_uuid, record)
return
flags = libvirt.VIR_MIGRATE_LIVE | libvirt.VIR_MIGRATE_PERSIST_DEST
new_dom = dom.migrate(dest_conn, flags, fdu.name, None, 0)
# new_dom = dom.migrate(dest_conn, libvirt.VIR_MIGRATE_LIVE and libvirt.VIR_MIGRATE_PERSIST_DEST and libvirt.VIR_MIGRATE_NON_SHARED_DISK, name, None, 0)
if new_dom is None:
self.logger.error('migrate_fdu()', 'KVM Plugin - Before Migration Source: Migration failed')
record.pop('migration_properties')
self.write_fdu_error(fdu_uuid, instance_uuid, 10, 'Failure on destination node')
# record.clean_migration_properties()
# record.set_status('ERROR')
# record.set_error_code(10)
self.connector.loc.actual.add_node_fdu(self.node, self.uuid, fdu_uuid, instance_uuid, record)
return
self.logger.info('migrate_fdu()', ' KVM Plugin - Before Migration Source: Migration succeeds')
dest_conn.close()
#
fdu.on_stop()
self.logger.info('migrate_fdu()', '[ INFO ] KVM Plugin - Unregistering start/run/log/ls/file evals for {}'.format(instance_uuid))
self.connector.loc.actual.remove_plugin_fdu_start_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.connector.loc.actual.remove_plugin_fdu_run_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.connector.loc.actual.remove_plugin_fdu_log_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.connector.loc.actual.remove_plugin_fdu_ls_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.connector.loc.actual.remove_plugin_fdu_file_eval(self.node, self.uuid, fdu_uuid, instance_uuid)
self.current_fdus.update({instance_uuid: fdu})
self.clean_fdu(instance_uuid)
self.undefine_fdu(instance_uuid)
self.logger.info('migrate_fdu()', ' KVM Plugin - Source is Clean')
else:
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Destination Node preparation...')
record.set_status('DEFINE')
self.connector.loc.actual.add_node_fdu(self.node, self.uuid, fdu_uuid, instance_uuid, record)
fdu = KVMFDU(record.to_json())
image_name = os.path.join(self.BASE_DIR, self.IMAGE_DIR, fdu.get_image_uri().split('/')[-1])
if fdu.get_image_uri().startswith('http'):
image_name = os.path.join(self.BASE_DIR, self.IMAGE_DIR, fdu.get_image_uri().split('/')[-1])
self.os.download_file(fdu.get_image_uri(), image_name)
elif fdu.get_image_uri().startswith('file://'):
image_name = os.path.join(
self.BASE_DIR, self.IMAGE_DIR, fdu.get_image_uri().split('/')[-1])
cmd = 'cp {} {}'.format(fdu.get_image_uri()[len('file://'):], image_name)
self.os.execute_command(cmd, blocking=True)
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Destination Node creating image and flavor...')
img = {
'uuid': fdu_uuid,
'name': '{}_img'.format(fdu.name),
'base_image': image_name,
'type':'kvm',
'format': fdu.get_image_format(),
'uri' :fdu.get_image_uri()
}
fdu.set_image_uuid(img.get('uuid'))
cpu = fdu.get_computation_requirements().get('cpu_min_count',1)
mem = fdu.get_computation_requirements().get('ram_size_mb', 256)
disk_size = fdu.get_computation_requirements().get('storage_size_gb',10)
flavor = {
'name': '{}_flavor'.format(fdu.name),
'uuid': fdu_uuid,
'cpu': cpu,
'memory': mem,
'disk_size': disk_size,
'type':'kvm'
}
fdu.get_computation_requirements().update({'uuid': fdu_uuid})
self.__add_flavor(flavor)
self.__add_image(img)
disk_path = '{}.{}'.format(instance_uuid, img.get('format'))
cdrom_path = '{}_config.iso'.format(instance_uuid)
disk_path = os.path.join(self.BASE_DIR, self.DISK_DIR, disk_path)
cdrom_path = os.path.join(self.BASE_DIR, self.DISK_DIR, cdrom_path)
fdu.disk = disk_path
fdu.cdrom = cdrom_path
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Destination Node creating Networks...')
for cp in fdu.get_connection_points():
cp_id = cp.get('uuid')
# cp_id = cp.get('uuid')
# cp_record = {
# 'cp_uuid':cp_id,
# 'status':'CREATE'
# }
self.connector.loc.desired.add_node_port(self.node, self.nm, cp_id,cp)
res = self.connector.loc.actual.get_node_port(self.node, self.nm, cp_id)
while res is None:
res = self.connector.loc.actual.get_node_port(self.node, self.nm, cp_id)
cp.update({'status':'CONNECTED'})
net_cfg = []
if fdu.get_interfaces() is not None:
for i, intf in enumerate(fdu.get_interfaces()):
intf_name = intf.get('name')
mac = intf.get('mac_address', self.__generate_random_mac())
intf.update({'mac_address': mac})
if intf.get('virtual_interface').get('intf_type').upper() in ['PHYSICAL','BRIDGED']:
real_intf_name = intf.get('phy_face')
if self.os.get_intf_type(real_intf_name) in ['ethernet']:
net_cfg.append({'name':intf_name, 'mac':mac, 'dev':real_intf_name,'type':'direct'})
self.os.set_interface_unaviable(real_intf_name)
elif self.os.get_intf_type(real_intf_name) in ['wireless']:
net_cfg.append({'name':intf_name, 'mac':mac, 'dev':real_intf_name,'type':'direct'})
self.os.set_interface_unaviable(real_intf_name)
else:
net_cfg.append({'name':intf_name, 'mac':mac, 'dev':real_intf_name})
else:
intf_id = 'kvm-{}-{}'.format(fdu.get_short_id(), i)
intf_data = self.connector.loc.actual.get_node_port(self.node, self.nm, intf.get('cp_id')).get('properties')
# self.nm.create_virtual_interface(intf_id,intf)
self.logger.info('migrate_fdu()','KVM Plugin - Interface info {}'.format(intf_data))
dev_name = intf_data.get('cp_name')
net_cfg.append({'name':intf_name, 'mac':mac, 'dev':dev_name})
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Destination Node creating disks...')
vm_xml = self.__generate_dom_xml(fdu, flavor, img, net_cfg)
xml_file_name = 'kvm-{}.xml'.format(instance_uuid)
self.os.store_file(vm_xml, self.BASE_DIR, xml_file_name)
vendor_conf = self.__generate_vendor_data(instance_uuid, self.node)
vendor_filename = 'vendor_{}.yaml'.format(instance_uuid)
self.os.store_file(vendor_conf, self.BASE_DIR, vendor_filename)
vendor_filename = os.path.join(self.BASE_DIR, vendor_filename)
### creating cloud-init initial drive TODO: check all the possibilities provided by OSM
conf_cmd = '{} --hostname {} --uuid {} --vendor-data {}'.format(os.path.join(self.DIR, 'templates',
'create_config_drive.sh'), fdu.name, instance_uuid,
vendor_filename)
rm_temp_cmd = 'rm'
if fdu.get_configuration() is not None:
if fdu.get_configuration().get('conf_type') in ['CLOUD_INIT']:
c_init_file = fdu.get_configuration().get('script')
data_filename = 'userdata_{}'.format(fdu_uuid)
self.os.store_file(c_init_file, self.BASE_DIR, data_filename)
data_filename = os.path.join(self.BASE_DIR, data_filename)
conf_cmd = conf_cmd + ' --user-data {}'.format(data_filename)
if fdu.get_configuration().get('ssh_keys') is not None and len(fdu.get_configuration().get('ssh_keys')) > 0:
key_filename = 'key_{}.pub'.format(fdu_uuid)
self.os.store_file(fdu.get_configuration().get('ssh_keys')[0], self.BASE_DIR, key_filename)
key_filename = os.path.join(self.BASE_DIR, key_filename)
conf_cmd = conf_cmd + ' --ssh-key {}'.format(key_filename)
qemu_cmd = 'qemu-img create -f {} {} {}G'.format(img.get('format'), fdu.disk, int(flavor.get('disk_size')))
conf_cmd = conf_cmd + ' {}'.format(fdu.cdrom)
# THIS AS TO BE DONE IN DIFFERENT WAY
dd_cmd = 'dd if={} of={}'.format(img.get('base_image'), fdu.disk)
self.os.execute_command(qemu_cmd, blocking=True)
self.os.execute_command(conf_cmd, blocking=True)
# THIS AS TO BE DONE IN DIFFERENT WAY
self.os.execute_command(dd_cmd,blocking=True)
# if fdu.ssh_key is not None and fdu.ssh_key != '':
# self.os.remove_file(key_filename)
# if fdu.configuration is not None:
# if fdu.configuration.get('conf_type') in ['CLOUD_INIT']:
# self.os.remove_file(data_filename)
# self.os.remove_file(vendor_filename)
self.os.remove_file(vendor_filename)
fdu.set_status('LAND')
self.connector.loc.actual.add_node_fdu(self.node, self.uuid, fdu_uuid, instance_uuid, fdu.to_json())
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Destination Node is ready for {}'.format(fdu_uuid))
### DESTINATION NODE WAIT FOR VM IN HYPERVISOR
while True:
dom = self.__lookup_by_uuid(instance_uuid)
if dom is None:
self.logger.info('migrate_fdu()', ' KVM Plugin - Domain not already in this host')
else:
if dom.isActive() == 1:
break
else:
self.logger.info('migrate_fdu()', ' KVM Plugin - Domain in this host but not running')
time.sleep(1)
fdu.on_start()
self.current_fdus.update({instance_uuid: fdu})
record.set_migration_properties('','')
record.on_start()
self.logger.info('migrate_fdu()', '[ INFO ] KVM Plugin - Registreting start/run/log/ls/file evals for {}'.format(instance_uuid))
start_fun = partial(self.start_fdu, instance_uuid)
run_fun = partial(self.run_fdu, instance_uuid)
log_fun = partial(self.get_log_fdu, instance_uuid)
ls_fun = partial(self.get_ls_fdu, instance_uuid)
file_fun = partial(self.get_file_fdu, instance_uuid)
try:
self.connector.loc.actual.add_plugin_fdu_start_eval(self.node, self.uuid, fdu_uuid, instance_uuid, start_fun)
self.connector.loc.actual.add_plugin_fdu_run_eval(self.node, self.uuid, fdu_uuid, instance_uuid, run_fun)
self.connector.loc.actual.add_plugin_fdu_log_eval(self.node, self.uuid, fdu_uuid, instance_uuid, log_fun)
self.connector.loc.actual.add_plugin_fdu_ls_eval(self.node, self.uuid, fdu_uuid, instance_uuid, ls_fun)
self.connector.loc.actual.add_plugin_fdu_file_eval(self.node, self.uuid, fdu_uuid, instance_uuid, file_fun)
except Exception as e:
self.logger.error('migrate_fdu()', '[ ERRO ] KVM Plugin - Error in registering start/run/log/ls/file function: {}'.format(e))
traceback.print_exc()
self.connector.loc.actual.add_node_fdu(self.node, self.uuid, fdu_uuid, instance_uuid, record.to_json)
self.logger.info('migrate_fdu()', '[ DONE ] KVM Plugin - Migrate a VM uuid {}'.format(instance_uuid))
#
# Here we should copy the disk image somehow
#
def get_log_fdu(self, instance_uuid, unit):
try:
self.logger.info('get_log_fdu()', ' KVM Plugin - Running VM uuid {}'.format(instance_uuid))
fdu = self.current_fdus.get(instance_uuid, None)
if fdu is None:
self.logger.error('get_log_fdu()', 'KVM Plugin - FDU not exists')
return {'error': 'FDU not exists'}
elif fdu.get_status() != State.CONFIGURED and fdu.get_status() != State.RUNNING:
self.logger.error('get_log_fdu()', 'KVM Plugin - FDU state is wrong, or transition not allowed')
return {'error': 'FDU is not in correct state'}
else:
log_filename = '{}/{}/{}_log.log'.format(self.BASE_DIR, self.LOG_DIR, instance_uuid)
cmd = 'sudo chmod a+r {}'.format(log_filename)
self.os.execute_command(cmd, blocking=True, external=True)
self.logger.info('get_log_fdu()', 'FDU log file {}'.format(log_filename))
out = open(log_filename)
data = out.read()
out.close()
return {'result': data}
except Exception as e:
self.logger.error('get_log_fdu()', '[ ERRO ] KVM Plugin - Error: {}'.format(e))
traceback.print_exc()
return {'error':'{}'.format(e)}
def get_ls_fdu(self, instance_uuid, unit):
return {'error':'KVM FDU {} cannot get ls'.format(instance_uuid)}
def get_file_fdu(self, instance_uuid, filename):
return {'error':'KVM FDU {} cannot get file'.format(instance_uuid)}
def __monitor_instance(self, fdu_uuid, instance_id, instance_name):
self.logger.info('__monitor_fdu()','[ INFO ] KVM Plugin - Staring monitoring of VM uuid {}'.format(instance_id))
while True:
time.sleep(self.update_interval)
try:
record = self.connector.loc.actual.get_node_fdu(self.node, self.uuid, fdu_uuid, instance_id)
if record.get('status') not in ['LAND', 'TAKE_OFF','MIGRATE']:
self.logger.info('__monitor_fdu()','[ INFO ] KVM Plugin - Updating status of {}'.format(fdu_uuid))
dom = self.__lookup_by_uuid(instance_id)
if dom is None:
raise Exception('VM not found in hypervisor')
detailed_state = {}
c_net = {}
for i in record.get('interfaces'):
ip = self.nm.get_address(i.get('mac_address',''))
c_net.update(
{
i['vintf_name']:
{
'hwaddr': i.get('mac_address',''),
'addresses': [
{'address': ip}
]
}
}
)
vm_mem_info = dom.memoryStats()
mem = {
'usage': (vm_mem_info['actual']-vm_mem_info.get('unused',0)),
'usage_peak': 0,
'swap_usage': vm_mem_info.get('swap_in',0),
'swap_usage_peak':0
}
detailed_state.update({'network': c_net})
detailed_state.update({'cpu': {'usage':dom.getCPUStats(True)[0]['cpu_time']}})
detailed_state.update({'memory': mem})
#detailed_state.update({'disk': cs.disk})
record.update({'hypervisor_info': detailed_state})
self.connector.loc.actual.add_node_fdu(self.node, self.uuid, fdu_uuid, instance_id, record)
except Exception as e:
self.logger.error('__monitor_instance()', '[ ERROR ] KVM Plugin - Stopping monitoring of VM uuid {} Error {}'.format(instance_id, e))
return
def __add_image(self, manifest):
img_uuid = manifest.get('uuid')
self.images.update({img_uuid: manifest})
self.connector.loc.actual.add_node_image(self.node, self.uuid, img_uuid, manifest)
def __remove_image(self, image_uuid):
image = self.images.get(image_uuid, None)
if image is None:
self.logger.info('__remove_image()', ' KVM Plugin - Image not found!!')
return
self.os.remove_file(image.get('path'))
self.images.pop(image_uuid)
self.connector.loc.actual.remove_node_image(self.node, self.uuid,image_uuid)
def __add_flavor(self, manifest):
#
fl_uuid = manifest.get('uuid')
self.flavors.update({fl_uuid: manifest})
self.connector.loc.actual.add_node_flavor(self.node, self.uuid, fl_uuid, manifest)
#
def __remove_flavor(self, flavor_uuid):
self.flavors.pop(flavor_uuid)
self.connector.loc.actual.remove_node_flavor(self.node, self.uuid,flavor_uuid)
def __random_mac_generator(self):
mac = [0x00, 0x16, 0x3e,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff)]
return ':'.join(map(lambda x: '%02x' % x, mac))
def __lookup_by_uuid(self, uuid):
try:
domains = self.conn.listAllDomains(0)
except libvirt.libvirtError as err:
self.conn = libvirt.open('qemu:///system')
domains = self.conn.listAllDomains(0)
if len(domains) != 0:
for domain in domains:
if str(uuid) == domain.UUIDString():
return domain
else:
return None