-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager.py
262 lines (201 loc) · 7.3 KB
/
manager.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
import os
import requests
import yaml
from flask import Flask, jsonify, request, abort, Response
from proxmoxer import ProxmoxAPI
app = Flask(__name__)
app_config = None
# uuid: nonce mapping
installOperations = {}
def get_setting(config, envvar, config_key, datatype=str, required=True, default=None):
"""
Fetch a config parameter. Search order:
Environment variable > Config dict (config_key) > default
"""
value = os.getenv(envvar, None)
if value is not None:
if isinstance(value, datatype):
return value
else:
if datatype == list:
return value.split() # split on whitespace
elif datatype == bool:
return value.lower() in ["true", "t", "1", "yes"]
raise Exception(f"Unable to cast value for {envvar} to {datatype}")
try:
value = config[config_key]
if isinstance(value, datatype):
return value
else:
# No casting for config dict
raise Exception(
f"Invalid value for {config_key} in config file: should be {datatype} but is {type(value)}"
)
except KeyError:
if required:
raise Exception(
f"Missing configuration: {config_key} is required, specify either in the config file or as {envvar} environment variable"
)
else:
return default
def proxmox_connector(config):
nodes = get_setting(config, "PROXMOX_MANAGER_NODES", "nodes", datatype=list)
for node in nodes:
settings = {
"user": get_setting(config, "PROXMOX_MANAGER_USERNAME", "username"),
"password": get_setting(config, "PROXMOX_MANAGER_PASSWORD", "password"),
"verify_ssl": get_setting(
config,
"PROXMOX_MANAGER_SSL_VERIFY",
"ssl_verify",
datatype=bool,
required=False,
default=True,
),
}
connector = ProxmoxAPI(
node,
**settings,
)
try:
connector.version.get()
return connector
except Exception as e:
print(f"Warning: Proxmox node {node} is unusable: {e}")
raise Exception("No usable proxmox nodes found")
def extract_vm_uuid(vm_config):
if not "smbios1" in vm_config:
print(
f"Warning: VM {vm['vmid']} on node {vm['node']} has no UUID set (no smbios1 key)"
)
options = vm_config.get("smbios1", "=").split(",")
for option in options:
parts = option.split("=", 1)
if parts[0] == "uuid":
if len(parts) != 2:
print(
f"Warning: VM {vm['vmid']} on node {vm['node']} has no UUID set (cannot parse UUID key)"
)
else:
return parts[1]
print(
f"Warning: VM {vm['vmid']} on node {vm['node']} has not UUID set (no UUID found)"
)
def inventory(config, connector=proxmox_connector):
data = get_inventory(connector(config["manager"]))
return data
def get_inventory(proxmox):
data = []
for node in proxmox.nodes.get():
vms = []
try:
vms = proxmox.nodes(node["node"]).get("qemu")
except Exception as e:
print(f"Warning: Proxmox node {node} is unusable: {e}")
continue
for vm in vms:
config = None
try:
config = proxmox.nodes(node["node"]).qemu(vm["vmid"]).config().get()
except Exception as e:
print(
f"Warning: Unable to fetch QEMU VM configuration for {vm['vmid']} on node {node}: {e}"
)
continue
uuid = extract_vm_uuid(config)
data.append({"uuid": uuid, "name": vm["name"]})
return data
def virtual_machine(config, uuid, connector=proxmox_connector):
c = connector(config["manager"])
vm = get_vm(c, uuid)
if vm is not None:
vm["_proxmox_connector"] = c
return vm
return None
def get_vm(proxmox, uuid):
for vm in proxmox.cluster.resources.get(type="vm"):
vm_config = None
try:
vm_config = proxmox.nodes(vm["node"]).qemu(vm["vmid"]).config.get()
except Exception as e:
printf(f"Error: Unable to get VM config for VM {vm_data['vmid']}")
raise e
vm_uuid = extract_vm_uuid(vm_config)
if uuid == vm_uuid:
return vm
return None
@app.route("/v1/machines", methods=["GET"])
def api_v1_machines():
return jsonify(inventory(app_config))
@app.route("/v1/machines/<uuid:uuid>/boot-installer", methods=["POST"])
def api_v1_boot_installer(uuid):
# According to the spec, there is a JSON payload in the request containing
# nonce, but currently we have no use for it, so leave request body be.
# TODO: add nonce from installOperations, fail/noop if there is another
# install request inflight for this uuid
vm_data = virtual_machine(app_config, str(uuid))
if vm_data is None:
return Response(status=404)
vm = vm_data["_proxmox_connector"].nodes(vm_data["node"]).qemu(vm_data["vmid"])
# Get list of all nics
vm_config = None
try:
vm_config = vm.config.get()
except Exception as e:
printf(f"Error: Unable to get VM config for VM {vm_data['vmid']}")
raise e
nics = []
for attr in vm_config:
if attr.startswith("net"):
nics.append(attr)
# Set boot order to force network boot
try:
vm.config.put(boot=f"order={';'.join(nics)}")
except Exception as e:
printf(f"Error: Unable to update boot order for VM {vm_data['vmid']}")
raise e
# Power off VM
try:
vm.status.stop.post()
except Exception as e:
printf(f"Error: Unable to stop VM {vm_data['vmid']}")
raise e
# Power on VM
try:
vm.status.start.post()
except Exception as e:
printf(f"Error: Unable to start VM {vm_data['vmid']}")
raise e
# Set default boot order (boot from disk)
try:
vm.config.put(boot="order=scsi0")
except Exception as e:
printf(f"Error: Unable to restore boot order for VM {vm_data['vmid']}")
raise e
return Response(status=200)
@app.route("/v1/machines/<uuid:uuid>/exit-installer", methods=["POST"])
def api_v1_exit_installer(uuid):
# According to the spec, there is a JSON payload in the request containing
# nonce, but currently we have no use for it, so leave request body be.
# TODO: remove nonce from installOperations, fail if there is no such installOperation
vm_data = virtual_machine(app_config, str(uuid))
if vm_data is None:
return Response(status=404)
vm = vm_data["_proxmox_connector"].nodes(vm_data["node"]).qemu(vm_data["vmid"])
# Power off VM
try:
vm.status.stop.post()
except Exception as e:
printf(f"Error: Unable to stop VM {vm_data['vmid']}")
raise e
# Power on VM
try:
vm.status.start.post()
except Exception as e:
printf(f"Error: Unable to stop VM {vm_data['vmid']}")
raise e
return Response(status=200)
if __name__ == "__main__":
with open("config.yml") as f:
app_config = yaml.load(f, Loader=yaml.FullLoader)
app.run(**app_config["flask"])