proxadmin/app/vmanager/routes.py

178 lines
7.2 KiB
Python
Raw Normal View History

2017-03-08 13:53:09 -05:00
from flask import render_template, abort, redirect, url_for, abort, flash, request, current_app, make_response, g
from flask_login import login_required, login_user, logout_user, current_user
from flask_sqlalchemy import get_debug_queries
2017-03-08 19:55:12 -05:00
from . import vmanager
from .forms import DeployForm, ActivateForm
2017-03-08 13:53:09 -05:00
from .. import db
from ..email import send_email
2017-07-15 00:13:57 -04:00
from ..models import User, Permission, Transaction, Deployment, Service, Region, Address, Domain, contact_proxmaster
2017-03-08 13:53:09 -05:00
from ..decorators import admin_required, permission_required
import base64
import string
import random
from datetime import datetime, timedelta, date, time
2017-07-15 00:13:57 -04:00
from dateutil.relativedelta import relativedelta
2017-06-01 18:27:17 -04:00
import ast
2017-03-08 13:53:09 -05:00
def randstr(n):
return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(n))
2017-03-08 19:55:12 -05:00
@vmanager.after_app_request
2017-03-08 13:53:09 -05:00
def after_request(response):
for query in get_debug_queries():
if query.duration >= current_app.config['SLOW_DB_QUERY_TIME']:
current_app.logger.warning('Slow query: %s\nParameters: %s\nDuration: %fs\nContext: %s\n' % (query.statement, query.parameters, query.duration, query.context))
return response
2017-07-28 21:31:44 -04:00
@vmanager.route('/createvm', methods=['GET', 'POST'])
2017-03-08 13:53:09 -05:00
@login_required
2017-07-28 21:31:44 -04:00
def createvm():
2017-03-08 13:53:09 -05:00
if current_user.name is None:
2017-05-25 01:54:33 -04:00
flash('Please update profile info for this operation.')
2017-07-28 21:31:44 -04:00
return redirect(url_for('settings.profile'))
2017-03-08 13:53:09 -05:00
2017-07-28 21:31:44 -04:00
deployment_seeds = Deployment.query.filter_by(protected=False).all()
if deployment_seeds != []:
flash('Offline deployments exist.')
return redirect(url_for('main.dashboard'))
2017-03-08 13:53:09 -05:00
if current_user.confirmed and form.validate_on_submit():
2017-07-30 17:10:08 -04:00
data = { 'clientid': str(current_user.pid),
2017-03-08 13:53:09 -05:00
'clientname': str(current_user.name),
'clientemail': str(current_user.email),
2017-07-30 17:10:08 -04:00
'hostname': str(form.deployname.data),
2017-03-08 13:53:09 -05:00
'region': form.region.data,
2017-07-30 17:10:08 -04:00
'type': 'kvm',
'cpu': '1',
'mem': '512',
'hdd': '20'
}
2017-03-08 13:53:09 -05:00
try:
query = contact_proxmaster(data, 'vmcreate')
except:
flash('Region unreachable! Please try again later...')
return redirect(url_for('main.dashboard'))
2017-03-08 13:53:09 -05:00
if query is not None:
2017-07-20 19:30:09 -04:00
deployment = Deployment(user_id=client_id, product_id=product_id, machine_alias=form.servername.data, machine_id=query['cube'], machine_cpu=form.cpu.data, machine_mem=form.mem.data, machine_hdd=form.hdd.data, enabled=True)
2017-03-08 13:53:09 -05:00
db.session.add(deployment)
db.session.commit()
flash('Deploy requested.')
else:
flash('Deploy cancelled! Please try again later...')
return redirect(url_for('main.dashboard'))
2017-03-08 13:53:09 -05:00
2017-07-14 09:04:27 -04:00
@vmanager.route('/activate/<int:itemid>', methods=['GET', 'POST'])
@login_required
2017-07-14 09:00:04 -04:00
def activate(itemid=0):
result = current_user.inv_deployments.all()
inventory = []
for invcls in result:
inventory.extend([invcls.machine_id])
if current_user.is_administrator():
2017-07-15 20:48:18 -04:00
current_app.logger.warning('[ADMIN] Access override for deployment id:{}'.format(itemid))
2017-07-14 09:00:04 -04:00
elif not itemid in inventory:
2017-07-15 20:48:18 -04:00
current_app.logger.error('[{}] Access violation with deployment id: {}'.format(current_user.email, itemid))
abort(404)
2017-07-15 00:13:57 -04:00
deploy = Deployment.query.filter_by(machine_id=itemid).first()
2017-07-20 19:30:09 -04:00
if deploy.enabled == True and deploy.warning == False:
abort(404)
2017-07-15 00:13:57 -04:00
cpu_cost = deploy.machine_cpu * current_app.config['CPU_RATIO']
mem_cost = ( deploy.machine_mem / 1024 ) * current_app.config['MEM_RATIO']
hdd_cost = deploy.machine_hdd * current_app.config['HDD_RATIO']
2017-07-20 19:30:09 -04:00
ppm = round(cpu_cost + mem_cost + hdd_cost)
2017-07-15 00:13:57 -04:00
form = ActivateForm(period=int(deploy.period))
2017-07-15 20:48:18 -04:00
owner = deploy.owner
if owner.confirmed and form.validate_on_submit():
2017-07-20 19:30:09 -04:00
total = ppm * form.period.data
2017-07-15 20:48:18 -04:00
if owner.wallet < total:
2017-07-20 19:30:09 -04:00
flash('Activation costs {} {}. Insufficient Funds'.format(total, owner.currency))
2017-07-15 00:13:57 -04:00
return redirect(url_for('uinvoice.transactions'))
2017-07-15 20:48:18 -04:00
current_app.logger.info('[{}] Charge deployment: {}'.format(owner.email, deploy.machine_id))
2017-07-15 00:13:57 -04:00
today = datetime.utcnow()
2017-07-15 20:48:18 -04:00
expiry = today + relativedelta(today, months=+(form.period.data))
daysleft = expiry - today
extradays = relativedelta(today, days=+(deploy.daysleft))
deploy.date_last_charge = today + extradays
2017-07-15 00:13:57 -04:00
deploy.period = form.period.data
2017-07-20 19:30:09 -04:00
deploy.daysleft = daysleft.days + extradays.days
2017-07-15 00:13:57 -04:00
deploy.warning = False
2017-07-15 00:28:04 -04:00
deploy.enabled = True
2017-07-15 00:13:57 -04:00
db.session.commit()
2017-07-15 20:48:18 -04:00
transaction = Transaction(user_id=int(owner.pid), description='Deployment {} activated for {} month(s)'.format(str(deploy.machine_alias), form.period.data), value=-total)
2017-07-15 00:13:57 -04:00
db.session.add(transaction)
db.session.commit()
2017-07-15 20:48:18 -04:00
owner.wallet = owner.wallet - total
2017-07-15 00:13:57 -04:00
db.session.commit()
2017-07-20 19:30:09 -04:00
flash('Deployment {} activated for {} month(s)'.format(str(deploy.machine_alias), form.period.data))
2017-07-15 20:48:18 -04:00
if owner.is_administrator:
2017-07-25 10:33:23 -04:00
return redirect(url_for('admin.list_deployments'))
2017-07-15 20:48:18 -04:00
else:
return redirect(url_for('main.dashboard'))
2017-07-24 06:33:33 -04:00
return render_template('vmanager/activate.html', form=form, deploy=deploy, cpu_cost=cpu_cost, mem_cost=mem_cost, hdd_cost=hdd_cost, ppm=ppm, total=(ppm * deploy.period), currency=owner.currency)
2017-07-28 21:31:44 -04:00
2017-03-08 19:55:12 -05:00
@vmanager.route('/<cmd>/<int:vmid>')
2017-03-08 13:53:09 -05:00
@login_required
def command(cmd=None, vmid=0):
#checks whether this is a valid command
2017-07-15 20:48:18 -04:00
valid_commands = ['vmstatus', 'vmstart', 'vmshutdown', 'vmstop', 'vmvnc']
2017-03-08 13:53:09 -05:00
if not cmd in valid_commands:
2017-06-06 09:49:32 -04:00
current_app.logger.warning(cmd + ' is not a valid command!')
2017-03-08 13:53:09 -05:00
abort(404)
2017-07-30 17:10:08 -04:00
#work with enabled deploys only that you own.
result = current_user.inv_deployments.filter_by(enabled=True)
2017-03-08 13:53:09 -05:00
inventory = []
for invcls in result:
2017-06-26 10:31:30 -04:00
inventory.extend([invcls.machine_id])
2017-06-06 09:49:32 -04:00
if current_user.is_administrator():
2017-07-15 20:48:18 -04:00
current_app.logger.warning('[ADMIN] Access override for cube id:{}'.format(vmid))
2017-06-06 09:49:32 -04:00
db_result = contact_proxmaster({}, cmd, vmid)
if cmd == 'vmvnc':
return redirect(db_result['url'])
else:
#checks if current user owns this vmid
if not vmid in inventory:
2017-07-15 20:48:18 -04:00
current_app.logger.error('[{}] Access violation with cube id: {}'.format(current_user.email, vmid))
#TODO: log ips
else:
db_result = contact_proxmaster({}, cmd, vmid)
#print(db_result)
2017-07-15 20:48:18 -04:00
if cmd == 'vmvnc':
return redirect(db_result['url'])
2017-03-08 13:53:09 -05:00
abort(404)
2017-07-28 21:31:44 -04:00
#APP STORE
@vmanager.route('/market/<int:group_id>', methods=['GET'])
@login_required
def market(group_id=0):
page = { 'title': 'Market' }
allproducts = Product.get_products()
allgroups = current_app.config['GROUPS']
if group_id == 0:
return render_template('vmanager/market.html', groups=allgroups, products=allproducts)
filtered_products = {}
for key, value in allproducts.items():
if value['group'] == group_id:
filtered_products[key] = value
if filtered_products == {}:
abort(404)
return render_template('vmanager/marketgroup.html', groupname=allgroups[group_id], products=filtered_products)