Skip to content

Commit c39b44f

Browse files
committed
Add VM cache scanning script
Signed-off-by: Tu Dinh <ngoc-tu.dinh@vates.tech>
1 parent 1b8053c commit c39b44f

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

scripts/scan_cache.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#!/usr/bin/env python3
2+
3+
import contextlib
4+
import re
5+
6+
import XenAPI
7+
8+
# Scan the current pool for test images that are not described in vm_data.py.
9+
# Deleting them is up to the user.
10+
11+
12+
@contextlib.contextmanager
13+
def xapi_session(uname="root", pwd=""):
14+
session = XenAPI.xapi_local()
15+
session.xenapi.login_with_password(uname, pwd, XenAPI.API_VERSION_1_2, "scan_cache.py")
16+
try:
17+
yield session
18+
finally:
19+
session.xenapi.logout()
20+
21+
22+
def strip_suffix(string, suffix):
23+
if string.endswith(suffix):
24+
return string[: -len(suffix)]
25+
return string
26+
27+
28+
def get_cache_url(vm):
29+
if type(vm) is tuple:
30+
url = vm[1]
31+
else:
32+
url = vm
33+
return strip_suffix(url, '.xva')
34+
35+
36+
def get_image_urls():
37+
from vm_data import VMS
38+
39+
image_urls = set()
40+
for vm in dict(VMS["single"]).values():
41+
image_urls.add(get_cache_url(vm))
42+
for vms in dict(VMS["multi"]).values():
43+
for vm in vms:
44+
image_urls.add(get_cache_url(vm))
45+
return image_urls
46+
47+
48+
def get_vm_type(session, vm_ref):
49+
vm_type = "VM"
50+
if session.xenapi.VM.get_is_control_domain(vm_ref):
51+
vm_type = "control domain"
52+
elif session.xenapi.VM.get_is_default_template(vm_ref):
53+
vm_type = "default template"
54+
elif session.xenapi.VM.get_is_a_snapshot(vm_ref):
55+
vm_type = "snapshot"
56+
elif session.xenapi.VM.get_is_a_template(vm_ref):
57+
vm_type = "template"
58+
return vm_type
59+
60+
61+
def main():
62+
image_urls = get_image_urls()
63+
64+
with xapi_session() as session:
65+
for vm_ref in session.xenapi.VM.get_all():
66+
if get_vm_type(session, vm_ref) != "VM":
67+
continue
68+
description = session.xenapi.VM.get_name_description(vm_ref)
69+
m = re.match(r'\[Cache for (.*)\]', description)
70+
if not m:
71+
continue
72+
current_url = m.group(1)
73+
if current_url in image_urls:
74+
continue
75+
uuid = session.xenapi.VM.get_uuid(vm_ref)
76+
label = session.xenapi.VM.get_name_label(vm_ref)
77+
print(f"{uuid} {label} {description}")
78+
79+
80+
if __name__ == "__main__":
81+
main()

0 commit comments

Comments
 (0)