-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
rhevm.py
1505 lines (1358 loc) · 49.4 KB
/
rhevm.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2016, Timothy Vandenbrande <timothy.vandenbrande@gmail.com>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r"""
module: rhevm
short_description: RHEV/oVirt automation
description:
- This module only supports oVirt/RHEV version 3.
- A newer module M(ovirt.ovirt.ovirt_vm) supports oVirt/RHV version 4.
- Allows you to create/remove/update or powermanage virtual machines on a RHEV/oVirt platform.
requirements:
- ovirtsdk
author:
- Timothy Vandenbrande (@TimothyVandenbrande)
extends_documentation_fragment:
- community.general.attributes
attributes:
check_mode:
support: none
diff_mode:
support: none
options:
user:
description:
- The user to authenticate with.
type: str
default: admin@internal
password:
description:
- The password for user authentication.
type: str
required: true
server:
description:
- The name/IP of your RHEV-m/oVirt instance.
type: str
default: 127.0.0.1
port:
description:
- The port on which the API is reachable.
type: int
default: 443
insecure_api:
description:
- A boolean switch to make a secure or insecure connection to the server.
type: bool
default: false
name:
description:
- The name of the VM.
type: str
cluster:
description:
- The RHEV/oVirt cluster in which you want you VM to start.
type: str
default: ''
datacenter:
description:
- The RHEV/oVirt datacenter in which you want you VM to start.
type: str
default: Default
state:
description:
- This serves to create/remove/update or powermanage your VM.
type: str
choices: [absent, cd, down, info, ping, present, restarted, up]
default: present
image:
description:
- The template to use for the VM.
type: str
type:
description:
- To define if the VM is a server or desktop.
type: str
choices: [desktop, host, server]
default: server
vmhost:
description:
- The host you wish your VM to run on.
type: str
vmcpu:
description:
- The number of CPUs you want in your VM.
type: int
default: 2
cpu_share:
description:
- This parameter is used to configure the CPU share.
type: int
default: 0
vmmem:
description:
- The amount of memory you want your VM to use (in GB).
type: int
default: 1
osver:
description:
- The operating system option in RHEV/oVirt.
type: str
default: rhel_6x64
mempol:
description:
- The minimum amount of memory you wish to reserve for this system.
type: int
default: 1
vm_ha:
description:
- To make your VM High Available.
type: bool
default: true
disks:
description:
- This option uses complex arguments and is a list of disks with the options V(name), V(size), and V(domain).
type: list
elements: str
ifaces:
description:
- This option uses complex arguments and is a list of interfaces with the options V(name) and V(vlan).
type: list
elements: str
aliases: [interfaces, nics]
boot_order:
description:
- This option uses complex arguments and is a list of items that specify the bootorder.
type: list
elements: str
default: [hd, network]
del_prot:
description:
- This option sets the delete protection checkbox.
type: bool
default: true
cd_drive:
description:
- The CD you wish to have mounted on the VM when O(state=cd).
type: str
timeout:
description:
- The timeout you wish to define for power actions.
- When O(state=up).
- When O(state=down).
- When O(state=restarted).
type: int
"""
RETURN = r"""
vm:
description: Returns all of the VMs variables and execution.
returned: always
type: dict
sample: {
"boot_order": [
"hd",
"network"
],
"changed": true,
"changes": [
"Delete Protection"
],
"cluster": "C1",
"cpu_share": "0",
"created": false,
"datacenter": "Default",
"del_prot": true,
"disks": [
{
"domain": "ssd-san",
"name": "OS",
"size": 40
}
],
"eth0": "00:00:5E:00:53:00",
"eth1": "00:00:5E:00:53:01",
"eth2": "00:00:5E:00:53:02",
"exists": true,
"failed": false,
"ifaces": [
{
"name": "eth0",
"vlan": "Management"
},
{
"name": "eth1",
"vlan": "Internal"
},
{
"name": "eth2",
"vlan": "External"
}
],
"image": false,
"mempol": "0",
"msg": [
"VM exists",
"cpu_share was already set to 0",
"VM high availability was already set to True",
"The boot order has already been set",
"VM delete protection has been set to True",
"Disk web2_Disk0_OS already exists",
"The VM starting host was already set to host416"
],
"name": "web2",
"type": "server",
"uuid": "4ba5a1be-e60b-4368-9533-920f156c817b",
"vm_ha": true,
"vmcpu": "4",
"vmhost": "host416",
"vmmem": "16"
}
"""
EXAMPLES = r"""
- name: Basic get info from VM
community.general.rhevm:
server: rhevm01
user: '{{ rhev.admin.name }}'
password: '{{ rhev.admin.pass }}'
name: demo
state: info
- name: Basic create example from image
community.general.rhevm:
server: rhevm01
user: '{{ rhev.admin.name }}'
password: '{{ rhev.admin.pass }}'
name: demo
cluster: centos
image: centos7_x64
state: present
- name: Power management
community.general.rhevm:
server: rhevm01
user: '{{ rhev.admin.name }}'
password: '{{ rhev.admin.pass }}'
cluster: RH
name: uptime_server
image: centos7_x64
state: down
- name: Multi disk, multi nic create example
community.general.rhevm:
server: rhevm01
user: '{{ rhev.admin.name }}'
password: '{{ rhev.admin.pass }}'
cluster: RH
name: server007
type: server
vmcpu: 4
vmmem: 2
ifaces:
- name: eth0
vlan: vlan2202
- name: eth1
vlan: vlan36
- name: eth2
vlan: vlan38
- name: eth3
vlan: vlan2202
disks:
- name: root
size: 10
domain: ssd-san
- name: swap
size: 10
domain: 15kiscsi-san
- name: opt
size: 10
domain: 15kiscsi-san
- name: var
size: 10
domain: 10kiscsi-san
- name: home
size: 10
domain: sata-san
boot_order:
- network
- hd
state: present
- name: Add a CD to the disk cd_drive
community.general.rhevm:
user: '{{ rhev.admin.name }}'
password: '{{ rhev.admin.pass }}'
name: server007
cd_drive: rhev-tools-setup.iso
state: cd
- name: New host deployment + host network configuration
community.general.rhevm:
password: '{{ rhevm.admin.pass }}'
name: ovirt_node007
type: host
cluster: rhevm01
ifaces:
- name: em1
- name: em2
- name: p3p1
ip: 172.31.224.200
netmask: 255.255.254.0
- name: p3p2
ip: 172.31.225.200
netmask: 255.255.254.0
- name: bond0
bond:
- em1
- em2
network: rhevm
ip: 172.31.222.200
netmask: 255.255.255.0
management: true
- name: bond0.36
network: vlan36
ip: 10.2.36.200
netmask: 255.255.254.0
gateway: 10.2.36.254
- name: bond0.2202
network: vlan2202
- name: bond0.38
network: vlan38
state: present
"""
import time
try:
from ovirtsdk.api import API
from ovirtsdk.xml import params
HAS_SDK = True
except ImportError:
HAS_SDK = False
from ansible.module_utils.basic import AnsibleModule
RHEV_FAILED = 1
RHEV_SUCCESS = 0
RHEV_UNAVAILABLE = 2
RHEV_TYPE_OPTS = ['desktop', 'host', 'server']
STATE_OPTS = ['absent', 'cd', 'down', 'info', 'ping', 'present', 'restart', 'up']
msg = []
changed = False
failed = False
class RHEVConn(object):
'Connection to RHEV-M'
def __init__(self, module):
self.module = module
user = module.params.get('user')
password = module.params.get('password')
server = module.params.get('server')
port = module.params.get('port')
insecure_api = module.params.get('insecure_api')
url = "https://%s:%s" % (server, port)
try:
api = API(url=url, username=user, password=password, insecure=str(insecure_api))
api.test()
self.conn = api
except Exception:
raise Exception("Failed to connect to RHEV-M.")
def __del__(self):
self.conn.disconnect()
def createVMimage(self, name, cluster, template):
try:
vmparams = params.VM(
name=name,
cluster=self.conn.clusters.get(name=cluster),
template=self.conn.templates.get(name=template),
disks=params.Disks(clone=True)
)
self.conn.vms.add(vmparams)
setMsg("VM is created")
setChanged()
return True
except Exception as e:
setMsg("Failed to create VM")
setMsg(str(e))
setFailed()
return False
def createVM(self, name, cluster, os, actiontype):
try:
vmparams = params.VM(
name=name,
cluster=self.conn.clusters.get(name=cluster),
os=params.OperatingSystem(type_=os),
template=self.conn.templates.get(name="Blank"),
type_=actiontype
)
self.conn.vms.add(vmparams)
setMsg("VM is created")
setChanged()
return True
except Exception as e:
setMsg("Failed to create VM")
setMsg(str(e))
setFailed()
return False
def createDisk(self, vmname, diskname, disksize, diskdomain, diskinterface, diskformat, diskallocationtype, diskboot):
VM = self.get_VM(vmname)
newdisk = params.Disk(
name=diskname,
size=1024 * 1024 * 1024 * int(disksize),
wipe_after_delete=True,
sparse=diskallocationtype,
interface=diskinterface,
format=diskformat,
bootable=diskboot,
storage_domains=params.StorageDomains(
storage_domain=[self.get_domain(diskdomain)]
)
)
try:
VM.disks.add(newdisk)
VM.update()
setMsg("Successfully added disk " + diskname)
setChanged()
except Exception as e:
setFailed()
setMsg("Error attaching " + diskname + "disk, please recheck and remove any leftover configuration.")
setMsg(str(e))
return False
try:
currentdisk = VM.disks.get(name=diskname)
attempt = 1
while currentdisk.status.state != 'ok':
currentdisk = VM.disks.get(name=diskname)
if attempt == 100:
setMsg("Error, disk %s, state %s" % (diskname, str(currentdisk.status.state)))
raise Exception()
else:
attempt += 1
time.sleep(2)
setMsg("The disk " + diskname + " is ready.")
except Exception as e:
setFailed()
setMsg("Error getting the state of " + diskname + ".")
setMsg(str(e))
return False
return True
def createNIC(self, vmname, nicname, vlan, interface):
VM = self.get_VM(vmname)
CLUSTER = self.get_cluster_byid(VM.cluster.id)
DC = self.get_DC_byid(CLUSTER.data_center.id)
newnic = params.NIC(
name=nicname,
network=DC.networks.get(name=vlan),
interface=interface
)
try:
VM.nics.add(newnic)
VM.update()
setMsg("Successfully added iface " + nicname)
setChanged()
except Exception as e:
setFailed()
setMsg("Error attaching " + nicname + " iface, please recheck and remove any leftover configuration.")
setMsg(str(e))
return False
try:
currentnic = VM.nics.get(name=nicname)
attempt = 1
while currentnic.active is not True:
currentnic = VM.nics.get(name=nicname)
if attempt == 100:
setMsg("Error, iface %s, state %s" % (nicname, str(currentnic.active)))
raise Exception()
else:
attempt += 1
time.sleep(2)
setMsg("The iface " + nicname + " is ready.")
except Exception as e:
setFailed()
setMsg("Error getting the state of " + nicname + ".")
setMsg(str(e))
return False
return True
def get_DC(self, dc_name):
return self.conn.datacenters.get(name=dc_name)
def get_DC_byid(self, dc_id):
return self.conn.datacenters.get(id=dc_id)
def get_VM(self, vm_name):
return self.conn.vms.get(name=vm_name)
def get_cluster_byid(self, cluster_id):
return self.conn.clusters.get(id=cluster_id)
def get_cluster(self, cluster_name):
return self.conn.clusters.get(name=cluster_name)
def get_domain_byid(self, dom_id):
return self.conn.storagedomains.get(id=dom_id)
def get_domain(self, domain_name):
return self.conn.storagedomains.get(name=domain_name)
def get_disk(self, disk):
return self.conn.disks.get(disk)
def get_network(self, dc_name, network_name):
return self.get_DC(dc_name).networks.get(network_name)
def get_network_byid(self, network_id):
return self.conn.networks.get(id=network_id)
def get_NIC(self, vm_name, nic_name):
return self.get_VM(vm_name).nics.get(nic_name)
def get_Host(self, host_name):
return self.conn.hosts.get(name=host_name)
def get_Host_byid(self, host_id):
return self.conn.hosts.get(id=host_id)
def set_Memory(self, name, memory):
VM = self.get_VM(name)
VM.memory = int(int(memory) * 1024 * 1024 * 1024)
try:
VM.update()
setMsg("The Memory has been updated.")
setChanged()
return True
except Exception as e:
setMsg("Failed to update memory.")
setMsg(str(e))
setFailed()
return False
def set_Memory_Policy(self, name, memory_policy):
VM = self.get_VM(name)
VM.memory_policy.guaranteed = int(memory_policy) * 1024 * 1024 * 1024
try:
VM.update()
setMsg("The memory policy has been updated.")
setChanged()
return True
except Exception as e:
setMsg("Failed to update memory policy.")
setMsg(str(e))
setFailed()
return False
def set_CPU(self, name, cpu):
VM = self.get_VM(name)
VM.cpu.topology.cores = int(cpu)
try:
VM.update()
setMsg("The number of CPUs has been updated.")
setChanged()
return True
except Exception as e:
setMsg("Failed to update the number of CPUs.")
setMsg(str(e))
setFailed()
return False
def set_CPU_share(self, name, cpu_share):
VM = self.get_VM(name)
VM.cpu_shares = int(cpu_share)
try:
VM.update()
setMsg("The CPU share has been updated.")
setChanged()
return True
except Exception as e:
setMsg("Failed to update the CPU share.")
setMsg(str(e))
setFailed()
return False
def set_Disk(self, diskname, disksize, diskinterface, diskboot):
DISK = self.get_disk(diskname)
setMsg("Checking disk " + diskname)
if DISK.get_bootable() != diskboot:
try:
DISK.set_bootable(diskboot)
setMsg("Updated the boot option on the disk.")
setChanged()
except Exception as e:
setMsg("Failed to set the boot option on the disk.")
setMsg(str(e))
setFailed()
return False
else:
setMsg("The boot option of the disk is correct")
if int(DISK.size) < (1024 * 1024 * 1024 * int(disksize)):
try:
DISK.size = (1024 * 1024 * 1024 * int(disksize))
setMsg("Updated the size of the disk.")
setChanged()
except Exception as e:
setMsg("Failed to update the size of the disk.")
setMsg(str(e))
setFailed()
return False
elif int(DISK.size) > (1024 * 1024 * 1024 * int(disksize)):
setMsg("Shrinking disks is not supported")
setFailed()
return False
else:
setMsg("The size of the disk is correct")
if str(DISK.interface) != str(diskinterface):
try:
DISK.interface = diskinterface
setMsg("Updated the interface of the disk.")
setChanged()
except Exception as e:
setMsg("Failed to update the interface of the disk.")
setMsg(str(e))
setFailed()
return False
else:
setMsg("The interface of the disk is correct")
return True
def set_NIC(self, vmname, nicname, newname, vlan, interface):
NIC = self.get_NIC(vmname, nicname)
VM = self.get_VM(vmname)
CLUSTER = self.get_cluster_byid(VM.cluster.id)
DC = self.get_DC_byid(CLUSTER.data_center.id)
NETWORK = self.get_network(str(DC.name), vlan)
checkFail()
if NIC.name != newname:
NIC.name = newname
setMsg('Updating iface name to ' + newname)
setChanged()
if str(NIC.network.id) != str(NETWORK.id):
NIC.set_network(NETWORK)
setMsg('Updating iface network to ' + vlan)
setChanged()
if NIC.interface != interface:
NIC.interface = interface
setMsg('Updating iface interface to ' + interface)
setChanged()
try:
NIC.update()
setMsg('iface has successfully been updated.')
except Exception as e:
setMsg("Failed to update the iface.")
setMsg(str(e))
setFailed()
return False
return True
def set_DeleteProtection(self, vmname, del_prot):
VM = self.get_VM(vmname)
VM.delete_protected = del_prot
try:
VM.update()
setChanged()
except Exception as e:
setMsg("Failed to update delete protection.")
setMsg(str(e))
setFailed()
return False
return True
def set_BootOrder(self, vmname, boot_order):
VM = self.get_VM(vmname)
bootorder = []
for device in boot_order:
bootorder.append(params.Boot(dev=device))
VM.os.boot = bootorder
try:
VM.update()
setChanged()
except Exception as e:
setMsg("Failed to update the boot order.")
setMsg(str(e))
setFailed()
return False
return True
def set_Host(self, host_name, cluster, ifaces):
HOST = self.get_Host(host_name)
CLUSTER = self.get_cluster(cluster)
if HOST is None:
setMsg("Host does not exist.")
ifacelist = dict()
networklist = []
manageip = ''
try:
for iface in ifaces:
try:
setMsg('creating host interface ' + iface['name'])
if 'management' in iface:
manageip = iface['ip']
if 'boot_protocol' not in iface:
if 'ip' in iface:
iface['boot_protocol'] = 'static'
else:
iface['boot_protocol'] = 'none'
if 'ip' not in iface:
iface['ip'] = ''
if 'netmask' not in iface:
iface['netmask'] = ''
if 'gateway' not in iface:
iface['gateway'] = ''
if 'network' in iface:
if 'bond' in iface:
bond = []
for slave in iface['bond']:
bond.append(ifacelist[slave])
try:
tmpiface = params.Bonding(
slaves=params.Slaves(host_nic=bond),
options=params.Options(
option=[
params.Option(name='miimon', value='100'),
params.Option(name='mode', value='4')
]
)
)
except Exception as e:
setMsg('Failed to create the bond for ' + iface['name'])
setFailed()
setMsg(str(e))
return False
try:
tmpnetwork = params.HostNIC(
network=params.Network(name=iface['network']),
name=iface['name'],
boot_protocol=iface['boot_protocol'],
ip=params.IP(
address=iface['ip'],
netmask=iface['netmask'],
gateway=iface['gateway']
),
override_configuration=True,
bonding=tmpiface)
networklist.append(tmpnetwork)
setMsg('Applying network ' + iface['name'])
except Exception as e:
setMsg('Failed to set' + iface['name'] + ' as network interface')
setFailed()
setMsg(str(e))
return False
else:
tmpnetwork = params.HostNIC(
network=params.Network(name=iface['network']),
name=iface['name'],
boot_protocol=iface['boot_protocol'],
ip=params.IP(
address=iface['ip'],
netmask=iface['netmask'],
gateway=iface['gateway']
))
networklist.append(tmpnetwork)
setMsg('Applying network ' + iface['name'])
else:
tmpiface = params.HostNIC(
name=iface['name'],
network=params.Network(),
boot_protocol=iface['boot_protocol'],
ip=params.IP(
address=iface['ip'],
netmask=iface['netmask'],
gateway=iface['gateway']
))
ifacelist[iface['name']] = tmpiface
except Exception as e:
setMsg('Failed to set ' + iface['name'])
setFailed()
setMsg(str(e))
return False
except Exception as e:
setMsg('Failed to set networks')
setMsg(str(e))
setFailed()
return False
if manageip == '':
setMsg('No management network is defined')
setFailed()
return False
try:
HOST = params.Host(name=host_name, address=manageip, cluster=CLUSTER, ssh=params.SSH(authentication_method='publickey'))
if self.conn.hosts.add(HOST):
setChanged()
HOST = self.get_Host(host_name)
state = HOST.status.state
while (state != 'non_operational' and state != 'up'):
HOST = self.get_Host(host_name)
state = HOST.status.state
time.sleep(1)
if state == 'non_responsive':
setMsg('Failed to add host to RHEVM')
setFailed()
return False
setMsg('status host: up')
time.sleep(5)
HOST = self.get_Host(host_name)
state = HOST.status.state
setMsg('State before setting to maintenance: ' + str(state))
HOST.deactivate()
while state != 'maintenance':
HOST = self.get_Host(host_name)
state = HOST.status.state
time.sleep(1)
setMsg('status host: maintenance')
try:
HOST.nics.setupnetworks(params.Action(
force=True,
check_connectivity=False,
host_nics=params.HostNics(host_nic=networklist)
))
setMsg('nics are set')
except Exception as e:
setMsg('Failed to apply networkconfig')
setFailed()
setMsg(str(e))
return False
try:
HOST.commitnetconfig()
setMsg('Network config is saved')
except Exception as e:
setMsg('Failed to save networkconfig')
setFailed()
setMsg(str(e))
return False
except Exception as e:
if 'The Host name is already in use' in str(e):
setMsg("Host already exists")
else:
setMsg("Failed to add host")
setFailed()
setMsg(str(e))
return False
HOST.activate()
while state != 'up':
HOST = self.get_Host(host_name)
state = HOST.status.state
time.sleep(1)
if state == 'non_responsive':
setMsg('Failed to apply networkconfig.')
setFailed()
return False
setMsg('status host: up')
else:
setMsg("Host exists.")
return True
def del_NIC(self, vmname, nicname):
return self.get_NIC(vmname, nicname).delete()
def remove_VM(self, vmname):
VM = self.get_VM(vmname)
try:
VM.delete()
except Exception as e:
setMsg("Failed to remove VM.")
setMsg(str(e))
setFailed()
return False
return True
def start_VM(self, vmname, timeout):
VM = self.get_VM(vmname)
try:
VM.start()
except Exception as e:
setMsg("Failed to start VM.")
setMsg(str(e))
setFailed()
return False
return self.wait_VM(vmname, "up", timeout)
def wait_VM(self, vmname, state, timeout):
VM = self.get_VM(vmname)
while VM.status.state != state:
VM = self.get_VM(vmname)
time.sleep(10)
if timeout is not False:
timeout -= 10
if timeout <= 0:
setMsg("Timeout expired")
setFailed()
return False
return True
def stop_VM(self, vmname, timeout):
VM = self.get_VM(vmname)
try:
VM.stop()
except Exception as e:
setMsg("Failed to stop VM.")
setMsg(str(e))
setFailed()
return False
return self.wait_VM(vmname, "down", timeout)
def set_CD(self, vmname, cd_drive):
VM = self.get_VM(vmname)
try:
if str(VM.status.state) == 'down':
cdrom = params.CdRom(file=cd_drive)
VM.cdroms.add(cdrom)
setMsg("Attached the image.")
setChanged()
else:
cdrom = VM.cdroms.get(id="00000000-0000-0000-0000-000000000000")
cdrom.set_file(cd_drive)
cdrom.update(current=True)
setMsg("Attached the image.")
setChanged()
except Exception as e:
setMsg("Failed to attach image.")
setMsg(str(e))
setFailed()
return False
return True
def set_VM_Host(self, vmname, vmhost):
VM = self.get_VM(vmname)
HOST = self.get_Host(vmhost)
try:
VM.placement_policy.host = HOST
VM.update()
setMsg("Set startup host to " + vmhost)
setChanged()
except Exception as e:
setMsg("Failed to set startup host.")
setMsg(str(e))
setFailed()
return False
return True
def migrate_VM(self, vmname, vmhost):
VM = self.get_VM(vmname)
HOST = self.get_Host_byid(VM.host.id)
if str(HOST.name) != vmhost:
try:
VM.migrate(
action=params.Action(
host=params.Host(
name=vmhost,
)
),
)
setChanged()
setMsg("VM migrated to " + vmhost)
except Exception as e:
setMsg("Failed to set startup host.")
setMsg(str(e))
setFailed()
return False
return True
def remove_CD(self, vmname):
VM = self.get_VM(vmname)
try:
VM.cdroms.get(id="00000000-0000-0000-0000-000000000000").delete()
setMsg("Removed the image.")
setChanged()
except Exception as e:
setMsg("Failed to remove the image.")
setMsg(str(e))
setFailed()
return False
return True