forked from lxc-webpanel/LXC-Web-Panel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lwp.py
483 lines (415 loc) · 23.1 KB
/
lwp.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
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, jsonify
import lxclite as lxc
import lwp
import subprocess
import time
import re
import hashlib
import signal
import sqlite3
import os
import ConfigParser
# configuration
config = ConfigParser.SafeConfigParser()
config.readfp(open('lwp.conf'))
SECRET_KEY = '\xb13\xb6\xfb+Z\xe8\xd1n\x80\x9c\xe7KM\x1c\xc1\xa7\xf8\xbeY\x9a\xfa<.'
DEBUG = config.getboolean('global', 'debug')
DATABASE = config.get('database', 'file')
ADDRESS = config.get('global', 'address')
PORT = int(config.get('global', 'port'))
# Flask app
app = Flask(__name__)
app.config.from_object(__name__)
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
@app.before_request
def before_request():
check_session_limit()
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
if hasattr(g, 'db'):
g.db.close()
#Home
@app.route('/')
@app.route('/home')
def home():
if 'logged_in' in session:
containers_all = []
listx = lxc.listx()
sorted_list = listx['RUNNING'] + listx['FROZEN'] + listx['STOPPED']
for container in sorted_list:
status = lxc.info(container)['state']
containers_all.append({'status':status, 'name':container, 'memusg':lwp.memory_usage(container), 'settings':lwp.get_container_settings(container)})
return render_template('index.html', containers=lwp.ls(), containers_all=containers_all, dist=lwp.check_ubuntu(), templates=lwp.get_templates_list())
return render_template('login.html')
@app.route('/about')
def about():
if 'logged_in' in session:
return render_template('about.html', containers=lwp.ls(), version=lwp.check_version())
return render_template('login.html')
#Edit
@app.route('/<container>/edit', methods=['POST', 'GET'])
def edit(container=None):
if 'logged_in' in session:
host_memory = lwp.host_memory_usage()
if request.method == 'POST':
cfg = lwp.get_container_settings(container)
ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
form = {}
form['type'] = request.form['type']
form['link'] = request.form['link']
form['flags'] = request.form['flags']
form['hwaddr'] = request.form['hwaddress']
form['rootfs'] = request.form['rootfs']
form['utsname'] = request.form['hostname']
form['ipv4'] = request.form['ipaddress']
form['memlimit'] = request.form['memlimit']
form['swlimit'] = request.form['swlimit']
form['cpus'] = request.form['cpus']
form['shares'] = request.form['cpushares']
if form['utsname'] != cfg['utsname'] and re.match('^(?!^containers$)([a-z0-9-]{1,63})|([a-z0-9-\.]{1,63}\.[a-z0-9-\.]{1,63}\.[a-z0-9\.]{1,6})$', form['utsname']):
lwp.push_config_value('lxc.utsname', form['utsname'], container=container)
flash(u'Hostname updated for %s!' % container, 'success')
if form['flags'] != cfg['flags'] and re.match('^(up|down)$', form['flags']):
lwp.push_config_value('lxc.network.flags', form['flags'], container=container)
flash(u'Network flag updated for %s!' % container, 'success')
if form['type'] != cfg['type'] and re.match('^\w+$', form['type']):
lwp.push_config_value('lxc.network.type', form['type'], container=container)
flash(u'Link type updated for %s!' % container, 'success')
if form['link'] != cfg['link'] and re.match('^\w+$', form['link']):
lwp.push_config_value('lxc.network.link', form['link'], container=container)
flash(u'Link name updated for %s!' % container, 'success')
if form['hwaddr'] != cfg['hwaddr'] and re.match('^([a-fA-F0-9]{2}[:|\-]?){6}$', form['hwaddr']):
lwp.push_config_value('lxc.network.hwaddr', form['hwaddr'], container=container)
flash(u'Hardware address updated for %s!' % container, 'success')
if (not form['ipv4'] and form['ipv4'] != cfg['ipv4']) or (form['ipv4'] != cfg['ipv4'] and re.match('^%s$' % ip_regex, form['ipv4'])):
lwp.push_config_value('lxc.network.ipv4', form['ipv4'], container=container)
flash(u'IP address updated for %s!' % container, 'success')
if form['memlimit'] != cfg['memlimit'] and re.match('^[0-9]+$', form['memlimit']) and int(form['memlimit']) <= int(host_memory['total']):
if int(form['memlimit']) == int(host_memory['total']):
form['memlimit'] = ''
if form['memlimit'] != cfg['memlimit']:
lwp.push_config_value('lxc.cgroup.memory.limit_in_bytes', form['memlimit'], container=container)
flash(u'Memory limit updated for %s!' % container, 'success')
if form['swlimit'] != cfg['swlimit'] and re.match('^[0-9]+$', form['swlimit']) and int(form['swlimit']) <= int(host_memory['total'] * 2):
if int(form['swlimit']) == int(host_memory['total'] * 2):
form['swlimit'] = ''
if form['swlimit'] != cfg['swlimit']:
lwp.push_config_value('lxc.cgroup.memory.memsw.limit_in_bytes', form['swlimit'], container=container)
flash(u'Swap limit updated for %s!' % container, 'success')
if (not form['cpus'] and form['cpus'] != cfg['cpus']) or (form['cpus'] != cfg['cpus'] and re.match('^[0-9,-]+$', form['cpus'])):
lwp.push_config_value('lxc.cgroup.cpuset.cpus', form['cpus'], container=container)
flash(u'CPUs updated for %s!' % container, 'success')
if (not form['shares'] and form['shares'] != cfg['shares']) or (form['shares'] != cfg['shares'] and re.match('^[0-9]+$', form['shares'])):
lwp.push_config_value('lxc.cgroup.cpu.shares', form['shares'], container=container)
flash(u'CPU shares updated for %s!' % container, 'success')
info = lxc.info(container)
status = info['state']
pid = info['pid']
infos = {'status':status, 'pid':pid, 'memusg':lwp.memory_usage(container)}
return render_template('edit.html', containers=lwp.ls(), container=container, infos=infos, settings=lwp.get_container_settings(container), host_memory=host_memory)
return render_template('login.html')
@app.route('/settings/lxc-net', methods=['POST', 'GET'])
def lxc_net():
if 'logged_in' in session:
if session['su'] != 'Yes': return abort(403)
if request.method == 'POST':
if lxc.running() == []:
try:
if request.form['status'] == 'Enable':
lwp.push_net_value('USE_LXC_BRIDGE', 'true')
if lwp.net_restart() == 0:
flash(u'LXC Networking enabled successfully!', 'success')
else:
flash(u'Failed to restart LXC networking.', 'error')
elif request.form['status'] == 'Disable':
lwp.push_net_value('USE_LXC_BRIDGE', 'false')
if lwp.net_restart() == 0:
flash(u'LXC Networking disabled successfully!', 'success')
else:
flash(u'Failed to restart LXC networking.', 'error')
except KeyError:
cfg = lwp.get_net_settings()
ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
if request.form['bridge'] != cfg['bridge'] and re.match('^\w+$', request.form['bridge']):
lwp.push_net_value('LXC_BRIDGE', request.form['bridge'])
if request.form['address'] != cfg['address'] and re.match('^%s$' % ip_regex, request.form['address']):
lwp.push_net_value('LXC_ADDR', request.form['address'])
if request.form['netmask'] != cfg['netmask'] and re.match('^%s$' % ip_regex, request.form['netmask']):
lwp.push_net_value('LXC_NETMASK', request.form['netmask'])
if request.form['network'] != cfg['network'] and re.match('^%s(?:/\d{1,2}|)$' % ip_regex, request.form['network']):
lwp.push_net_value('LXC_NETWORK', request.form['network'])
if request.form['range'] != cfg['range'] and re.match('^%s,%s$' % (ip_regex,ip_regex), request.form['range']):
lwp.push_net_value('LXC_DHCP_RANGE', request.form['range'])
if request.form['max'] != cfg['max'] and re.match('^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', request.form['max']):
lwp.push_net_value('LXC_DHCP_MAX', request.form['max'])
if lwp.net_restart() == 0:
flash(u'LXC Network settings applied successfully!', 'success')
else:
flash(u'Failed to restart LXC networking.', 'error')
else:
flash(u'Stop all containers before restart lxc-net.', 'warning')
return render_template('lxc-net.html', containers=lwp.ls(), cfg=lwp.get_net_settings(), running=lxc.running())
return render_template('login.html')
@app.route('/lwp/users', methods=['POST', 'GET'])
def lwp_users():
if 'logged_in' in session:
if session['su'] != 'Yes': return abort(403)
try: trash = request.args.get('trash')
except KeyError: trash = 0
if request.args.get('token') == session.get('token') and trash == '1' and request.args.get('userid') and request.args.get('username'):
g.db.execute("DELETE FROM users WHERE id=? AND username=?", [request.args.get('userid'), request.args.get('username')])
g.db.commit()
flash('Deleted %s' % request.args.get('username'), 'success')
return redirect(url_for('lwp_users'))
if request.method == 'POST':
users = query_db('SELECT id, name, username, su FROM users ORDER BY id ASC')
if request.form['newUser'] == 'True':
if not request.form['username'] in [user['username'] for user in users]:
if re.match('^\w+$', request.form['username']) and request.form['password1']:
if request.form['password1'] == request.form['password2']:
if request.form['name']:
if re.match('[a-z A-Z0-9]{3,32}', request.form['name']):
g.db.execute("INSERT INTO users (name, username, password) VALUES (?, ?, ?)", [request.form['name'], request.form['username'], hash_passwd(request.form['password1'])])
g.db.commit()
else: flash('Invalid name!', 'error')
else:
g.db.execute("INSERT INTO users (username, password) VALUES (?, ?)", [request.form['username'], hash_passwd(request.form['password1'])])
g.db.commit()
flash('Created %s' % request.form['username'], 'success')
else: flash('No password match', 'error')
else: flash('Invalid username or password!', 'error')
else: flash('Username already exist!', 'error')
elif request.form['newUser'] == 'False':
if request.form['password1'] == request.form['password2']:
if re.match('[a-z A-Z0-9]{3,32}', request.form['name']):
try:
su = request.form['su']
except KeyError:
su = 'No'
if not request.form['name']:
g.db.execute("UPDATE users SET name='', su=? WHERE username=?", [su, request.form['username']])
g.db.commit()
elif request.form['name'] and not request.form['password1'] and not request.form['password2']:
g.db.execute("UPDATE users SET name=?, su=? WHERE username=?", [request.form['name'], su, request.form['username']])
g.db.commit()
elif request.form['name'] and request.form['password1'] and request.form['password2']:
g.db.execute("UPDATE users SET name=?, password=?, su=? WHERE username=?", [request.form['name'], hash_passwd(request.form['password1']), su, request.form['username']])
g.db.commit()
elif request.form['password1'] and request.form['password2']:
g.db.execute("UPDATE users SET password=?, su=? WHERE username=?", [hash_passwd(request.form['password1']), su, request.form['username']])
g.db.commit()
flash('Updated', 'success')
else: flash('Invalid name!', 'error')
else: flash('No password match', 'error')
else: flash('Unknown error!', 'error')
users = query_db('SELECT id, name, username, su FROM users ORDER BY id ASC')
return render_template('users.html', containers=lwp.ls(), users=users)
return render_template('login.html')
#Check config
@app.route('/checkconfig')
def checkconfig():
if 'logged_in' in session:
if session['su'] != 'Yes': return abort(403)
return render_template('checkconfig.html', containers=lwp.ls(), cfg=lxc.checkconfig())
return render_template('login.html')
#Start/Stop/Freeze/Unfreeze
@app.route('/action', methods=['GET'])
def action():
if 'logged_in' in session:
if request.args['token'] == session.get('token') :
action = request.args['action']
name = request.args['name']
if action == 'start' :
try:
if lxc.start(name) == 0:
time.sleep(1) # Fix bug : "the container is randomly not displayed in overview list after a boot"
flash(u'Container %s started successfully!' % name, 'success')
else:
flash(u'Unable to start %s!' % name, 'error')
except lxc.ContainerAlreadyRunning:
flash(u'Container %s is already running!' % name, 'error')
elif action == 'stop' :
try:
if lxc.stop(name) == 0:
flash(u'Container %s stopped successfully!' % name, 'success')
else:
flash(u'Unable to stop %s!' % name, 'error')
except lxc.ContainerNotRunning:
flash(u'Container %s is already stopped!' % name, 'error')
elif action == 'freeze' :
try:
if lxc.freeze(name) == 0:
flash(u'Container %s frozen successfully!' % name, 'success')
else:
flash(u'Unable to freeze %s!' % name, 'error')
except lxc.ContainerNotRunning:
flash(u'Container %s not running!' % name, 'error')
elif action == 'unfreeze' :
try:
if lxc.unfreeze(name) == 0:
flash(u'Container %s unfrozen successfully!' % name, 'success')
else:
flash(u'Unable to unfeeze %s!' % name, 'error')
except lxc.ContainerNotRunning:
flash(u'Container %s not frozen!' % name, 'error')
elif action == 'destroy' :
try:
if lxc.destroy(name) == 0:
flash(u'Container %s destroyed successfully!' % name, 'success')
else:
flash(u'Unable to destroy %s!' % name, 'error')
except lxc.ContainerDoesntExists:
flash(u'The Container %s does not exists!' % name,'error')
elif action == 'reboot' and name == 'host':
msg = '\v*** LXC Web Panel *** \
\nReboot from web panel'
try:
subprocess.check_call('/sbin/shutdown -r now \'%s\'' % msg, shell=True)
flash(u'System will now restart!', 'success')
except:
flash(u'System error!', 'error')
try:
if request.args['from'] == 'edit':
return redirect('../%s/edit' % name)
else:
return redirect(url_for('home'))
except:
return redirect(url_for('home'))
return render_template('login.html')
@app.route('/action/create-container', methods=['GET', 'POST'])
def create_container():
if 'logged_in' in session:
if request.method == 'POST':
name = request.form['name']
template = request.form['template']
if re.match('^(?!^containers$)|[a-zA-Z0-9_-]+$', name):
storage_method = request.form['backingstore']
if storage_method == 'default':
try:
if lxc.create(name, template=template) == 0:
flash(u'Container %s created successfully!' % name,'success')
else:
flash(u'Failed to create %s!' % name,'error')
except lxc.ContainerAlreadyExists:
flash(u'The Container %s is already created!' % name,'error')
elif storage_method == 'directory':
directory = request.form['dir']
if re.match('^/[a-zA-Z0-9_/-]+$', directory) and directory != '':
try:
if lxc.create(name, template=template, backing_store='dir --dir %s' % directory) == 0:
flash(u'Container %s created successfully!' % name,'success')
else:
flash(u'Failed to create %s!' % name,'error')
except lxc.ContainerAlreadyExists:
flash(u'The Container %s is already created!' % name,'error')
elif storage_method == 'lvm':
lvname = request.form['lvname']
vgname = request.form['vgname']
fstype = request.form['fstype']
fssize = request.form['fssize']
storage_options = 'lvm'
if re.match('^[a-zA-Z0-9_-]+$', lvname) and lvname != '':
storage_options += ' --lvname %s' % lvname
if re.match('^[a-zA-Z0-9_-]+$', vgname) and vgname != '':
storage_options += ' --vgname %s' % vgname
if re.match('^[a-z0-9]+$', fstype) and fstype != '':
storage_options += ' --fstype %s' % fstype
if re.match('^[0-9][G|M]$', fssize) and fssize != '':
storage_options += ' --fssize %s' % fssize
try:
if lxc.create(name, template=template, backing_store=storage_options) == 0:
flash(u'Container %s created successfully!' % name,'success')
else:
flash(u'Failed to create %s!' % name,'error')
except lxc.ContainerAlreadyExists:
flash(u'The container/logical volume %s is already created!' % name,'error')
else:
flash(u'Missing parameters to create container!','error')
else:
if name == '':
flash(u'Please enter a container name!','error')
else:
flash(u'Invalid name for \"%s\"!' % name,'error')
return redirect(url_for('home'))
return render_template('login.html')
# Login process
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
request_username = request.form['username']
request_passwd = hash_passwd(request.form['password'])
current_url = request.form['url']
user = query_db('select name, username, su from users where username=? and password=?',[request_username,request_passwd], one=True)
if user:
session['logged_in'] = True
session['token'] = get_token()
session['last_activity'] = int(time.time())
session['username'] = user['username']
session['name'] = user['name']
session['su'] = user['su']
flash(u'You are logged in!','success')
if current_url == url_for('login'):
return redirect(url_for('home'))
return redirect(current_url)
flash(u'Invalid username or password!','error')
return render_template('login.html')
# Logout process
@app.route('/logout')
def logout():
session.pop('logged_in', None)
session.pop('token', None)
session.pop('last_activity', None)
session.pop('username', None)
session.pop('name',None)
session.pop('su',None)
flash(u'You are logged out!','success')
return redirect(url_for('login'))
@app.route('/_refresh_cpu_host')
def refresh_cpu_host():
return lwp.host_cpu_percent()
@app.route('/_refresh_uptime_host')
def refresh_uptime_host():
return jsonify(lwp.host_uptime())
@app.route('/_refresh_disk_host')
def refresh_disk_host():
return jsonify(lwp.host_disk_usage())
@app.route('/_refresh_memory_<name>')
def refresh_memory_containers(name=None):
if name == 'containers':
containers_running = lxc.running()
containers = []
for container in containers_running:
container = container.replace(' (auto)', '')
containers.append({'name':container, 'memusg':lwp.memory_usage(container)})
return jsonify(data=containers)
elif name == 'host':
return jsonify(lwp.host_memory_usage())
return jsonify({'memusg':lwp.memory_usage(name)})
@app.route('/_check_version')
def check_version():
return jsonify(lwp.check_version())
def hash_passwd(passwd):
return hashlib.sha512(passwd).hexdigest()
#Generate security token
def get_token():
return hashlib.md5(str(time.time())).hexdigest()
#Perform Queries to database
def query_db(query, args=(), one=False):
cur = g.db.execute(query, args)
rv = [dict((cur.description[idx][0], value) for idx, value in enumerate(row)) for row in cur.fetchall()]
return (rv[0] if rv else None) if one else rv
#Logout non active user
def check_session_limit():
if 'logged_in' in session and session.get('last_activity') != None:
now = int(time.time())
limit = now - 60 * int(config.get('session', 'time'))
last_activity = session.get('last_activity')
if last_activity < limit:
flash(u'Session timed out !','info')
logout()
else:
session['last_activity'] = now
if __name__ == '__main__':
app.run(host=app.config['ADDRESS'], port=app.config['PORT'])