This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
flask_control.py
executable file
·348 lines (284 loc) · 8.56 KB
/
flask_control.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2017 James Tanner (@jctanner) <[email protected]>
# Abhijeet Kasurde (@akasurde) <[email protected]>
#
# Written by James Tanner <[email protected]>
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import psutil
import socket
import subprocess
from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
GOPATH = os.path.abspath(os.environ['GOPATH'])
VCSIMPATH = os.path.join(GOPATH, 'bin', 'vcsim')
GOVCPATH = os.path.join(GOPATH, 'bin', 'govc')
GOVCURL = None
@app.route('/')
def m_index():
return 'vcsim controller'
@app.route('/log')
def get_log():
"""Read and return the vcsim log"""
fdata = ''
if os.path.isfile('vcsim.log'):
with open('vcsim.log', 'rb') as f:
fdata = f.read()
return fdata
@app.route('/kill/<int:number>')
def kill_one(number):
"""Kill any arbitrary process id"""
success = False
e = None
try:
p = psutil.Process(number)
p.terminate()
success = True
except Exception as e:
pass
return jsonify({'success': success, 'e': str(e)})
@app.route('/killall')
def kill_all():
"""Kill ALL of the running vcsim pids"""
results = []
for x in psutil.pids():
p = psutil.Process(x)
if VCSIMPATH in p.cmdline():
success = False
e = None
try:
p.terminate()
success = True
except Exception as e:
pass
results.append(
{'pid': x, 'cmdline': p.cmdline(),
'success': success, 'e': str(e)}
)
return jsonify(results)
@app.route('/spawn')
def spawn_vcsim():
"""Launch vcsim in a background process and return the pid+govcm_url"""
global GOVCURL
username = request.args.get('username') or 'user'
password = request.args.get('password') or 'pass'
hostname = request.args.get('hostname') or \
socket.gethostbyname(socket.gethostname())
port = request.args.get('port') or '443'
port = int(port)
# FIXME - enable tracing
if request.args.get('trace'):
trace = True
else:
trace = False
# vcsim cli options and their default values
cli_opts = [
['app', 0],
['cluster', 0],
['dc', 1],
['ds', 1],
['folder', 1],
['host', 3],
['pg', 1],
['pod', 1],
['pool', 1],
['vm', 2]
]
# useful for client govc commands
govc_url = 'https://%s:%s@%s:%s' % (username, password, hostname, port)
GOVCURL = govc_url
# need these to run the service
env = {
'GOPATH': GOPATH,
'GOVC_URL': govc_url,
'GOVC_INSECURE': '1'
}
# build the command
cmd = [
VCSIMPATH,
'-l',
'%s:%s' % (hostname, port),
]
# trace soap requests+responses
if trace:
cmd.append('-trace')
# esx only allows certain arguments
if request.args.get('esx'):
cmd.append('-esx')
for x in [('vm', 1), ('ds', 1)]:
name = x[0]
default = x[1]
if request.args.get(name):
default = request.args.get(name)
cmd.append('-%s=%s' % (name, default))
else:
# use all other options as requested for vcenter
for x in cli_opts:
name = x[0]
default = x[1]
if request.args.get(name):
default = request.args.get(name)
cmd.append('-%s=%s' % (name, default))
cmd = ' '.join(cmd)
cmd += ' > vcsim.log 2>&1'
# run it with environment settings
p = subprocess.Popen(
cmd,
env=env,
shell=True
)
# return the relevant data
pid = p.pid
rdata = {
'cmd': cmd,
'pid': pid,
'host': hostname,
'port': port,
'username': username,
'password': password,
'GOVC_URL': govc_url
}
return jsonify(rdata)
@app.route('/govc_find')
def govc_find():
"""Run govc find and optionally filter results"""
ofilter = request.args.get('filter') or None
stdout_lines = _get_all_objs(ofilter=ofilter)
return jsonify(stdout_lines)
@app.route('/govc_vm_info')
def get_govc_vm_info():
"""Run govc vm info """
vm_name = request.args.get('vm_name') or None
vm_output = {}
if vm_name:
all_vms = [vm_name]
else:
# Get all VMs
all_vms = _get_all_objs(ofilter='VM')
for vm_name in all_vms:
vm_info = _get_vm_info(vm_name=vm_name)
name = vm_info.get('Name', vm_name)
vm_output[name] = vm_info
return jsonify(vm_output)
@app.route('/govc_host_info')
def get_govc_host_info():
""" Run govc host.info """
host_name = request.args.get("host_name") or None
host_output = {}
if host_name:
all_hosts = [host_name]
else:
all_hosts = _get_all_objs(ofilter='H')
for host_system in all_hosts:
host_info = _get_host_info(host_name=host_system)
name = host_info.get('Name', host_system)
host_output[name] = host_info
return jsonify(host_output)
@app.route('/create_cluster')
def create_cluster():
"""
Create a managed object for cluster in VCSIM
"""
cluster_obj = request.args.get('name') or None
govc_info = {}
if cluster_obj:
cmd = '%s cluster.create %s 2>&1' % (GOVCPATH, cluster_obj)
govc_info['stdout'], govc_info['stderr'] = run_cmd(cmd)
return jsonify(govc_info)
def _get_host_info(host_name=None):
"""
Get all information of host from vcsim
:param host_name: Name of host
:return: Dictionary containing information about host,
where KEY represent attributes and VALUE represent attribute's value
"""
cmd = '%s host.info -host=%s 2>&1' % (GOVCPATH, host_name)
host_info = {}
if host_name is None:
return host_info
host_info = parse_govc_info(cmd)
return host_info
def _get_vm_info(vm_name=None):
"""
Get all information of VM from vcsim
:param vm_name: Name of VM
:return: Dictionary containing information about VM,
where KEY represent attributes and VALUE represent attribute's value
"""
cmd = '%s vm.info %s 2>&1' % (GOVCPATH, vm_name)
vm_info = {}
if vm_name is None:
return vm_info
vm_info = parse_govc_info(cmd)
return vm_info
def parse_govc_info(cmd):
"""
Helper function to parse output of govc info commands
:param cmd: command variable to run and parse output for
:return: Dictionary containing information about object
"""
so, se = run_cmd(cmd)
stdout_lines = so.splitlines()
info = {}
for line in stdout_lines:
if ":" in line:
key, value = line.split(":", 1)
key = key.lstrip()
info[key] = value.strip()
return info
def _get_all_objs(ofilter=None):
"""
Get all VM Objects from vcsim
:param ofilter: Specify which object to get
:return: list of Object specified by ofilter
"""
cmd = '%s find ' % GOVCPATH
filter_mapping = dict(VA='a', CCR='c', DC='d', F='f', DVP='g', H='h',
VM='m', N='n', ON='o', RP='p', CR='r', D='s', DVS='w')
if ofilter:
type_filter = filter_mapping.get(ofilter, '')
if type_filter != '':
cmd += '-type %s ' % type_filter
cmd += "2>&1"
so, se = run_cmd(cmd)
stdout_lines = so.splitlines()
return stdout_lines
def run_cmd(cmd):
"""
Helper Function to run commands
:param cmd: Command string to execute
:return: StdOut and StdErr in string format
"""
global GOVCURL
env = {
'GOPATH': GOPATH,
'GOVC_URL': GOVCURL,
'GOVC_INSECURE': '1'
}
p = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
shell=True
)
(so, se) = p.communicate()
return so, se
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0')