add slaveswitcher to the order confirm button

This commit is contained in:
deflax 2018-04-02 11:49:32 +03:00
parent fd24153ddb
commit 5d088b7dd7
5 changed files with 94 additions and 95 deletions

View file

@ -38,8 +38,9 @@ def index():
@fresh_login_required @fresh_login_required
@admin_required @admin_required
def list_orders(): def list_orders():
AllOrders = Order.query.filter_by(status='new').all() NewOrders = Order.query.filter_by(status='new').all()
return render_template('admin/list_orders.html', orders=AllOrders) AcceptedOrders = Order.query.filter_by(status='accepted').all()
return render_template('admin/list_orders.html', neworders=NewOrders, oldorders=AcceptedOrders)
@admin.route("/listdeployments", methods=['GET']) @admin.route("/listdeployments", methods=['GET'])
@fresh_login_required @fresh_login_required

View file

@ -28,7 +28,7 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for order in orders %} {% for order in neworders %}
<tr> <tr>
<td data-title="User"><a href="{{ url_for('panel.dashboard', user_pid=order.user_id) }}">{{ order.owner.email }}</a></td> <td data-title="User"><a href="{{ url_for('panel.dashboard', user_pid=order.user_id) }}">{{ order.owner.email }}</a></td>
<td data-title="Region">{{ order.region.description }}</td> <td data-title="Region">{{ order.region.description }}</td>
@ -40,6 +40,19 @@
<td data-title="Status">{{ order.status }}</td> <td data-title="Status">{{ order.status }}</td>
<td><button class="btn btn-default btn-success" onclick="window.open('{{ url_for('vmanager.vmcreate', orderid=order.pid) }}','_self');"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Confirm</button></td> <td><button class="btn btn-default btn-success" onclick="window.open('{{ url_for('vmanager.vmcreate', orderid=order.pid) }}','_self');"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Confirm</button></td>
{% endfor %} {% endfor %}
{% for order in oldorders %}
<tr>
<td data-title="User"><a href="{{ url_for('panel.dashboard', user_pid=order.user_id) }}">{{ order.owner.email }}</a></td>
<td data-title="Region">{{ order.region.description }}</td>
<td data-title="Recipe"><a href="#" title="{{ order.recipe.description }}">{{ order.recipe.templatefile }}</a></td>
<td data-title="Parameter1">{{ order.parameter1 }}</td>
<td data-title="Parameter2">{{ order.parameter2 }}</td>
<td data-title="Parameter3">{{ order.parameter3 }}</td>
<td data-title="Parameter4">{{ order.parameter4 }}</td>
<td data-title="Status">{{ order.status }}</td>
<td></td>
{% endfor %}
</tr> </tr>
</tbody> </tbody>
</table> </table>

View file

@ -4,37 +4,20 @@
{% block page_content %} {% block page_content %}
<div class="page-header"> <div class="page-header">
<h1>Deploy</h1> <h1>Deployment order #{{ order.pid }}</h1>
</div> </div>
<div class="container-fluid">
<br />
<div class="row">
<div class="col-md-12"> <div class="col-md-12">
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-heading">Create Deployment</div> <div class="panel-heading">Create Deployment</div>
<div class="panel-body"> <div class="panel-body">
<form method="POST" action="{{ url_for('vmanager.vmcreate') }}"> <form method="POST" action="{{ url_for('vmanager.vmcreate', orderid=order.pid) }}">
<p> <label><strong><b>{{ form.slaveswitcher.label }}</b></strong></label>
{{ form.servername.label }}<br />{{ form.servername(size=42) }}<br /> <div>{{ form.slaveswitcher }}</div>
{% for error in form.servername.errors %} {% for error in form.slaveswitcher.errors %}
{{ error }}<br /> {{ error }}<br />
{% endfor %} {% endfor %}
</p>
<p>
{{ form.region.label }}<br /> {{ form.region }}<br />
{% for error in form.region.errors %}
{{ error }}<br />
{% endfor %}
</p>
<p>
{{ form.invite_key.label }}<br /> {{ form.invite_key }}<br />
{% for error in form.invite_key.errors %}
{{ error }}<br />
{% endfor %}
</p>
<p> <p>
{{ form.csrf_token() }} {{ form.csrf_token() }}
{{ form.submit }} {{ form.submit }}
@ -43,9 +26,5 @@
</div> </div>
</div> </div>
</div> </div>
</div>
</div>
{% endblock %} {% endblock %}

View file

@ -1,20 +1,7 @@
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, DecimalField from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, DecimalField
from wtforms import validators, ValidationError from wtforms import validators, ValidationError
from wtforms.fields.html5 import EmailField
from .. import db
class CreateForm(FlaskForm):
region_choices = [(1, 'Plovdiv, Bulgaria')]
servername = StringField('Domain Name:', [validators.Regexp(message='ex.: myservice1.com, myservice2.local', regex='^[a-zA-Z0-9][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.([a-zA-Z]{1,6}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,3})$'), validators.Length(6,64)])
region = SelectField('Region:', choices=region_choices, coerce=int)
invite_key = StringField('Invite Code:', [validators.DataRequired(), validators.Length(6,35)])
def validate_invite_key(self, field):
if field.data != 'invitation1919':
raise ValidationError('Denied')
submit = SubmitField('Create')
class ActivateForm(FlaskForm): class ActivateForm(FlaskForm):
period = SelectField('Deploy Period', choices=[(1, '1 Month'), (2, '2 Months'), (3, '3 Months'), (6, '6 Months'), (12, '1 Year'), (24, '2 Years')], coerce=int) period = SelectField('Deploy Period', choices=[(1, '1 Month'), (2, '2 Months'), (3, '3 Months'), (6, '6 Months'), (12, '1 Year'), (24, '2 Years')], coerce=int)

View file

@ -3,10 +3,10 @@ from flask_login import login_required, login_user, logout_user, current_user
from flask_sqlalchemy import get_debug_queries from flask_sqlalchemy import get_debug_queries
from . import vmanager from . import vmanager
from .forms import CreateForm, ActivateForm from .forms import ActivateForm
from .. import db, csrf from .. import db, csrf
from ..email import send_email from ..email import send_email
from ..models import User, Permission, Transaction, Deployment, PubVLAN, Service, Region, Server, Address, Domain, contact_proxmaster from ..models import User, Permission, Transaction, Order, Deployment, PubVLAN, Service, Region, Server, Address, Domain, contact_proxmaster
from ..decorators import admin_required, permission_required from ..decorators import admin_required, permission_required
import json import json
@ -53,12 +53,27 @@ def slavetables():
@login_required @login_required
@admin_required @admin_required
def vmcreate(orderid): def vmcreate(orderid):
form = CreateForm() from flask_wtf import FlaskForm
if form.validate_on_submit(): from wtforms import validators, RadioField, SubmitField
#selects the chosen region
selected_region = Region.query.filter_by(pid=int(form.region.data)).first()
#create new machine... order = Order.query.filter_by(pid=int(orderid)).first()
if order == None:
abort(403)
servers = Server.query.filter_by(region_id=int(order.region_id)).all()
serverchoices = []
for server in servers:
serverchoice = (str(server.pid), str(server.name))
serverchoices.append(serverchoice)
#TODO: check api for happiness and preselect suggested slave
happyslave = '2' #warrior in our case
class SlaveForm(FlaskForm):
slaveswitcher = RadioField('Select Slave Server', [validators.Required()], choices=serverchoices, default=happyslave)
submit = SubmitField('Create')
form = SlaveForm()
if form.validate_on_submit():
data = { 'clientid': str(current_user.pid), data = { 'clientid': str(current_user.pid),
'clientemail': str(current_user.email), 'clientemail': str(current_user.email),
'hostname': 'c' + str(current_user.pid) + '-' + str(form.servername.data), 'hostname': 'c' + str(current_user.pid) + '-' + str(form.servername.data),
@ -80,17 +95,63 @@ def vmcreate(orderid):
deployment = Deployment(user_id=int(current_user.pid), machine_alias=str(form.servername.data), period=1, machine_id=query['unit_id'], machine_cpu=data['cpu'], machine_mem=data['mem'], machine_hdd=data['hdd'], enabled=True, protected=False, daysleft=15, warning=True, discount=0, server_id=int(selected_slave.pid)) deployment = Deployment(user_id=int(current_user.pid), machine_alias=str(form.servername.data), period=1, machine_id=query['unit_id'], machine_cpu=data['cpu'], machine_mem=data['mem'], machine_hdd=data['hdd'], enabled=True, protected=False, daysleft=15, warning=True, discount=0, server_id=int(selected_slave.pid))
db.session.add(deployment) db.session.add(deployment)
db.session.commit() db.session.commit()
new_vlan = PubVLAN(deploy_id=int(deployment.pid), vlan_id=int(query['vlanid'])) new_vlan = PubVLAN(deploy_id=int(deployment.pid), vlan_id=int(query['vlanid']))
db.session.add(new_vlan) db.session.add(new_vlan)
db.session.commit() db.session.commit()
order.status = 'accepted'
db.session.update(order)
db.session.commit()
flash('A new deployment is created successfully in region "{}".'.format(str(selected_region.description))) flash('A new deployment is created successfully in region "{}".'.format(str(selected_region.description)))
return redirect(url_for('panel.dashboard')) return redirect(url_for('panel.dashboard'))
else: else:
flash('Deployment could not be created! Please try again later...') flash('Deployment could not be created! Please try again later...')
return redirect(url_for('panel.dashboard')) return redirect(url_for('panel.dashboard'))
return render_template('vmanager/create.html', form=form) return render_template('vmanager/create.html', form=form, order=order)
@vmanager.route('/vmremove/<int:unit_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def remove(unit_id=0):
data = { 'unit_id': int(unit_id),
'type': 'kvm' }
deploy = Deployment.query.filter_by(machine_id=int(unit_id)).first()
if current_user.is_administrator():
if deploy.protected is not True:
try:
#pubvlans depends on deploy as foreign key so delete them first
for pubvlan in deploy.inv_pubvlans:
#clean public addr assignment
if pubvlan.pubaddr != None:
pubvlan.pubaddr.pubvlan_id = None
pubvlan.pubaddr.user_id = None
db.session.commit()
db.session.delete(pubvlan)
db.session.commit()
query = contact_proxmaster(data, 'status')
if query['status'] == 'running':
query = contact_proxmaster(data, 'stop')
flash('Machine {} force stopped'.format(unit_id))
time.sleep(7)
query = contact_proxmaster(data, 'remove')
flash('Machine {} terminated'.format(unit_id))
deploy.deleted = True
deploy.enabled = False
deploy.warning = False
db.session.commit()
except Exception as e:
current_app.logger.error(e)
flash('Cannot delete machine {}'.format(unit_id))
return redirect(url_for('admin.list_archive'))
else:
current_app.logger.warning('Deployment id:{} is protected! Cannot be removed'.format(unit_id))
else:
current_app.logger.warning('[WARNING] Unauthorized attempt to remove Deployment id:{}'.format(unit_id))
abort(404)
@vmanager.route('/activate/<int:itemid>', methods=['GET', 'POST']) @vmanager.route('/activate/<int:itemid>', methods=['GET', 'POST'])
@login_required @login_required
@ -163,48 +224,6 @@ def activate(itemid=0):
return redirect(url_for('panel.dashboard')) return redirect(url_for('panel.dashboard'))
return render_template('vmanager/activate.html', form=form, deploy=deploy, cpu_cost=cpu_cost, mem_cost=mem_cost, hdd_cost=hdd_cost, tpm=tpm, ppm=ppm, discount=discount, total=total, currency=owner.currency) return render_template('vmanager/activate.html', form=form, deploy=deploy, cpu_cost=cpu_cost, mem_cost=mem_cost, hdd_cost=hdd_cost, tpm=tpm, ppm=ppm, discount=discount, total=total, currency=owner.currency)
@vmanager.route('/vmremove/<int:unit_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def remove(unit_id=0):
data = { 'unit_id': int(unit_id),
'type': 'kvm' }
deploy = Deployment.query.filter_by(machine_id=int(unit_id)).first()
if current_user.is_administrator():
if deploy.protected is not True:
try:
#pubvlans depends on deploy as foreign key so delete them first
for pubvlan in deploy.inv_pubvlans:
#clean public addr assignment
if pubvlan.pubaddr != None:
pubvlan.pubaddr.pubvlan_id = None
pubvlan.pubaddr.user_id = None
db.session.commit()
db.session.delete(pubvlan)
db.session.commit()
query = contact_proxmaster(data, 'status')
if query['status'] == 'running':
query = contact_proxmaster(data, 'stop')
flash('Machine {} force stopped'.format(unit_id))
time.sleep(7)
query = contact_proxmaster(data, 'remove')
flash('Machine {} terminated'.format(unit_id))
deploy.deleted = True
deploy.enabled = False
deploy.warning = False
db.session.commit()
except Exception as e:
current_app.logger.error(e)
flash('Cannot delete machine {}'.format(unit_id))
return redirect(url_for('admin.list_archive'))
else:
current_app.logger.warning('Deployment id:{} is protected! Cannot be removed'.format(unit_id))
else:
current_app.logger.warning('[WARNING] Unauthorized attempt to remove Deployment id:{}'.format(unit_id))
abort(404)
@vmanager.route('/command/<cmd>/<int:unit_id>') @vmanager.route('/command/<cmd>/<int:unit_id>')
@login_required @login_required
def command(cmd=None, unit_id=0): def command(cmd=None, unit_id=0):