-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhost_thread.py
1692 lines (1516 loc) · 77.6 KB
/
host_thread.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
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
# -*- coding: utf-8 -*-
##
# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
# This file is part of openmano
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# For those usages not covered by the Apache License, Version 2.0 please
# contact with: nfvlabs@tid.es
##
'''
This is thread that interact with the host and the libvirt to manage VM
One thread will be launched per host
'''
__author__="Pablo Montes, Alfonso Tierno"
__date__ ="$10-jul-2014 12:07:15$"
import json
import yaml
import threading
import time
import Queue
import paramiko
from jsonschema import validate as js_v, exceptions as js_e
import libvirt
from vim_schema import localinfo_schema, hostinfo_schema
import random
#from logging import Logger
#import utils.auxiliary_functions as af
#TODO: insert a logging system
class host_thread(threading.Thread):
def __init__(self, name, host, user, db, db_lock, test, image_path, host_id, version, develop_mode, develop_bridge_iface):
'''Init a thread.
Arguments:
'id' number of thead
'name' name of thread
'host','user': host ip or name to manage and user
'db', 'db_lock': database class and lock to use it in exclusion
'''
threading.Thread.__init__(self)
self.name = name
self.host = host
self.user = user
self.db = db
self.db_lock = db_lock
self.test = test
self.develop_mode = develop_mode
self.develop_bridge_iface = develop_bridge_iface
self.image_path = image_path
self.host_id = host_id
self.version = version
self.xml_level = 0
#self.pending ={}
self.server_status = {} #dictionary with pairs server_uuid:server_status
self.pending_terminate_server =[] #list with pairs (time,server_uuid) time to send a terminate for a server being destroyed
self.next_update_server_status = 0 #time when must be check servers status
self.hostinfo = None
self.queueLock = threading.Lock()
self.taskQueue = Queue.Queue(2000)
def ssh_connect(self):
try:
#Connect SSH
self.ssh_conn = paramiko.SSHClient()
self.ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh_conn.load_system_host_keys()
self.ssh_conn.connect(self.host, username=self.user, timeout=10) #, None)
except paramiko.ssh_exception.SSHException as e:
text = e.args[0]
print self.name, ": ssh_connect ssh Exception:", text
def load_localinfo(self):
if not self.test:
try:
#Connect SSH
self.ssh_connect()
command = 'mkdir -p ' + self.image_path
#print self.name, ': command:', command
(_, stdout, stderr) = self.ssh_conn.exec_command(command)
content = stderr.read()
if len(content) > 0:
print self.name, ': command:', command, "stderr:", content
command = 'cat ' + self.image_path + '/.openvim.yaml'
#print self.name, ': command:', command
(_, stdout, stderr) = self.ssh_conn.exec_command(command)
content = stdout.read()
if len(content) == 0:
print self.name, ': command:', command, "stderr:", stderr.read()
raise paramiko.ssh_exception.SSHException("Error empty file ")
self.localinfo = yaml.load(content)
js_v(self.localinfo, localinfo_schema)
self.localinfo_dirty=False
if 'server_files' not in self.localinfo:
self.localinfo['server_files'] = {}
print self.name, ': localinfo load from host'
return
except paramiko.ssh_exception.SSHException as e:
text = e.args[0]
print self.name, ": load_localinfo ssh Exception:", text
except libvirt.libvirtError as e:
text = e.get_error_message()
print self.name, ": load_localinfo libvirt Exception:", text
except yaml.YAMLError as exc:
text = ""
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
text = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
print self.name, ": load_localinfo yaml format Exception", text
except js_e.ValidationError as e:
text = ""
if len(e.path)>0: text=" at '" + ":".join(map(str, e.path))+"'"
print self.name, ": load_localinfo format Exception:", text, e.message
except Exception as e:
text = str(e)
print self.name, ": load_localinfo Exception:", text
#not loaded, insert a default data and force saving by activating dirty flag
self.localinfo = {'files':{}, 'server_files':{} }
#self.localinfo_dirty=True
self.localinfo_dirty=False
def load_hostinfo(self):
if self.test:
return;
try:
#Connect SSH
self.ssh_connect()
command = 'cat ' + self.image_path + '/hostinfo.yaml'
#print self.name, ': command:', command
(_, stdout, stderr) = self.ssh_conn.exec_command(command)
content = stdout.read()
if len(content) == 0:
print self.name, ': command:', command, "stderr:", stderr.read()
raise paramiko.ssh_exception.SSHException("Error empty file ")
self.hostinfo = yaml.load(content)
js_v(self.hostinfo, hostinfo_schema)
print self.name, ': hostlinfo load from host', self.hostinfo
return
except paramiko.ssh_exception.SSHException as e:
text = e.args[0]
print self.name, ": load_hostinfo ssh Exception:", text
except libvirt.libvirtError as e:
text = e.get_error_message()
print self.name, ": load_hostinfo libvirt Exception:", text
except yaml.YAMLError as exc:
text = ""
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
text = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
print self.name, ": load_hostinfo yaml format Exception", text
except js_e.ValidationError as e:
text = ""
if len(e.path)>0: text=" at '" + ":".join(map(str, e.path))+"'"
print self.name, ": load_hostinfo format Exception:", text, e.message
except Exception as e:
text = str(e)
print self.name, ": load_hostinfo Exception:", text
#not loaded, insert a default data
self.hostinfo = None
def save_localinfo(self, tries=3):
if self.test:
self.localinfo_dirty = False
return
while tries>=0:
tries-=1
try:
command = 'cat > ' + self.image_path + '/.openvim.yaml'
print self.name, ': command:', command
(stdin, _, _) = self.ssh_conn.exec_command(command)
yaml.safe_dump(self.localinfo, stdin, explicit_start=True, indent=4, default_flow_style=False, tags=False, encoding='utf-8', allow_unicode=True)
self.localinfo_dirty = False
break #while tries
except paramiko.ssh_exception.SSHException as e:
text = e.args[0]
print self.name, ": save_localinfo ssh Exception:", text
if "SSH session not active" in text:
self.ssh_connect()
except libvirt.libvirtError as e:
text = e.get_error_message()
print self.name, ": save_localinfo libvirt Exception:", text
except yaml.YAMLError as exc:
text = ""
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
text = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
print self.name, ": save_localinfo yaml format Exception", text
except Exception as e:
text = str(e)
print self.name, ": save_localinfo Exception:", text
def load_servers_from_db(self):
self.db_lock.acquire()
r,c = self.db.get_table(SELECT=('uuid','status', 'image_id'), FROM='instances', WHERE={'host_id': self.host_id})
self.db_lock.release()
self.server_status = {}
if r<0:
print self.name, ": Error getting data from database:", c
return
for server in c:
self.server_status[ server['uuid'] ] = server['status']
#convert from old version to new one
if 'inc_files' in self.localinfo and server['uuid'] in self.localinfo['inc_files']:
server_files_dict = {'source file': self.localinfo['inc_files'][ server['uuid'] ] [0], 'file format':'raw' }
if server_files_dict['source file'][-5:] == 'qcow2':
server_files_dict['file format'] = 'qcow2'
self.localinfo['server_files'][ server['uuid'] ] = { server['image_id'] : server_files_dict }
if 'inc_files' in self.localinfo:
del self.localinfo['inc_files']
self.localinfo_dirty = True
def delete_unused_files(self):
'''Compares self.localinfo['server_files'] content with real servers running self.server_status obtained from database
Deletes unused entries at self.loacalinfo and the corresponding local files.
The only reason for this mismatch is the manual deletion of instances (VM) at database
'''
if self.test:
return
for uuid,images in self.localinfo['server_files'].items():
if uuid not in self.server_status:
for localfile in images.values():
try:
print self.name, ": deleting file '%s' of unused server '%s'" %(localfile['source file'], uuid)
self.delete_file(localfile['source file'])
except paramiko.ssh_exception.SSHException as e:
print self.name, ": Exception deleting file '%s': %s" %(localfile['source file'], str(e))
del self.localinfo['server_files'][uuid]
self.localinfo_dirty = True
def insert_task(self, task, *aditional):
try:
self.queueLock.acquire()
task = self.taskQueue.put( (task,) + aditional, timeout=5)
self.queueLock.release()
return 1, None
except Queue.Full:
return -1, "timeout inserting a task over host " + self.name
def run(self):
while True:
self.load_localinfo()
self.load_hostinfo()
self.load_servers_from_db()
self.delete_unused_files()
while True:
self.queueLock.acquire()
if not self.taskQueue.empty():
task = self.taskQueue.get()
else:
task = None
self.queueLock.release()
if task is None:
now=time.time()
if self.localinfo_dirty:
self.save_localinfo()
elif self.next_update_server_status < now:
self.update_servers_status()
self.next_update_server_status = now + 5
elif len(self.pending_terminate_server)>0 and self.pending_terminate_server[0][0]<now:
self.server_forceoff()
else:
time.sleep(1)
continue
if task[0] == 'instance':
print self.name, ": processing task instance", task[1]['action']
retry=0
while retry <2:
retry += 1
r=self.action_on_server(task[1], retry==2)
if r>=0:
break
elif task[0] == 'image':
pass
elif task[0] == 'exit':
print self.name, ": processing task exit"
self.terminate()
return 0
elif task[0] == 'reload':
print self.name, ": processing task reload terminating and relaunching"
self.terminate()
break
elif task[0] == 'edit-iface':
print self.name, ": processing task edit-iface port=%s, old_net=%s, new_net=%s" % (task[1], task[2], task[3])
self.edit_iface(task[1], task[2], task[3])
elif task[0] == 'restore-iface':
print self.name, ": processing task restore-iface %s mac=%s" % (task[1], task[2])
self.restore_iface(task[1], task[2])
else:
print self.name, ": unknown task", task
def server_forceoff(self, wait_until_finished=False):
while len(self.pending_terminate_server)>0:
now = time.time()
if self.pending_terminate_server[0][0]>now:
if wait_until_finished:
time.sleep(1)
continue
else:
return
req={'uuid':self.pending_terminate_server[0][1],
'action':{'terminate':'force'},
'status': None
}
self.action_on_server(req)
self.pending_terminate_server.pop(0)
def terminate(self):
try:
self.server_forceoff(True)
if self.localinfo_dirty:
self.save_localinfo()
if not self.test:
self.ssh_conn.close()
except Exception as e:
text = str(e)
print self.name, ": terminate Exception:", text
print self.name, ": exit from host_thread"
def get_local_iface_name(self, generic_name):
if self.hostinfo != None and "iface_names" in self.hostinfo and generic_name in self.hostinfo["iface_names"]:
return self.hostinfo["iface_names"][generic_name]
return generic_name
def create_xml_server(self, server, dev_list, server_metadata={}):
"""Function that implements the generation of the VM XML definition.
Additional devices are in dev_list list
The main disk is upon dev_list[0]"""
#get if operating system is Windows
windows_os = False
os_type = server_metadata.get('os_type', None)
if os_type == None and 'metadata' in dev_list[0]:
os_type = dev_list[0]['metadata'].get('os_type', None)
if os_type != None and os_type.lower() == "windows":
windows_os = True
#get type of hard disk bus
bus_ide = True if windows_os else False
bus = server_metadata.get('bus', None)
if bus == None and 'metadata' in dev_list[0]:
bus = dev_list[0]['metadata'].get('bus', None)
if bus != None:
bus_ide = True if bus=='ide' else False
self.xml_level = 0
text = "<domain type='kvm'>"
#get topology
topo = server_metadata.get('topology', None)
if topo == None and 'metadata' in dev_list[0]:
topo = dev_list[0]['metadata'].get('topology', None)
#name
name = server.get('name','') + "_" + server['uuid']
name = name[:58] #qemu impose a length limit of 59 chars or not start. Using 58
text += self.inc_tab() + "<name>" + name+ "</name>"
#uuid
text += self.tab() + "<uuid>" + server['uuid'] + "</uuid>"
numa={}
if 'extended' in server and server['extended']!=None and 'numas' in server['extended']:
numa = server['extended']['numas'][0]
#memory
use_huge = False
memory = int(numa.get('memory',0))*1024*1024 #in KiB
if memory==0:
memory = int(server['ram'])*1024;
else:
if not self.develop_mode:
use_huge = True
if memory==0:
return -1, 'No memory assigned to instance'
memory = str(memory)
text += self.tab() + "<memory unit='KiB'>" +memory+"</memory>"
text += self.tab() + "<currentMemory unit='KiB'>" +memory+ "</currentMemory>"
if use_huge:
text += self.tab()+'<memoryBacking>'+ \
self.inc_tab() + '<hugepages/>'+ \
self.dec_tab()+ '</memoryBacking>'
#cpu
use_cpu_pinning=False
vcpus = int(server.get("vcpus",0))
cpu_pinning = []
if 'cores-source' in numa:
use_cpu_pinning=True
for index in range(0, len(numa['cores-source'])):
cpu_pinning.append( [ numa['cores-id'][index], numa['cores-source'][index] ] )
vcpus += 1
if 'threads-source' in numa:
use_cpu_pinning=True
for index in range(0, len(numa['threads-source'])):
cpu_pinning.append( [ numa['threads-id'][index], numa['threads-source'][index] ] )
vcpus += 1
if 'paired-threads-source' in numa:
use_cpu_pinning=True
for index in range(0, len(numa['paired-threads-source'])):
cpu_pinning.append( [numa['paired-threads-id'][index][0], numa['paired-threads-source'][index][0] ] )
cpu_pinning.append( [numa['paired-threads-id'][index][1], numa['paired-threads-source'][index][1] ] )
vcpus += 2
if use_cpu_pinning and not self.develop_mode:
text += self.tab()+"<vcpu placement='static'>" +str(len(cpu_pinning)) +"</vcpu>" + \
self.tab()+'<cputune>'
self.xml_level += 1
for i in range(0, len(cpu_pinning)):
text += self.tab() + "<vcpupin vcpu='" +str(cpu_pinning[i][0])+ "' cpuset='" +str(cpu_pinning[i][1]) +"'/>"
text += self.dec_tab()+'</cputune>'+ \
self.tab() + '<numatune>' +\
self.inc_tab() + "<memory mode='strict' nodeset='" +str(numa['source'])+ "'/>" +\
self.dec_tab() + '</numatune>'
else:
if vcpus==0:
return -1, "Instance without number of cpus"
text += self.tab()+"<vcpu>" + str(vcpus) + "</vcpu>"
#boot
boot_cdrom = False
for dev in dev_list:
if dev['type']=='cdrom' :
boot_cdrom = True
break
text += self.tab()+ '<os>' + \
self.inc_tab() + "<type arch='x86_64' machine='pc'>hvm</type>"
if boot_cdrom:
text += self.tab() + "<boot dev='cdrom'/>"
text += self.tab() + "<boot dev='hd'/>" + \
self.dec_tab()+'</os>'
#features
text += self.tab()+'<features>'+\
self.inc_tab()+'<acpi/>' +\
self.tab()+'<apic/>' +\
self.tab()+'<pae/>'+ \
self.dec_tab() +'</features>'
if windows_os or topo=="oneSocket":
text += self.tab() + "<cpu mode='host-model'> <topology sockets='1' cores='%d' threads='1' /> </cpu>"% vcpus
else:
text += self.tab() + "<cpu mode='host-model'></cpu>"
text += self.tab() + "<clock offset='utc'/>" +\
self.tab() + "<on_poweroff>preserve</on_poweroff>" + \
self.tab() + "<on_reboot>restart</on_reboot>" + \
self.tab() + "<on_crash>restart</on_crash>"
text += self.tab() + "<devices>" + \
self.inc_tab() + "<emulator>/usr/libexec/qemu-kvm</emulator>" + \
self.tab() + "<serial type='pty'>" +\
self.inc_tab() + "<target port='0'/>" + \
self.dec_tab() + "</serial>" +\
self.tab() + "<console type='pty'>" + \
self.inc_tab()+ "<target type='serial' port='0'/>" + \
self.dec_tab()+'</console>'
if windows_os:
text += self.tab() + "<controller type='usb' index='0'/>" + \
self.tab() + "<controller type='ide' index='0'/>" + \
self.tab() + "<input type='mouse' bus='ps2'/>" + \
self.tab() + "<sound model='ich6'/>" + \
self.tab() + "<video>" + \
self.inc_tab() + "<model type='cirrus' vram='9216' heads='1'/>" + \
self.dec_tab() + "</video>" + \
self.tab() + "<memballoon model='virtio'/>" + \
self.tab() + "<input type='tablet' bus='usb'/>" #TODO revisar
#> self.tab()+'<alias name=\'hostdev0\'/>\n' +\
#> self.dec_tab()+'</hostdev>\n' +\
#> self.tab()+'<input type=\'tablet\' bus=\'usb\'/>\n'
if windows_os:
text += self.tab() + "<graphics type='vnc' port='-1' autoport='yes'/>"
else:
#If image contains 'GRAPH' include graphics
#if 'GRAPH' in image:
text += self.tab() + "<graphics type='vnc' port='-1' autoport='yes' listen='0.0.0.0'>" +\
self.inc_tab() + "<listen type='address' address='0.0.0.0'/>" +\
self.dec_tab() + "</graphics>"
vd_index = 'a'
for dev in dev_list:
bus_ide_dev = bus_ide
if dev['type']=='cdrom' or dev['type']=='disk':
if dev['type']=='cdrom':
bus_ide_dev = True
text += self.tab() + "<disk type='file' device='"+dev['type']+"'>"
if 'file format' in dev:
text += self.inc_tab() + "<driver name='qemu' type='" +dev['file format']+ "' cache='writethrough'/>"
if 'source file' in dev:
text += self.tab() + "<source file='" +dev['source file']+ "'/>"
#elif v['type'] == 'block':
# text += self.tab() + "<source dev='" + v['source'] + "'/>"
#else:
# return -1, 'Unknown disk type ' + v['type']
vpci = dev.get('vpci',None)
if vpci == None:
vpci = dev['metadata'].get('vpci',None)
text += self.pci2xml(vpci)
if bus_ide_dev:
text += self.tab() + "<target dev='hd" +vd_index+ "' bus='ide'/>" #TODO allows several type of disks
else:
text += self.tab() + "<target dev='vd" +vd_index+ "' bus='virtio'/>"
text += self.dec_tab() + '</disk>'
vd_index = chr(ord(vd_index)+1)
elif dev['type']=='xml':
dev_text = dev['xml']
if 'vpci' in dev:
dev_text = dev_text.replace('__vpci__', dev['vpci'])
if 'source file' in dev:
dev_text = dev_text.replace('__file__', dev['source file'])
if 'file format' in dev:
dev_text = dev_text.replace('__format__', dev['source file'])
if '__dev__' in dev_text:
dev_text = dev_text.replace('__dev__', vd_index)
vd_index = chr(ord(vd_index)+1)
text += dev_text
else:
return -1, 'Unknown device type ' + dev['type']
net_nb=0
bridge_interfaces = server.get('networks', [])
for v in bridge_interfaces:
#Get the brifge name
self.db_lock.acquire()
result, content = self.db.get_table(FROM='nets', SELECT=('provider',),WHERE={'uuid':v['net_id']} )
self.db_lock.release()
if result <= 0:
print "create_xml_server ERROR getting nets",result, content
return -1, content
#ALF: Allow by the moment the 'default' bridge net because is confortable for provide internet to VM
#I know it is not secure
#for v in sorted(desc['network interfaces'].itervalues()):
model = v.get("model", None)
if content[0]['provider']=='default':
text += self.tab() + "<interface type='network'>" + \
self.inc_tab() + "<source network='" +content[0]['provider']+ "'/>"
elif content[0]['provider'][0:7]=='macvtap':
text += self.tab()+"<interface type='direct'>" + \
self.inc_tab() + "<source dev='" + self.get_local_iface_name(content[0]['provider'][8:]) + "' mode='bridge'/>" + \
self.tab() + "<target dev='macvtap0'/>"
if windows_os:
text += self.tab() + "<alias name='net" + str(net_nb) + "'/>"
elif model==None:
model = "virtio"
elif content[0]['provider'][0:6]=='bridge':
text += self.tab() + "<interface type='bridge'>" + \
self.inc_tab()+"<source bridge='" +self.get_local_iface_name(content[0]['provider'][7:])+ "'/>"
if windows_os:
text += self.tab() + "<target dev='vnet" + str(net_nb)+ "'/>" +\
self.tab() + "<alias name='net" + str(net_nb)+ "'/>"
elif model==None:
model = "virtio"
else:
return -1, 'Unknown Bridge net provider ' + content[0]['provider']
if model!=None:
text += self.tab() + "<model type='" +model+ "'/>"
if v.get('mac_address', None) != None:
text+= self.tab() +"<mac address='" +v['mac_address']+ "'/>"
text += self.pci2xml(v.get('vpci',None))
text += self.dec_tab()+'</interface>'
net_nb += 1
interfaces = numa.get('interfaces', [])
net_nb=0
for v in interfaces:
if self.develop_mode: #map these interfaces to bridges
text += self.tab() + "<interface type='bridge'>" + \
self.inc_tab()+"<source bridge='" +self.develop_bridge_iface+ "'/>"
if windows_os:
text += self.tab() + "<target dev='vnet" + str(net_nb)+ "'/>" +\
self.tab() + "<alias name='net" + str(net_nb)+ "'/>"
else:
text += self.tab() + "<model type='e1000'/>" #e1000 is more probable to be supported than 'virtio'
if v.get('mac_address', None) != None:
text+= self.tab() +"<mac address='" +v['mac_address']+ "'/>"
text += self.pci2xml(v.get('vpci',None))
text += self.dec_tab()+'</interface>'
continue
if v['dedicated'] == 'yes': #passthrought
text += self.tab() + "<hostdev mode='subsystem' type='pci' managed='yes'>" + \
self.inc_tab() + "<source>"
self.inc_tab()
text += self.pci2xml(v['source'])
text += self.dec_tab()+'</source>'
text += self.pci2xml(v.get('vpci',None))
if windows_os:
text += self.tab() + "<alias name='hostdev" + str(net_nb) + "'/>"
text += self.dec_tab()+'</hostdev>'
net_nb += 1
else: #sriov_interfaces
#skip not connected interfaces
if v.get("net_id") == None:
continue
text += self.tab() + "<interface type='hostdev' managed='yes'>"
self.inc_tab()
if v.get('mac_address', None) != None:
text+= self.tab() + "<mac address='" +v['mac_address']+ "'/>"
text+= self.tab()+'<source>'
self.inc_tab()
text += self.pci2xml(v['source'])
text += self.dec_tab()+'</source>'
if v.get('vlan',None) != None:
text += self.tab() + "<vlan> <tag id='" + str(v['vlan']) + "'/> </vlan>"
text += self.pci2xml(v.get('vpci',None))
if windows_os:
text += self.tab() + "<alias name='hostdev" + str(net_nb) + "'/>"
text += self.dec_tab()+'</interface>'
text += self.dec_tab()+'</devices>'+\
self.dec_tab()+'</domain>'
return 0, text
def pci2xml(self, pci):
'''from a pci format text XXXX:XX:XX.X generates the xml content of <address>
alows an empty pci text'''
if pci is None:
return ""
first_part = pci.split(':')
second_part = first_part[2].split('.')
return self.tab() + "<address type='pci' domain='0x" + first_part[0] + \
"' bus='0x" + first_part[1] + "' slot='0x" + second_part[0] + \
"' function='0x" + second_part[1] + "'/>"
def tab(self):
"""Return indentation according to xml_level"""
return "\n" + (' '*self.xml_level)
def inc_tab(self):
"""Increment and return indentation according to xml_level"""
self.xml_level += 1
return self.tab()
def dec_tab(self):
"""Decrement and return indentation according to xml_level"""
self.xml_level -= 1
return self.tab()
def get_file_info(self, path):
command = 'ls -lL --time-style=+%Y-%m-%dT%H:%M:%S ' + path
print self.name, ': command:', command
(_, stdout, _) = self.ssh_conn.exec_command(command)
content = stdout.read()
if len(content) == 0:
return None # file does not exist
else:
return content.split(" ") #(permission, 1, owner, group, size, date, file)
def qemu_get_info(self, path):
command = 'qemu-img info ' + path
print self.name, ': command:', command
(_, stdout, stderr) = self.ssh_conn.exec_command(command)
content = stdout.read()
if len(content) == 0:
error = stderr.read()
print self.name, ": get_qemu_info error ", error
raise paramiko.ssh_exception.SSHException("Error getting qemu_info: " + error)
else:
try:
return yaml.load(content)
except yaml.YAMLError as exc:
text = ""
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
text = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
print self.name, ": get_qemu_info yaml format Exception", text
raise paramiko.ssh_exception.SSHException("Error getting qemu_info yaml format" + text)
def qemu_change_backing(self, inc_file, new_backing_file):
command = 'qemu-img rebase -u -b ' + new_backing_file + ' ' + inc_file
print self.name, ': command:', command
(_, _, stderr) = self.ssh_conn.exec_command(command)
content = stderr.read()
if len(content) == 0:
return 0
else:
print self.name, ": qemu_change_backing error: ", content
return -1
def get_notused_filename(self, proposed_name, suffix=''):
'''Look for a non existing file_name in the host
proposed_name: proposed file name, includes path
suffix: suffix to be added to the name, before the extention
'''
extension = proposed_name.rfind(".")
slash = proposed_name.rfind("/")
if extension < 0 or extension < slash: # no extension
extension = len(proposed_name)
target_name = proposed_name[:extension] + suffix + proposed_name[extension:]
info = self.get_file_info(target_name)
if info is None:
return target_name
index=0
while info is not None:
target_name = proposed_name[:extension] + suffix + "-" + str(index) + proposed_name[extension:]
index+=1
info = self.get_file_info(target_name)
return target_name
def get_notused_path(self, proposed_path, suffix=''):
'''Look for a non existing path at database for images
proposed_path: proposed file name, includes path
suffix: suffix to be added to the name, before the extention
'''
extension = proposed_path.rfind(".")
if extension < 0:
extension = len(proposed_path)
if suffix != None:
target_path = proposed_path[:extension] + suffix + proposed_path[extension:]
index=0
while True:
r,_=self.db.get_table(FROM="images",WHERE={"path":target_path})
if r<=0:
return target_path
target_path = proposed_path[:extension] + suffix + "-" + str(index) + proposed_path[extension:]
index+=1
def delete_file(self, file_name):
command = 'rm -f '+file_name
print self.name, ': command:', command
(_, _, stderr) = self.ssh_conn.exec_command(command)
error_msg = stderr.read()
if len(error_msg) > 0:
raise paramiko.ssh_exception.SSHException("Error deleting file: " + error_msg)
def copy_file(self, source, destination, perserve_time=True):
command = 'cp --no-preserve=mode '
if perserve_time: command += '--preserve=timestamps '
command += source + ' ' + destination
print self.name, ': command:', command
(_, _, stderr) = self.ssh_conn.exec_command(command)
error_msg = stderr.read()
if len(error_msg) > 0:
raise paramiko.ssh_exception.SSHException("Error copying image to local host: " + error_msg)
def copy_remote_file(self, remote_file, use_incremental):
''' Copy a file from the repository to local folder and recursively
copy the backing files in case the remote file is incremental
Read and/or modified self.localinfo['files'] that contain the
unmodified copies of images in the local path
params:
remote_file: path of remote file
use_incremental: None (leave the decision to this function), True, False
return:
local_file: name of local file
qemu_info: dict with quemu information of local file
use_incremental_out: True, False; same as use_incremental, but if None a decision is taken
'''
use_incremental_out = use_incremental
new_backing_file = None
local_file = None
#in case incremental use is not decided, take the decision depending on the image
#avoid the use of incremental if this image is already incremental
qemu_remote_info = self.qemu_get_info(remote_file)
if use_incremental_out==None:
use_incremental_out = not 'backing file' in qemu_remote_info
#copy recursivelly the backing files
if 'backing file' in qemu_remote_info:
new_backing_file, _, _ = self.copy_remote_file(qemu_remote_info['backing file'], True)
#check if remote file is present locally
if use_incremental_out and remote_file in self.localinfo['files']:
local_file = self.localinfo['files'][remote_file]
local_file_info = self.get_file_info(local_file)
remote_file_info = self.get_file_info(remote_file)
if local_file_info == None:
local_file = None
elif local_file_info[4]!=remote_file_info[4] or local_file_info[5]!=remote_file_info[5]:
#local copy of file not valid because date or size are different.
#TODO DELETE local file if this file is not used by any active virtual machine
try:
self.delete_file(local_file)
del self.localinfo['files'][remote_file]
except Exception:
pass
local_file = None
else: #check that the local file has the same backing file, or there are not backing at all
qemu_info = self.qemu_get_info(local_file)
if new_backing_file != qemu_info.get('backing file'):
local_file = None
if local_file == None: #copy the file
img_name= remote_file.split('/') [-1]
img_local = self.image_path + '/' + img_name
local_file = self.get_notused_filename(img_local)
self.copy_file(remote_file, local_file, use_incremental_out)
if use_incremental_out:
self.localinfo['files'][remote_file] = local_file
if new_backing_file:
self.qemu_change_backing(local_file, new_backing_file)
qemu_info = self.qemu_get_info(local_file)
return local_file, qemu_info, use_incremental_out
def launch_server(self, conn, server, rebuild=False, domain=None):
if self.test:
time.sleep(random.randint(20,150)) #sleep random timeto be make it a bit more real
return 0, 'Success'
server_id = server['uuid']
paused = server.get('paused','no')
try:
if domain!=None and rebuild==False:
domain.resume()
#self.server_status[server_id] = 'ACTIVE'
return 0, 'Success'
self.db_lock.acquire()
result, server_data = self.db.get_instance(server_id)
self.db_lock.release()
if result <= 0:
print self.name, ": launch_server ERROR getting server from DB",result, server_data
return result, server_data
#0: get image metadata
server_metadata = server.get('metadata', {})
use_incremental = None
if "use_incremental" in server_metadata:
use_incremental = False if server_metadata["use_incremental"]=="no" else True
server_host_files = self.localinfo['server_files'].get( server['uuid'], {})
if rebuild:
#delete previous incremental files
for file_ in server_host_files.values():
self.delete_file(file_['source file'] )
server_host_files={}
#1: obtain aditional devices (disks)
#Put as first device the main disk
devices = [ {"type":"disk", "image_id":server['image_id'], "vpci":server_metadata.get('vpci', None) } ]
if 'extended' in server_data and server_data['extended']!=None and "devices" in server_data['extended']:
devices += server_data['extended']['devices']
for dev in devices:
if dev['image_id'] == None:
continue
self.db_lock.acquire()
result, content = self.db.get_table(FROM='images', SELECT=('path','metadata'),WHERE={'uuid':dev['image_id']} )
self.db_lock.release()
if result <= 0:
error_text = "ERROR", result, content, "when getting image", dev['image_id']
print self.name, ": launch_server", error_text
return -1, error_text
if content[0]['metadata'] is not None:
dev['metadata'] = json.loads(content[0]['metadata'])
else:
dev['metadata'] = {}
if dev['image_id'] in server_host_files:
dev['source file'] = server_host_files[ dev['image_id'] ] ['source file'] #local path
dev['file format'] = server_host_files[ dev['image_id'] ] ['file format'] # raw or qcow2
continue
#2: copy image to host
remote_file = content[0]['path']
use_incremental_image = use_incremental
if dev['metadata'].get("use_incremental") == "no":
use_incremental_image = False
local_file, qemu_info, use_incremental_image = self.copy_remote_file(remote_file, use_incremental_image)
#create incremental image
if use_incremental_image:
local_file_inc = self.get_notused_filename(local_file, '.inc')
command = 'qemu-img create -f qcow2 '+local_file_inc+ ' -o backing_file='+ local_file
print 'command:', command
(_, _, stderr) = self.ssh_conn.exec_command(command)
error_msg = stderr.read()
if len(error_msg) > 0:
raise paramiko.ssh_exception.SSHException("Error creating incremental file: " + error_msg)
local_file = local_file_inc
qemu_info = {'file format':'qcow2'}
server_host_files[ dev['image_id'] ] = {'source file': local_file, 'file format': qemu_info['file format']}
dev['source file'] = local_file
dev['file format'] = qemu_info['file format']
self.localinfo['server_files'][ server['uuid'] ] = server_host_files
self.localinfo_dirty = True
#3 Create XML
result, xml = self.create_xml_server(server_data, devices, server_metadata) #local_file
if result <0:
print self.name, ": create xml server error:", xml
return -2, xml
print self.name, ": create xml:", xml
atribute = libvirt.VIR_DOMAIN_START_PAUSED if paused == "yes" else 0
#4 Start the domain
if not rebuild: #ensures that any pending destroying server is done
self.server_forceoff(True)
#print self.name, ": launching instance" #, xml
conn.createXML(xml, atribute)
#self.server_status[server_id] = 'PAUSED' if paused == "yes" else 'ACTIVE'
return 0, 'Success'
except paramiko.ssh_exception.SSHException as e:
text = e.args[0]
print self.name, ": launch_server(%s) ssh Exception: %s" %(server_id, text)
if "SSH session not active" in text:
self.ssh_connect()
except libvirt.libvirtError as e:
text = e.get_error_message()
print self.name, ": launch_server(%s) libvirt Exception: %s" %(server_id, text)
except Exception as e:
text = str(e)
print self.name, ": launch_server(%s) Exception: %s" %(server_id, text)
return -1, text
def update_servers_status(self):
# # virDomainState
# VIR_DOMAIN_NOSTATE = 0
# VIR_DOMAIN_RUNNING = 1
# VIR_DOMAIN_BLOCKED = 2
# VIR_DOMAIN_PAUSED = 3
# VIR_DOMAIN_SHUTDOWN = 4
# VIR_DOMAIN_SHUTOFF = 5
# VIR_DOMAIN_CRASHED = 6
# VIR_DOMAIN_PMSUSPENDED = 7 #TODO suspended
if self.test or len(self.server_status)==0:
return
try:
conn = libvirt.open("qemu+ssh://"+self.user+"@"+self.host+"/system")
domains= conn.listAllDomains()
domain_dict={}
for domain in domains:
uuid = domain.UUIDString() ;
libvirt_status = domain.state()
#print libvirt_status
if libvirt_status[0] == libvirt.VIR_DOMAIN_RUNNING or libvirt_status[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
new_status = "ACTIVE"
elif libvirt_status[0] == libvirt.VIR_DOMAIN_PAUSED:
new_status = "PAUSED"
elif libvirt_status[0] == libvirt.VIR_DOMAIN_SHUTOFF:
new_status = "INACTIVE"
elif libvirt_status[0] == libvirt.VIR_DOMAIN_CRASHED:
new_status = "ERROR"
else:
new_status = None
domain_dict[uuid] = new_status
conn.close
except libvirt.libvirtError as e:
print self.name, ": get_state() Exception '", e.get_error_message()
return
for server_id, current_status in self.server_status.iteritems():
new_status = None
if server_id in domain_dict:
new_status = domain_dict[server_id]
else:
new_status = "INACTIVE"
if new_status == None or new_status == current_status:
continue
if new_status == 'INACTIVE' and current_status == 'ERROR':
continue #keep ERROR status, because obviously this machine is not running
#change status
print self.name, ": server ", server_id, "status change from ", current_status, "to", new_status
STATUS={'progress':100, 'status':new_status}