-
Notifications
You must be signed in to change notification settings - Fork 1
/
proxmoxlib.py
executable file
·1657 lines (1523 loc) · 57.2 KB
/
proxmoxlib.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/env python
"""proxmoxlib module for managing promox cluster remotely"""
from datetime import datetime
import enum
import inspect
import time
from typing import Any
from urllib import parse as urllib_parse
import json
import re
import os
from dataclasses import dataclass
import configparser
import shutil
import yaml
import requests
from beautifultable import BeautifulTable
import urllib3
from termcolor import colored
from rich import print as rprint
from proxmoxer import ResourceException
from proxmoxer import ProxmoxAPI
from proxmoxer.tools import Tasks
import proxcli_exceptions
urllib3.disable_warnings()
@dataclass
class VmProperties:
"""Description of the class.
Args:
<arg> (<type>): Description of the arg.
Variables:
<variable> (<type>): Description of the variable.
"""
vmid: int
vmname: str = None
cores: int = None
memory: str = None
ipconfig: str = None
cipassword: str = None
disk_size: str = None
ciuser: str = None
sshkey: str = None
tags: str = None
@dataclass
class HaResource:
"""Description of the class.
Args:
<arg> (<type>): Description of the arg.
Variables:
<variable> (<type>): Description of the variable.
"""
sid: str
comment: str
delete: str
digest: str
group: str
max_relocate: int
max_restart: int
state: str
class Proxmox():
"""proxmox api helper"""
def __init__(self) -> None:
result = self.load_config()
self.host = ""
if result:
self.proxmox_instance = self.proxmox()
# UTILITY #
def bytesto(self, bytes, to, bsize=1024):
"""convert bytes to megabytes, etc.
sample code:
print('mb= ' + str(bytesto(314575262000000, 'm')))
sample output:
mb= 300002347.946
"""
a = {'K': 1, 'M': 2, 'G': 3, 'T': 4, 'P': 5, 'E': 6}
r = float(bytes)
for i in range(a[to]):
r = r / bsize
return r
def tobytes(self, size):
"""Description of the function/method.
Parameters:
<param>: Description of the parameter
Returns:
<variable>: Description of the return value
"""
size_name = ("B", "K", "M", "G", "T", "P", "E")
unit = size[-1]
size = int(size[:-1])
idx = size_name.index(unit)
factor = 1024 ** idx
return size * factor
def get_terminal_width(self) -> int:
"""shortcut to shutil.get_terminal_size()[0]"""
return shutil.get_terminal_size()[0]
def get_caller(self) -> str:
"""get the calling method"""
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
print(calframe)
return calframe[1][3]
def load_config(self) -> bool:
"""load configuration"""
configfile = os.path.expanduser('~') + "/.proxmox"
if os.path.exists(configfile):
config = configparser.ConfigParser()
config.read(os.path.abspath(configfile))
self.username = config["credentials"]["user"]
self.password = config["credentials"]["password"]
self.hosts = config["credentials"]["hosts"].split(",")
headers = config["headers"]
self.headers_nodes = headers["nodes"].split(",")
self.headers_qemu = headers["qemu"].split(",")
self.headers_lxc = headers["lxc"].split(",")
self.headers_storage = headers["storage"].split(",")
self.headers_tasks = headers["tasks"].split(",")
self.headers_ha_groups = headers["ha_groups"].split(",")
self.headers_ha_resources = headers["ha_resources"].split(",")
self.headers_cluster_log = headers["cluster_log"].split(",")
self.headers_cluster_status = headers["cluster_status"].split(",")
self.headers_cluster_status_node = headers[
"cluster_status_node"
].split(",")
self.headers_node_networks = headers["node_networks"].split(",")
self.headers_storage_content = headers[
"storage_content"].split(",")
self.table_style = self.get_table_style(config["data"]["style"])
self.task_polling_interval = config["tasks"]["polling_interval"]
self.task_timeout = config["tasks"]["timeout"]
self.table_colorize = dict(
[v.split(':') for v in config["data"]["colorize"].split(",")]
)
return True
else:
return False
def select_active_node(self) -> None:
"""
select the first available node
iterate over nodes, ping and set self.host property
"""
for host in self.hosts:
values = (host,)
url = f"https://{values[0]}:8006"
try:
requests.get(
url,
timeout=1,
allow_redirects=True,
verify=False
)
self.host = host
break
finally:
pass
def get_table_style(self, style) -> enum.Enum:
"""set beautiful table display style from string"""
if hasattr(BeautifulTable, style):
selected_style = getattr(BeautifulTable, style)
else:
selected_style = getattr(BeautifulTable, "STYLE_BOX")
return selected_style
def output(
self,
data,
headers=None,
output_format="internal",
save=False
) -> Any:
"""
print data on specified format
default to internal (raw data is returned instead of displaying)
"""
# immediately return data if using for internal use
if output_format == "internal":
return data
if output_format == "json":
data = json.dumps(data, indent=2)
elif output_format == "yaml":
data = yaml.dump(data)
elif output_format == "table":
data = self.table(headers=headers, data=data)
if save:
with open(file=save, encoding="utf-8", mode="w") as handle:
handle.write(str(data))
handle.close()
else:
if output_format == "yaml" or output_format == "json":
rprint(data)
else:
print(data)
def readable_date(self, timestamp) -> str:
"""convert unix timestamp to human readable date time"""
return datetime.utcfromtimestamp(
timestamp).strftime('%Y-%m-%d %H:%M:%S')
def table(self, headers, data, width=None) -> BeautifulTable:
"""
Display list of dict as table
"""
width = self.get_terminal_width() if not width else width
table = BeautifulTable(maxwidth=width)
table.set_style(self.table_style)
table.columns.header = headers
for element in data:
datarow = []
for header in headers:
if header in element:
if header == "ip" and isinstance(element[header], list):
# special element
datarow.append(self.ips_to_display(element[header]))
else:
datarow.append(element[header])
else:
datarow.append('')
new_data_row = []
for cell in datarow:
if len(str(cell)) > 0:
words = list(self.table_colorize.keys())
match = [word for word in words if word in str(cell)]
if len(match) == 1:
new_data_row.append(
colored(cell, self.table_colorize[match[0]]))
else:
new_data_row.append(cell)
else:
new_data_row.append("")
table.rows.append(tuple(new_data_row))
return table
def ismatching(self, regex, data) -> bool:
"""shortcut method used to check is a string match a regex"""
if not re.match(regex, data):
return False
else:
return True
def task_block(self, task) -> Any:
"""
Poll a task until the task is finished or timed out
Paramaters:
task (str): a task identifier
UPID:<n>:<ph>:<ps>:<st>:<t>:<id>:<u>@<r>:)
n: node name
ph: pid in hex format
ps: pstart in hex
st: start tim in hex
t: type
id: id (optional)
u: user
r: realm
Returns:
result (dict): a dict with all the task information
https://proxmoxer.github.io/docs/2.0/tools/tasks/#blocking_status
"""
print(f"Waiting for task {(task,)} to finish")
return Tasks.blocking_status(
prox=self.proxmox_instance,
task_id=task,
timeout=int(self.task_timeout),
polling_interval=float(self.task_polling_interval))
def proxmox(self) -> ProxmoxAPI:
"""create proxmox api instance from the first available node found"""
self.select_active_node()
return ProxmoxAPI(
self.host,
user=self.username,
password=self.password,
verify_ssl=False
)
# STORAGE #
def get_storages(self, output_format="json") -> Any:
"""list storages"""
# nodes = self.get_nodes(format="internal")
# nodes = [] if not nodes else nodes
# available_nodes = [n for n in nodes if n["status"] == "online"]
# if len(available_nodes) > 0:
# query_node = available_nodes[0]
# else:
# raise ProxmoxClusterDownException
all_storages = []
storages = self.proxmox_instance.storage.get()
storages = [] if not storages else storages
for storage in storages:
all_storages.append(storage)
return self.output(
headers=self.headers_storage,
data=all_storages,
output_format=output_format
)
def storages_upload(
self,
file,
proxmox_node,
storage,
content
) -> None:
"""upload image or iso file to proxmox node"""
with open(str(file), 'rb') as file_handler:
storage = self.proxmox_instance.nodes(proxmox_node).storage(
storage
)
storage.upload.post(content=content, filename=file_handler)
def set_orphaned_storage_volumes_flag(
self,
volumes
) -> Any:
"""add a flag orphaned to volumes storage list"""
virtual_machines = self.get_vms(output_format="internal")
vmids = [v["vmid"] for v in virtual_machines]
for volume in volumes:
if "vmid" in volume:
if volume["vmid"] not in vmids:
volume["orphaned"] = "YES"
else:
volume["orphaned"] = "NO"
else:
volume["orphaned"] = "N/A"
return volumes
def get_storage_content(
self,
proxmox_node,
storage,
output_format="json",
headers="",
content_type="",
content_format="",
filter_orphaned="YES,NO,N/A"
) -> Any:
"""get storage content list"""
headers = self.headers_storage_content if (
not headers or headers == "") else headers
results = []
formats = content_format.split(",") if len(content_format) > 0 else []
contents = content_type.split(",") if len(content_type) > 0 else []
results = self.proxmox_instance.nodes(
proxmox_node).storage(storage).content.get()
# filter by content and format if needed
if len(formats) > 0:
results = [result for result in results if (
result["format"] in formats
)]
if len(contents) > 0:
results = [result for result in results if (
result["content"] in contents
)]
results = self.set_orphaned_storage_volumes_flag(results)
# filter desired orphaned status
filter_orphaned = filter_orphaned.split(",")
results = [volume for volume in results if (
volume["orphaned"] in filter_orphaned
)]
headers = [] if not headers or len(headers) == 0 else headers
return self.output(
headers=headers,
data=results,
output_format=output_format
)
def clean_orphaned_storage_content(
self,
proxmox_node,
storage,
content_type,
content_format,
confirm=True
):
""" clean orphaned volumes in node storage """
orphaned = self.get_storage_content(
proxmox_node=proxmox_node,
storage=storage,
output_format="internal",
filter_orphaned="YES",
content_type=content_type,
content_format=content_format
)
delete_volume = False
for o in orphaned:
if confirm:
response = input((
f"Do you realy want to delete "
f"volume {o['volid']} ?"
))
if response:
delete_volume = True
else:
delete_volume = False
else:
delete_volume = True
if delete_volume:
print(f"delete {o['volid']}")
self.proxmox_instance.nodes(proxmox_node).storage(
storage).content(o["volid"]).delete()
# CLUSTER #
def get_cluster_status(self, output_format="internal") -> None:
"""Description of the function/method.
Parameters:
<param>: Description of the parameter
Returns:
<variable>: Description of the return value
"""
status = []
status = self.proxmox_instance.cluster.status.get()
if isinstance(status, list):
cluster_status = [
c for c in status if c["type"] == "cluster"]
cluster_status_node = [
c for c in status if c["type"] == "node"]
self.output(
output_format=output_format,
headers=self.headers_cluster_status,
data=cluster_status
)
self.output(
output_format=output_format,
headers=self.headers_cluster_status_node,
data=cluster_status_node)
def get_cluster_log(
self,
proxmox_nodes,
severities,
output_format="internal",
max_items=100
) -> Any:
"""get cluster logs
Args:
format (str, optional): _description_. Defaults to "internal".
max (int, optional): _description_. Defaults to 100.
"""
translate_severity = {
'0': "panic",
'1': "alert",
'2': "critical",
'3': "error",
'4': "warning",
'5': "notice",
'6': "info",
'7': "debug"
}
logs = self.proxmox_instance.cluster.log.get(**{'max': max_items})
if not logs:
logs = []
proxmox_nodes = [n.strip() for n in proxmox_nodes.split(",")]
severities = [s.strip() for s in severities.split(",")]
filtered_logs = []
for log in logs:
log["severity"] = translate_severity[str(log["pri"])]
log["date"] = self.readable_date(log["time"])
if log["severity"] in severities:
if len(proxmox_nodes) == 0:
filtered_logs.append(log)
else:
if log["node"] in proxmox_nodes:
filtered_logs.append(log)
if len(filtered_logs) == 0:
return
return self.output(
headers=self.headers_cluster_log,
data=filtered_logs,
output_format=output_format
)
def get_ha_groups(
self,
output_format="internal",
filter_group="^.*"
) -> Any:
"""list cluster ha groups"""
hagroups = self.proxmox_instance.cluster.ha.groups.get()
hagroups = [
hag for hag in hagroups if re.match(
pattern=filter_group,
string=hag["group"]
)
]
return self.output(
headers=self.headers_ha_groups,
data=hagroups,
output_format=output_format
)
def exists_ha_group(self, ha_group):
"""check if ha group exist"""
ha_groups = self.get_ha_groups(output_format="internal")
ha_groups = [h for h in ha_groups if h["group"] == ha_group]
return True if len(ha_groups) > 0 else False
def create_ha_group(
self,
group,
proxmox_nodes,
nofailback=False,
restricted=False
) -> None:
"""
create a hagroup
Parameters:
group (str): the ha group name
nodes (str): List of cluster node members
nofailback (bool):
restricted (bool):
type (enum):
Returns:
result (bool): true if success, false if failure
"""
nofailback = 0 if nofailback is False else 1
restricted = 0 if restricted is False else 1
self.proxmox_instance.cluster.ha.groups.post(**{
"group": group,
"nodes": proxmox_nodes,
"nofailback": nofailback,
"restricted": restricted
})
def update_ha_group(
self,
group,
proxmox_nodes=None,
nofailback=None,
restricted=None
) -> None:
""" Update an existing ha group """
if nofailback is not None:
nofailback = 0 if nofailback is False else 1
if restricted is not None:
restricted = 0 if restricted is False else 1
desired = {
"nodes": proxmox_nodes,
"nofailback": nofailback,
"restricted": restricted
}
desired = {k: v for k, v in desired.items() if v is not None}
self.proxmox_instance.cluster.ha.groups(group).put(**desired)
def delete_ha_group(self, group) -> None:
"""delete cluster ha group
Args:
group (str): cluster ha group name to delete
"""
self.proxmox_instance.cluster.ha.groups.delete(group)
def get_ha_resources(
self,
output_format="table",
filter_name="^.*$",
group=None
) -> Any:
"""retrieve a list of cluster ha resources with named cluster ha groups
Returns:
list: list of ha resources
"""
resources = self.proxmox_instance.cluster.ha.resources.get()
if not resources:
resources = []
vms = self.get_vms(output_format="internal", filter_name=filter_name)
for resource in resources:
vmid = resource["sid"].split(":")[-1]
virtual_machine = [v for v in vms if int(v["vmid"]) == int(vmid)]
if len(virtual_machine) > 0:
virtual_machine = virtual_machine[0]
resource["name"] = virtual_machine["name"]
resource["vmid"] = vmid
else:
resource["name"] = ""
resource["vmid"] = vmid
resources = [r for r in resources if re.match(filter_name, r["name"])]
if group:
resources = [r for r in resources if r["group"] == group]
return self.output(
headers=self.headers_ha_resources,
data=resources,
output_format=output_format
)
def update_ha_resource(
self,
ha_resource: HaResource
) -> None:
""" Update an existing ha group """
desired = {
"max_restart": ha_resource.max_restart,
"max_relocate": ha_resource.max_relocate
}
desired = {k: v for k, v in desired.items() if v is not None}
self.proxmox_instance.cluster.ha.resources(
ha_resource.sid
).put(**desired)
def create_ha_resource(
self,
group,
name=None,
vmid=None,
filter_name=None,
comment="",
max_relocate=1,
max_restart=1,
state="started"
) -> None:
"""add a resource to ha group"""
if name and name != "":
vms = self.get_vms(
output_format="internal",
filter_name=name
)
vms = [] if not vms else vms
for virtual_machine in vms:
print(
(
f"Adding resource {(virtual_machine['vmid'],)} "
f"to group {(group,)}"
)
)
self.proxmox_instance.cluster.ha.resources.post(**{
'sid': virtual_machine["vmid"],
'comment': comment,
'group': group,
'max_relocate': max_relocate,
'max_restart': max_restart,
'state': state
})
return
if vmid and vmid > 0:
print(f"Adding resource {(vmid,)} to group {(group,)}")
self.proxmox_instance.cluster.ha.resources.post(**{
'sid': str(vmid),
'comment': comment,
'group': group,
'max_relocate': max_relocate,
'max_restart': max_restart,
'state': state
})
return
if filter_name and filter_name != "":
vms = self.get_vms(
output_format="internal",
filter_name=filter_name
)
for vm in vms:
print(
f"Adding resource {vmid} with name "
f"{name} to group {group}"
)
self.proxmox_instance.cluster.ha.resources.post(**{
'sid': str(vm["vmid"]),
'comment': comment,
'group': group,
'max_relocate': max_relocate,
'max_restart': max_restart,
'state': state
})
return
def vm_ha_resource_managed(self, vmid):
"""checker if a vm is ha managed"""
resources = self.get_ha_resources(output_format="internal")
resources = [str(r["vmid"]) for r in resources]
return True if str(vmid) in resources else False
def delete_ha_resources_by_group_name(
self,
group
) -> None:
"""Description of the function/method.
Parameters:
<param>: Description of the parameter
Returns:
<variable>: Description of the return value
"""
resources = self.get_ha_resources(
output_format="internal",
filter_name="^.*"
)
resources = [r for r in resources if r["group"] == group]
for resource in resources:
print(f"Removing resource {(resource['vmid'],)}")
ha_endpoint = self.proxmox_instance.cluster.ha
ha_endpoint.resources.delete(resource["vmid"])
def delete_ha_resources(
self,
filter_name=None,
vmid=None
) -> None:
"""delete resource from ha group"""
if filter_name:
resources = self.get_ha_resources(
output_format="internal",
filter_name=filter_name
)
for resource in resources:
if int(resource["vmid"]) > 0:
print(f"Removing resource {(resource['vmid'],)}")
ha_endpoint = self.proxmox_instance.cluster.ha
ha_endpoint.resources.delete(resource["vmid"])
return
if vmid > 0:
print(f"Removing resource {(vmid,)}")
self.proxmox_instance.cluster.ha.resources.delete(vmid)
return
def migrate_ha_resources(
self,
proxmox_node=None,
filter_name=None,
vmid=None,
block=False,
block_max_try=3
) -> None:
"""migrate a resource from ha group"""
resources = []
if filter_name and filter_name != "":
resources = self.get_ha_resources(
output_format="internal",
filter_name=filter_name
)
resources = [] if not resources else resources
if vmid and vmid > 0:
resources = [self.get_resource_by_id_or_name(vmid=vmid)]
for resource in resources:
print(
(
f"migrating resource {(resource['vmid'],)} "
f"to node {(proxmox_node,)}"
)
)
ha_group = self.proxmox_instance.cluster.ha
ha_group.resources(resource["vmid"]).migrate.post(
**{'node': proxmox_node})
if block:
current_try = 0
current_node = "unknown"
virtual_machine_status = "unknown"
print("Waiting for migration to finish")
while (
current_node != proxmox_node or
virtual_machine_status != "running" or
current_try < block_max_try
):
resource = self.get_vm_by_id_or_name(
vmid=resource["vmid"]
)
if resource and resource["node"] != proxmox_node:
vmid = resource["vmid"]
virtual_machine_status = resource["status"]
else:
break
current_try += 1
def get_resource_by_id_or_name(self, vmid=None, resource_name=None) -> Any:
"""get resource by its id or name"""
resources = self.get_ha_resources(output_format="internal")
resources = [] if not resources else resources
if vmid:
resource = [v for v in resources if v["vmid"] == int(vmid)]
else:
resource = [v for v in resources if v["name"] == resource_name]
if len(resource) == 0:
return False
return resource[0]
def relocate_ha_resources(
self,
proxmox_node,
filter_name=None,
vmid=None,
block=False,
block_max_try=3
) -> None:
"""relocate ha resource"""
print((
f"node {proxmox_node} "
f"filter {filter_name} "
f"id {vmid} "
f"block {block}"
))
resources = []
if filter_name and filter_name != "":
resources = self.get_ha_resources(
output_format="internal",
filter_name=filter_name
)
resources = [] if not resources else resources
if vmid and vmid > 0:
resources = [self.get_resource_by_id_or_name(vmid=vmid)]
for resource in resources:
print(
(
f"relocating resource {(resource['vmid'],)} "
f"to node {(proxmox_node,)}"
)
)
ha_group = self.proxmox_instance.cluster.ha
ha_group.resources(resource["vmid"]).relocate.post(
**{'node': proxmox_node})
if block:
current_try = 0
current_node = "unknown"
virtual_machine_status = "unknown"
print("Waiting for relocation to finish")
while (
current_node != proxmox_node or
virtual_machine_status != "running" or
current_try < block_max_try
):
resource = self.get_vm_by_id_or_name(
vmid=resource["vmid"]
)
if resource and resource["node"] != proxmox_node:
vmid = resource["vmid"]
virtual_machine_status = resource["status"]
else:
break
current_try += 1
# NODES #
def get_nodes(
self,
output_format="internal",
filter_name=None
) -> Any:
'''
Get all node as a list
Parameters:
TODO
Returns:
TODO
'''
proxmox_nodes = self.proxmox_instance.nodes.get()
proxmox_nodes = [] if not proxmox_nodes else proxmox_nodes
if filter_name:
proxmox_nodes = [
n for n in list(proxmox_nodes) if self.ismatching(
filter_name, n["node"]
)
]
return self.output(
headers=self.headers_nodes,
data=proxmox_nodes,
output_format=output_format
)
def get_tasks(
self,
output_format="internal",
errors=0,
limit=50,
source="all",
proxmox_nodes=None
) -> Any:
"""get tasks from nodes"""
available_nodes = self.get_nodes(output_format="internal")
available_nodes = [
n["node"] for n in available_nodes if n["status"] == "online"]
if not proxmox_nodes:
proxmox_nodes = available_nodes
else:
proxmox_nodes = proxmox_nodes.split(",")
proxmox_nodes = [n for n in proxmox_nodes if n in available_nodes]
tasks = []
for node in proxmox_nodes:
node_tasks = self.proxmox_instance.nodes(node).tasks.get(**{
"errors": errors,
"limit": limit,
"source": source,
"vmid": None
})
node_tasks = [] if not node_tasks else node_tasks
tasks += node_tasks
tasks = [t for t in tasks if t["node"] in proxmox_nodes]
tasks = sorted(tasks, key=lambda d: d['starttime'], reverse=True)
for node_tasks in tasks:
node_tasks['starttime'] = self.readable_date(
node_tasks['starttime'])
if 'endtime' in node_tasks:
node_tasks['endtime'] = self.readable_date(
node_tasks['endtime'])
else:
node_tasks['endtime'] = ""
self.output(
headers=self.headers_tasks,
data=tasks,
output_format=output_format
)
def get_nodes_network(
self,
proxmox_nodes=None,
output_format="table"
) -> Any:
"""get the default ip address from a node"""
if not proxmox_nodes:
return []
proxmox_nodes = proxmox_nodes.split(",")
networks = []
for node in proxmox_nodes:
result = self.proxmox_instance.nodes(node).network.get()
result = [] if not result else result
for net in result:
net["node"] = node
networks.append(net)
self.output(
data=networks,
output_format=output_format,
headers=self.headers_node_networks
)
# VMS #
def exists_vm(self, virtual_machine_id=None, virtual_machine_name=None) -> bool:
""" check if a vm exists by name or vmid """
vms = self.get_vms(output_format="internal")
vms = [] if not vms else vms
if virtual_machine_id:
vms = [v for v in vms if int(v["vmid"]) == int(virtual_machine_id)]
else:
vms = [v for v in vms if v["name"] == virtual_machine_name]
return True if len(vms) > 0 else False
def get_vm_by_id_or_name(self, vmid=None, vmname=None) -> Any:
"""get vm by its id or name"""
vms = self.get_vms(output_format="internal")
vms = [] if not vms else vms
virtual_machine = None
if vmid:
virtual_machine = [v for v in vms if v["vmid"] == int(vmid)]
else:
virtual_machine = [v for v in vms if v["name"] == vmname]
if len(virtual_machine) == 0:
return False
return virtual_machine[0]
def get_vms_config(self, vmid) -> Any:
"""get virtual machine config"""