Commit 0f5d9d0c authored by Philippe Valfok's avatar Philippe Valfok

Acompanhamento de criação de droplets adicionado à visualização de clientes.

parent f10d1dbd
......@@ -92,13 +92,17 @@ def altera_named(domain_name, file_db_name):
return local_named_path
def cria_arquivo_db(file_db_name):
def cria_arquivo_db(domain_name, file_db_name, droplet_ip):
"""
Função para criar o arquivo 'subdominio.dominio.com.br.db'
Que será adicionado em /var/named/
:param domain_name: Nome do subdomínio
:type domain_name: str
:param file_db_name: Nome do arquivo db
:type file_db_name: str
:param droplet_ip: O subdomínio apontará para este IP
:type droplet_ip: str
:returns file_path: Localização/Path local do arquivo
:rtype: str
"""
......@@ -130,7 +134,7 @@ def exec_add_domain(domain_name, droplet_ip):
path_db = '/var/named/'
file_db_name = "%s.pege.com.br.db" % domain_name
# Pegando arquivo named.conf do servidor
# Baixando arquivo named.conf do servidor
result = get(server_named_path, os.path.join(os.getcwd(), 'named.conf'))
if result.failed:
raise Exception('Erro ao tentar copiar arquivo named.conf do servidor.')
......@@ -139,7 +143,7 @@ def exec_add_domain(domain_name, droplet_ip):
local_named_path = altera_named(domain_name, file_db_name)
# Criando arquivo .db
file_db_path = cria_arquivo_db(file_db_name)
file_db_path = cria_arquivo_db(domain_name, file_db_name, droplet_ip)
# Enviando arquivo .db para o servidor
result = put(local_path=file_db_path, remote_path=path_db)
......@@ -181,7 +185,7 @@ def exec_add_domain(domain_name, droplet_ip):
raise Exception('Erro ao realizar chown no arquivo e/ou reiniciar o serviço.')
if __name__ == '__main__':
def main():
try:
domain_name = sys.argv[1]
droplet_ip = sys.argv[2]
......@@ -190,3 +194,7 @@ if __name__ == '__main__':
except Exception as err:
msg = "Erro ao executar comando! (%s)" % err
print msg
if __name__ == '__main__':
main()
......@@ -40,7 +40,7 @@ def exec_add_domain(domain_name, droplet_ip):
raise Exception("Erro ao executar script de criação de domínio. (%s)" % result.command)
if __name__ == '__main__':
def main():
try:
domain_name = sys.argv[1]
droplet_ip = sys.argv[2]
......@@ -49,3 +49,7 @@ if __name__ == '__main__':
except Exception as err:
msg = "Erro ao executar comando! (%s)" % err
print msg
if __name__ == '__main__':
main()
......@@ -10,9 +10,16 @@ from .models import Cliente
from .models import ChaveSSH
class ClienteAdmin(admin.ModelAdmin):
list_display = ('__str__', 'email', 'droplet_ip', 'droplet_status')
list_display_links = ('__str__', 'email')
search_fields = ('nome', 'domain_name', 'email', 'username')
list_per_page = 25
admin.site.site_tile = _(settings.SITE_TITLE)
admin.site.site_header = _(settings.SITE_HEADER)
admin.site.register(Configuracao, SingletonModelAdmin)
admin.site.register(Cliente)
admin.site.register(Cliente, ClienteAdmin)
admin.site.register(ChaveSSH)
......@@ -12,7 +12,7 @@ class Cliente(models.Model):
# Informações do cliente
nome = models.CharField(max_length=50)
domain_name = models.CharField(max_length=50, unique=True)
domain_name = models.CharField(_('Subdomínio'), max_length=50, unique=True)
email = models.EmailField(max_length=70)
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
......
import digitalocean
import os
import psycopg2
import subprocess
from decouple import config
......@@ -54,7 +54,10 @@ def criar_droplet(cliente):
if action.type == 'create':
cliente.set_status("Aguardando disponibilização do droplet.")
action.wait()
continue
droplet.load()
cliente.droplet_ip = droplet.ip_address
cliente.save()
break
else:
error = "Erro. Nenhuma action encontrada."
cliente.set_status(error)
......@@ -93,6 +96,18 @@ def criar_banco(cliente):
raise Exception(msg)
def criar_subdominio(cliente):
cliente.set_status("Iniciando criação do subdomínio.")
process = subprocess.run(
'/run_add_domain.py',
cliente.domain_name,
cliente.droplet_ip
)
cliente.set_status(
process.stdout.decode('utf-8').strip().split('\n').pop()
)
def configuracao_cliente_pipeline(cliente):
"""
Pipeline para configuração do servidor do cliente.
......@@ -105,5 +120,6 @@ def configuracao_cliente_pipeline(cliente):
try:
criar_banco(cliente)
criar_droplet(cliente)
criar_subdominio(cliente)
except Exception as err:
cliente.set_status(err)
from django.urls import path
from backend.core.views import cliente_droplet_status
urlpatterns = [
path('droplet_status/<domain>', cliente_droplet_status, name='cliente-droplet-status'),
]
from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
from backend.core.models import Cliente
def cliente_droplet_status(request, domain):
data = {}
if request.method == 'GET':
if domain is not None:
cliente = Cliente.objects.get(domain_name=domain)
data['result'] = {
'status': cliente.droplet_status,
'ip': cliente.droplet_ip
}
else:
data['result'] = 'Nenhum domínio enviado.'
else:
data['result'] = 'Método incorreto.'
return JsonResponse(data)
......@@ -16,7 +16,10 @@ Including another URLconf
from django.contrib import admin
from django.urls import include, path
from backend.core import urls as core_urls
urlpatterns = [
path('', admin.site.urls),
path('manager/', include(core_urls)),
path('django-rq/', include('django_rq.urls')),
]
{% extends "admin/change_list.html" %}
{% block extrahead %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function status_update(line){
var client_data = line.children[1].textContent.split(' - '),
client_name = client_data[0],
client_domain = client_data[1].split('.')[0];
$.get("/manager/droplet_status/" + client_domain,
function (data, status) {
$(line).find('.field-droplet_status').text(data.result.status);
$(line).find('.field-droplet_ip').text(data.result.ip);
}
);
}
$(document).ready( function () {
$('tbody tr').map( function(index, line) {
var line = this;
setInterval(function(){
status_update(line);
}, 3000);
});
});
</script>
{% endblock %}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment