Skip to content

Commit

Permalink
Merge pull request #6 from agepoly/correction_mail
Browse files Browse the repository at this point in the history
Correction mail
  • Loading branch information
the-glu committed Dec 10, 2013
2 parents 04ad63a + 165b65e commit 56bee46
Show file tree
Hide file tree
Showing 5 changed files with 293 additions and 5 deletions.
2 changes: 2 additions & 0 deletions app/settingsLocal.py.dist
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,5 @@ BROKER_URL = ''

NGNIX_SSL_PEM = ''
NGNIX_SSL_KEY = ''

MYSQL_VM = ''
39 changes: 39 additions & 0 deletions fabrun/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ def run_task(id):
else:
needUser = False

needKomUser = '[$AG:NeedKomUser]' in description
needSudo = '[$AG:NeedSudo]' in description
needMysqlPassword = '[$AG:NeedMysqlPassword]' in description
needSrvIp = '[$AG:NeedSrvIp]' in description

if not task.server.ssh_connection_string_from_gestion:
task.stderr = 'I don\'t know how to connect to the server'
task.end_date = timezone.now()
Expand All @@ -56,6 +61,28 @@ def run_task(id):
task.save()
return

if needKomUser or needSudo or needMysqlPassword:
if not task.args:
task.stderr = 'I needed special arguements bot task.args wasen\'t set !.'
task.end_date = timezone.now()
task.save()
return
try:
import json
arg_data = json.loads(task.args)
except:
task.stderr = 'I needed special arguements bot task.args wasen\'t json !.'
task.end_date = timezone.now()
task.save()
return

for (arg, name) in ((needKomUser, 'user'), (needSudo, 'sudo'), (needMysqlPassword, 'password')):
if arg and name not in arg_data:
task.stderr = 'I needed ' + name + ' but it wasent in args.'
task.end_date = timezone.now()
task.save()
return

thing_to_set = ''

if needGestion:
Expand All @@ -70,6 +97,18 @@ def run_task(id):
if needUser:
thing_to_set += ',fab_user=' + task.args

if needKomUser:
thing_to_set += ',fab_komuser=' + arg_data['user']

if needSudo:
thing_to_set += ',fab_addsudo=' + arg_data['sudo']

if needMysqlPassword:
thing_to_set += ',fab_mysqlpassword=' + arg_data['password']

if needSrvIp:
thing_to_set += ',fab_srvip=' + task.server.internal_ip

thing_to_set = thing_to_set[1:]

out, err = subprocess.Popen(['fab', '--abort-on-prompts', '-p', task.server.random_proxmox_password(), '-H', task.server.get_host_for_fabric(), '--set=' + thing_to_set, task.command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=settings.FABRIC_FOLDER).communicate()
Expand Down
2 changes: 1 addition & 1 deletion fabrun/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from fabrun.models import Task
from fabrun.tasks import run_task

KEYWORDS = ('[$AG:NeedGestion]', '[$AG:NeedKM]', '[$AG:NeedUser]')
KEYWORDS = ('[$AG:NeedGestion]', '[$AG:NeedKM]', '[$AG:NeedUser]', '[$AG:NeedKomUser]', '[$AG:NeedSudo]', '[$AG:NeedMysqlPassword]', '[$AG:NeedSrvIp]')


@login_required
Expand Down
14 changes: 10 additions & 4 deletions hostnameforwarding/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,16 @@ def get_conf(request, pk):
if host.port_from == 443 and settings.NGNIX_SSL_PEM != '' and settings.NGNIX_SSL_KEY != '':
script += """ ssl on;
"""
script += """ ssl_certificate """ + settings.NGNIX_SSL_PEM + """;
"""
script += """ ssl_certificate_key """ + settings.NGNIX_SSL_KEY + """;
"""
if host.domain != 'truffe.polylan.ch':
script += """ ssl_certificate """ + settings.NGNIX_SSL_PEM + """;
"""
script += """ ssl_certificate_key """ + settings.NGNIX_SSL_KEY + """;
"""
else:
script += """ ssl_certificate """ + settings.NGNIX_SSL_PEM + """-polylan;
"""
script += """ ssl_certificate_key """ + settings.NGNIX_SSL_KEY + """-polylan;
"""


if host.force_https:
Expand Down
241 changes: 241 additions & 0 deletions wizard/wizards/setup_agepvm_for_com.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
from _wizard import _Wizard

from django import forms

from django.conf import settings

from django.utils import timezone

from django.core.mail import send_mail

from servers.models import Server, ServerUser
from fabrun.models import Task
from fabrun.tasks import run_task

import os
import uuid

from hostnameforwarding.models import Hostnameforwarded
from hostnameforwarding.tasks import update_hostnameforwarding


class Step1Form(forms.Form):
server = forms.ModelChoiceField(queryset=Server.objects.exclude(ssh_connection_string_from_gestion=None).order_by('name'))


class Step2Form(forms.Form):

username = forms.CharField(help_text='Be nice and avoid strange chars here. [a-z] will be fine.')
password = forms.CharField()

grant_sudo_rights = forms.BooleanField(initial=False, required=False)

create_mysql_database = forms.BooleanField(initial=True, required=False)
mysql_password = forms.CharField()

create_epfl_host = forms.BooleanField(initial=True, required=False)
epfl_host = forms.CharField()

send_confirmation_email = forms.BooleanField(initial=True, required=False)
mail_dest = forms.CharField(help_text='Comma-separted values')

def __init__(self, server, build_inital_values, request, *args, **kwargs):
super(Step2Form, self).__init__(*args, **kwargs)

self.server = server

if build_inital_values:

name = server.name.split('.')[0]

self.fields["username"].initial = name
self.fields["epfl_host"].initial = name + '.epfl.ch'
self.fields['mail_dest'].initial = request.user.email
self.fields['mysql_password'].initial = str(uuid.uuid4())
self.fields['password'].initial = str(uuid.uuid4())


class SetupAgepVMForCom(_Wizard):
"""Agep's Wizard for VMs."""

_name = 'SetupAgepVMForCom'
_description = 'Wizard to setup a new VM for a commision: Add user, setup apache and php, add x.epfl.ch entry, setup database and send confirmation email.'

_nb_step = 2
_nb_task = 11

_steps_names = ['Server selection', 'Details confirmation']
_tasks_names = ['Create user', 'Set password', 'Copy config scripts', 'Add user to the server', 'Create ssh folder', 'Update keymanager', 'Run keymanager', 'Create hostforwarding entry', 'Setup apache, php and cie', 'Setup mysql database', 'Send confirmation email']

def display_step_1(self, request):

if request.method == 'POST':
form = Step1Form(request.POST)
else:
form = Step1Form()

return ('', form, "$('#id_server').css('width', '220px').select2();")

def save_step_1(self, form):
server_pk = form.cleaned_data['server'].pk

return {'server_pk': server_pk}

def display_step_2(self, request):

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

if request.method == 'POST':
form = Step2Form(server, False, request, request.POST)
else:
form = Step2Form(server, True, request)

return ('If needed, you can edit values of this forms. You can leave them to defaults values, everything should be ok !', form, "$('#id_template').css('width', '220px').select2();")

def save_step_2(self, form):
return form.cleaned_data

def do_task_1(self):
"""Create the user"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

os.system('ssh ' + server.ssh_connection_string_from_gestion + ' useradd -s /bin/zsh -m ' + self.step_data[1]['username'])

return (True, None)

def do_task_2(self):
"""Set the user password"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

if self.step_data[1]['password'] != '':
os.system('ssh ' + server.ssh_connection_string_from_gestion + ' "echo \'' + self.step_data[1]['username'] + ':' + self.step_data[1]['password'] + '\' | chpasswd"')

return (True, None)

def do_task_3(self):
"""Copy config scripts"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

t = Task(creation_date=timezone.now(), server=server, command=settings.COPY_USER_CONFIG_FABRIC_SCRIPT, args=self.step_data[1]['username'])
t.save()
run_task(t.pk)

return (True, None)

def do_task_4(self):
"""Add user to the server"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

ServerUser(server=server, name=self.step_data[1]['username']).save()

return (True, None)

def do_task_5(self):
"""Create the SSH folder"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

os.system('ssh ' + server.ssh_connection_string_from_gestion + ' "mkdir ~' + self.step_data[1]['username'] + '/.ssh/"')
os.system('ssh ' + server.ssh_connection_string_from_gestion + ' "chown ' + self.step_data[1]['username'] + ' ~' + self.step_data[1]['username'] + '/.ssh/"')

return (True, None)

def do_task_6(self):
"""Update the keymanager"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

t = Task(creation_date=timezone.now(), server=server, command=settings.UPDATE_KM_FABRIC_SCRIPT)
t.save()
run_task(t.pk)

return (True, None)

def do_task_7(self):
"""Run the keymanager"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

t = Task(creation_date=timezone.now(), server=server, command=settings.RUN_KM_FABRIC_SCRIPT)
t.save()
run_task(t.pk)

return (True, None)

def do_task_8(self):
"""Add the new entry for hostforwarding"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

if self.step_data[1]['create_epfl_host']:

if settings.NGNIX_SSL_KEY != '':
Hostnameforwarded(server_host=server.vm_host, server_to=server, domain=self.step_data[1]['epfl_host'], port_from=443).save()

Hostnameforwarded(server_host=server.vm_host, server_to=server, domain=self.step_data[1]['epfl_host']).save()
update_hostnameforwarding()

return (True, None)

def do_task_9(self):
"""Run the fabric script to setup the server with apache and cie"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

t = Task(creation_date=timezone.now(), server=server, command='agep.setup_agep_vm')

data = {'user': self.step_data[1]['username'], 'sudo': 'False'}
if self.step_data[1]['grant_sudo_rights']:
data['sudo'] = 'True'
import json
t.args = json.dumps(data)

t.save()
run_task(t.pk)


return (True, None)

def do_task_10(self):
"""Run the fabric script to setup mysql, if needed"""

server = Server.objects.get(name=settings.MYSQL_VM)

if self.step_data[1]['create_mysql_database']:

t = Task(creation_date=timezone.now(), server=server, command='agep.setup_mysql')

data = {'user': self.step_data[1]['username'], 'password': self.step_data[1]['mysql_password']}
import json
t.args = json.dumps(data)

t.save()
run_task(t.pk)


return (True, None)

def do_task_11(self):
"""Run the fabric script to setup mysql, if needed"""

server = Server.objects.get(pk=self.step_data[0]['server_pk'])

if self.step_data[1]['send_confirmation_email'] and self.step_data[1]['mail_dest']:

bdd = ''
sudo = ''

if self.step_data[1]['create_mysql_database']:
bdd = u'Les parametres d\'access a la base de donnée sont:\n - Username: ' + self.step_data[1]['username'] + u'\n- Mot de passe: ' + self.step_data[1]['mysql_password'] + u'\n- Host: mysql\n- Database: ' + self.step_data[1]['username'] + u'\nAdresse PhpMyAdmin : https://mysql.agepoly.ch/phpmyponey/ \n\n'
if self.step_data[1]['grant_sudo_rights']:
sudo = u'L\'utilisateur dispose des droits sudo. Merci de ne pas supprimer les cles SSH de root ou la VM sera potentiellement detruite automatiquement. Usage a vos risques et perils !\n\n'

send_mail(u'[AGEPoly::Serveurs] Parametres pour ' + server.name, u'Bonjour !\n\nJe suis le script de deployment de l\'AGEPoly et j\'ai le bonheur de vous annonce que j\'ai fini mon travail :]\n\nLes parametres pour la machine ' + server.name + ' sont les suivants:\n- Connection ssh: ssh ' + server.ssh_connection_string_from_backup.replace('root@', '') + '\n- Username: ' + self.step_data[1]['username'] + '\n- Mot de passe: ' + self.step_data[1]['password'] + '\n- Port : ' + server.get_port() + u'\n\nLes fichiers web sont a mettre dans le dossier ~/public_html/, les logs sont dans ~/logs/.\n\nPour uploader des fichiers, vous pouvez faire du SFTP, pour ceci utilisez des programmes comme WinSCP ou FileZilla qui sont gratuits.\n\n' + bdd + sudo + u'En cas de problèmes, contactez : serveuragep@polylan.ch\n\nJoyeuse journée,\nLe script de cération et le système azimut-gestion\n\nPs: N\'oubliez jamais de faire des backups ;)\n\n', 'nobody@agepoly.ch', self.step_data[1]['mail_dest'].split(','), fail_silently=False)


return (True, None)

0 comments on commit 56bee46

Please sign in to comment.