forked from ispras/vmemperor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xenadapter.py
executable file
·205 lines (184 loc) · 10.1 KB
/
xenadapter.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
import XenAPI
import json
import hooks
import provision
class XenAdapter:
def __init__(self, endpoint, flask_session, login=None, password=None):
"""
@type session: XenAPI.Session
"""
self.endpoint = endpoint
url = endpoint['url']
session = XenAPI.Session(url)
if not login or not password:
if flask_session and \
url in flask_session and \
'login' in flask_session[url] and 'password' in flask_session[url]:
login = flask_session[url]['login']
password = flask_session[url]['password']
else:
raise Exception("Unauthorized")
else:
flask_session[url] = {'url': endpoint['url'], 'login': login, 'password': password}
session.login_with_password(login, password)
if session['Status'] == "Failure":
raise Exception
flask_session[url]['is_su'] = session.xenapi.session.get_is_local_superuser(session._session)
self.session = session
self.api = self.session.xenapi
def get_template_list(self):
print("Getting template list using fast method")
template_list = []
all_records = self.api.VM.get_all_records()
for record in all_records.values():
entry = dict()
for field in ['is_control_domain', 'is_a_template', 'is_a_snapshot']:
entry[field] = record[field] if field in record and record[field] != 'OpaqueRef:NULL' else None
if not entry['is_control_domain'] and entry['is_a_template'] and not entry['is_a_snapshot']:
for field in ['uuid', 'name_label', 'name_description', 'allowed_operations', 'tags', 'other_config']:
entry[field] = record[field] if field in record and record[field] != 'OpaqueRef:NULL' else None
entry['other_config']['vmemperor_hooks'] = hooks.merge_with_dict(entry['other_config'].get('vmemperor_hooks'))
entry['other_config']['vmemperor_hooks_meta'] = hooks.get_hooks_with_manifest(entry['other_config']['vmemperor_hooks'])
entry['endpoint'] = self.endpoint
if 'ubuntu' in record['name_label'].lower():
entry['default_mirror'] = 'http://mirror.yandex.ru/ubuntu/'
elif 'debian' in record['name_label'].lower():
entry['default_mirror'] = 'http://mirror.yandex.ru/debian/'
else:
entry['default_mirror'] = ''
template_list.append(entry)
return template_list
def retrieve_pool_info(self):
pool_info = dict()
networks = self.api.network.get_all_records()
# TODO: implement filtering by tags some time
pool_info["networks"] = []
for net in networks.values():
if net["name_label"] == "Host internal management network":
continue
pool_info["networks"].append({"uuid": net["uuid"], "name_label": net["name_label"]})
pool_info["storage_resources"] = []
storage_resources = self.api.SR.get_all_records()
for sr in storage_resources.values():
if sr["type"] == "lvmoiscsi" or sr["type"] == "lvm":
label = ''.join((sr["name_label"], " (Available %d GB)" % ((int(sr['physical_size']) - int(sr['virtual_allocation']))/(1024*1024*1024))))
if sr["shared"]:
label = ''.join(("Shared storage: ", label))
pool_info["storage_resources"].insert(0, {"uuid": sr["uuid"], "name_label": label})
else:
pool_info["storage_resources"].append({"uuid": sr["uuid"], "name_label": label})
pools = self.api.pool.get_all_records()
default_sr = None
for pool in pools.values():
default_sr = pool['default_SR']
if default_sr != 'OpaqueRef:NULL':
sr_info = self.api.SR.get_record(default_sr)
pool_info['hdd_available'] = (int(sr_info['physical_size']) - int(sr_info['virtual_allocation']))/(1024*1024*1024)
else:
pool_info['hdd_available'] = None
pool_info['host_list'] = []
records = self.api.host.get_all_records()
for host_ref, record in records.items():
metrics = self.api.host_metrics.get_record(record['metrics'])
host_entry = dict()
for i in ['name_label', 'resident_VMs', 'software_version', 'cpu_info']:
host_entry[i] = record[i]
host_entry['memory_total'] = int(metrics['memory_total'])/(1024*1024)
host_entry['memory_free'] = int(metrics['memory_free'])/(1024*1024)
host_entry['live'] = metrics['live']
host_entry['memory_available'] = int(self.api.host.compute_free_memory(host_ref))/(1024*1024)
pool_info['host_list'].append(host_entry)
print(pool_info)
return pool_info
def get_vms_list(self):
vm_list = []
all_records = self.api.VM.get_all_records()
for record in all_records.values():
entry = dict()
for field in ['is_control_domain', 'is_a_template', 'is_a_snapshot']:
entry[field] = record[field] if field in record and record[field] != 'OpaqueRef:NULL' else None
if not max([x for x in entry.values()]):
for field in ['uuid', 'name_label', 'name_description', 'allowed_operations',
'power_state', 'VCPUs_at_startup', 'memory_target', 'guest_metrics',
'memory_dynamic_min', 'memory_dynamic_max']:
entry[field] = record[field] if field in record and record[field] != 'OpaqueRef:NULL' else None
entry['networks'] = self.api.VM_guest_metrics.get_record(entry['guest_metrics'])['networks'] if entry['guest_metrics'] else None
entry['endpoint'] = self.endpoint
vm_list.append(entry)
return vm_list
def capture_template(self, vm_uuid, enable):
vm_ref = self.api.VM.get_by_uuid(vm_uuid)
try:
if enable:
self.api.VM.add_tags(vm_ref, 'vmemperor')
else:
self.api.VM.remove_tags(vm_ref, 'vmemperor')
return {'status': 'success', 'details': 'template modified', 'reason': ''}, 200
except XenAPI.Failure as e:
return {'status': 'error', 'details': 'can not modify template', 'reason': e.details}, 409
except Exception as e:
return {'status': 'error', 'details': 'can not modify template', 'reason': str(e)}, 500
def start_stop_vm(self, vm_uuid, enable):
vm_ref = self.api.VM.get_by_uuid(vm_uuid)
try:
if enable:
self.api.VM.start(vm_ref, False, False)
else:
self.api.VM.shutdown(vm_ref)
return {'status': 'success', 'details': 'VM power state changed', 'reason': ''}, 200
except XenAPI.Failure as e:
return {'status': 'error', 'details': 'Can not change VM power state', 'reason': e.details}, 409
except Exception as e:
return {'status': 'error', 'details': 'Can not change VM power state', 'reason': str(e)}, 500
def set_install_options(self, vm_uuid, hooks_dict, mirror):
vm_ref = self.api.VM.get_by_uuid(vm_uuid)
internal_hooks = hooks.generate_other_config_entry(hooks_dict)
try:
self.api.VM.remove_from_other_config(vm_ref, 'vmemperor_hooks')
self.api.VM.remove_from_other_config(vm_ref, 'default_mirror')
self.api.VM.remove_from_other_config(vm_ref, 'install-repository')
except:
pass
try:
self.api.VM.add_to_other_config(vm_ref, 'vmemperor_hooks', internal_hooks)
self.api.VM.add_to_other_config(vm_ref, 'default_mirror', mirror)
self.api.VM.add_to_other_config(vm_ref, 'install-repository', mirror)
return {'status': 'success', 'details': 'Install options updated', 'reason': ''}, 200
except XenAPI.Failure as e:
return {'status': 'error', 'details': 'Can not set install options', 'reason': e.details}, 409
except Exception as e:
return {'status': 'error', 'details': 'Can not set install options', 'reason': str(e)}, 500
def create_vm(self, template_uuid, hostname, vcpus, ram, hdd, sr, network_uuid, os_kind, preseed_prefix):
api = self.api
template = api.VM.get_by_uuid(template_uuid)
tmpl = api.VM.get_record(template)
vm_ref = api.VM.clone(template, hostname)
vm = api.VM.get_record(vm_ref)
nets = api.network.get_all_records()
net = api.network.get_by_uuid(network_uuid)
network = api.network.get_record(net)
print(network["bridge"])
vif = api.VIF.create({'network': net, 'VM': vm_ref, 'device': "0", "MAC": "", "MTU": network["MTU"], "other_config": {}, "qos_algorithm_type": "",
"qos_algorithm_params": {}})
preseed = "".join((preseed_prefix, "/", os_kind, "/", vm["uuid"]))
if os_kind == "ubuntu":
pv_args = "netcfg/get_hostname=%s console=hvc0 debian-installer/locale=en_US console-setup/layoutcode=us console-setup/ask_detect=false interface=eth0 netcfg/disable_dhcp=false preseed/url=%s" % (hostname, preseed)
else:
pv_args = ""
api.VM.set_PV_args(vm_ref, pv_args)
spec = provision.getProvisionSpec(self.session, vm_ref)
spec.setSR(sr)
provision.setProvisionSpec(self.session, vm_ref, spec)
vm_platform = api.VM.get_platform(vm_ref)
vm_platform["cores-per-socket"] = vcpus
api.VM.set_platform(vm_ref, vm_platform)
api.VM.set_VCPUs_max(vm_ref, vcpus)
api.VM.set_VCPUs_at_startup(vm_ref, vcpus)
api.VM.set_memory_limits(vm_ref, str(ram), str(ram), str(ram), str(ram))
api.VM.provision(vm_ref)
api.VM.start(vm_ref, False, True)
repo = vm["other_config"]["install-repository"].replace("http://", "")
repo = repo.replace("ftp://", "")
mirror_url, mirror_path = repo.split("/", 1)
mirror_path = "".join(("/", mirror_path))
return vm["uuid"], mirror_url, mirror_path