atualizando DIARIO_MANAGER para INFATEC_MANAGER

parent 9e76ee22
......@@ -14,19 +14,19 @@ from datetime import datetime
# Estrutura do arquivo .db que será usada como base
PONTO_DB = """$TTL 14400
__domain_name__.pege.com.br. 86400 IN SOA ns1.infatec.net.br. abuse.infatec.net.br. (
__subdomain_name__.__domain_name__. 86400 IN SOA ns1.infatec.net.br. abuse.infatec.net.br. (
__date__01 ;Serial Number
3600 ;refresh
7200 ;retry
1209600 ;expire
86400 ;minimum
)
__domain_name__.pege.com.br. 86400 IN NS ns1.infatec.net.br.
__domain_name__.pege.com.br. 86400 IN NS ns2.infatec.net.br.
__domain_name__.pege.com.br. 14400 IN A __droplet_ip__
__domain_name__.pege.com.br. 14400 IN A __droplet_ip__
mail 14400 IN CNAME __domain_name__.pege.com.br.
www 14400 IN CNAME __domain_name__.pege.com.br.
__subdomain_name__.__domain_name__. 86400 IN NS ns1.infatec.net.br.
__subdomain_name__.__domain_name__. 86400 IN NS ns2.infatec.net.br.
__subdomain_name__.__domain_name__. 14400 IN A __droplet_ip__
__subdomain_name__.__domain_name__. 14400 IN A __droplet_ip__
mail 14400 IN CNAME __subdomain_name__.__domain_name__.
www 14400 IN CNAME __subdomain_name__.__domain_name__.
ftp 14400 IN A __droplet_ip__
cpanel 14400 IN A __droplet_ip__
webdisk 14400 IN A __droplet_ip__
......@@ -37,7 +37,7 @@ webmail 14400 IN A 209.126.103.85
"""
# Estrutura da zona que será adicionada ao named.conf
ZONE = '};\n\n\nzone "__domain_name__.pege.com.br" {\n\ttype ' +\
ZONE = '};\n\n\nzone "__subdomain_name__.__domain_name__" {\n\ttype ' +\
'master;\n\tfile "/var/named/__file_db_name__";\n};\n\n};'
......@@ -54,13 +54,13 @@ env.hosts = [
env.user = 'root'
def altera_named(domain_name, file_db_name):
def altera_named(subdomain_name, file_db_name):
"""
Função para atualizar o arquivo 'named.conf' com o novo subdomínio
Que será adicionado em /etc/named.conf
:param domain_name: Nome do subdomínio
:type domain_name: str
:param subdomain_name: Nome do subdomínio
:type subdomain_name: str
:param file_db_name: Nome do arquivo db
:type file_db_name: str
:returns local_named_path: Localização/Path local do arquivo
......@@ -80,7 +80,7 @@ def altera_named(domain_name, file_db_name):
named_content = named_content.replace(
text_to_replace,
ZONE.replace(
'__domain_name__', domain_name
'__subdomain_name__', subdomain_name
).replace(
'__file_db_name__', file_db_name
)
......@@ -92,7 +92,7 @@ def altera_named(domain_name, file_db_name):
return local_named_path
def cria_arquivo_db(domain_name, file_db_name, droplet_ip):
def cria_arquivo_db(subdomain_name, domain_name, file_db_name, droplet_ip):
"""
Função para criar o arquivo 'subdominio.dominio.com.br.db'
Que será adicionado em /var/named/
......@@ -110,7 +110,8 @@ def cria_arquivo_db(domain_name, file_db_name, droplet_ip):
file_db = open(file_path, 'w')
file_db.write(
PONTO_DB.replace('__domain_name__', domain_name)
PONTO_DB.replace('__subdomain_name__', subdomain_name)
.replace('__domain_name__', domain_name)
.replace('__droplet_ip__', droplet_ip)
.replace('__date__', datetime.now().strftime("%Y%m%d"))
)
......@@ -120,7 +121,7 @@ def cria_arquivo_db(domain_name, file_db_name, droplet_ip):
return file_path
def exec_add_domain(domain_name, droplet_ip):
def exec_add_domain(subdomain_name, domain_name, droplet_ip):
"""
Função para adicionar subdomínios ao domínio "pege.com.br".
......@@ -132,7 +133,7 @@ def exec_add_domain(domain_name, droplet_ip):
"""
server_named_path = "/etc/named.conf"
path_db = '/var/named/'
file_db_name = "%s.pege.com.br.db" % domain_name
file_db_name = "%s.%s.db" % (subdomain_name, domain_name)
# Baixando arquivo named.conf do servidor
result = get(server_named_path, os.path.join(os.getcwd(), 'named.conf'))
......@@ -140,10 +141,10 @@ def exec_add_domain(domain_name, droplet_ip):
raise Exception('Erro ao tentar copiar arquivo named.conf do servidor.')
# Alterando arquivo named.conf
local_named_path = altera_named(domain_name, file_db_name)
local_named_path = altera_named(subdomain_name, file_db_name)
# Criando arquivo .db
file_db_path = cria_arquivo_db(domain_name, file_db_name, droplet_ip)
file_db_path = cria_arquivo_db(subdomain_name, domain_name, file_db_name, droplet_ip)
# Enviando arquivo .db para o servidor
result = put(local_path=file_db_path, remote_path=path_db)
......@@ -187,10 +188,11 @@ def exec_add_domain(domain_name, droplet_ip):
def main():
try:
domain_name = sys.argv[1]
droplet_ip = sys.argv[2]
execute(exec_add_domain, domain_name, droplet_ip)
print 'Sucesso ao executar script para criação do domínio "{}".'.format(domain_name)
subdomain_name = sys.argv[1]
domain_name = sys.argv[2]
droplet_ip = sys.argv[3]
execute(exec_add_domain, subdomain_name, domain_name, droplet_ip)
print 'Sucesso ao executar script para criação do domínio "{}.{}".'.format(subdomain_name, domain_name)
except Exception as err:
msg = "Erro ao executar comando! (%s)" % err
print msg
......
......@@ -23,28 +23,29 @@ env.user = os.environ.get('MANAGER_HOST_USER')
env.password = os.environ.get('MANAGER_HOST_PASSWORD')
def exec_add_domain(domain_name, droplet_ip):
def exec_add_domain(subdomain_name, domain_name, droplet_ip):
"""
Função para acessar o servidor MANAGER e iniciar o script que adicionará
o novo subdomínio ao servidor DNS.
:param domain_name: Nome do subdomínio
:type domain_name: str
:param subdomain_name: Nome do subdomínio
:type subdomain_name: str
:param droplet_ip: O subdomínio apontará para este IP
:type droplet_ip: str
:returns:
"""
script_path = "django_apps/DIARIO_MANAGER/scripts/add_domain.py"
result = run("chmod +x %s && %s %s %s" % (script_path, script_path, domain_name, droplet_ip))
result = run("chmod +x %s && %s %s %s %s" % (script_path, script_path, subdomain_name, domain_name, droplet_ip))
if result.failed:
raise Exception("Erro ao executar script de criação de domínio. (%s)" % result.command)
def main():
try:
domain_name = sys.argv[1]
droplet_ip = sys.argv[2]
execute(exec_add_domain, domain_name, droplet_ip)
subdomain_name = sys.argv[1]
domain_name = sys.argv[2]
droplet_ip = sys.argv[3]
execute(exec_add_domain, subdomain_name, domain_name, droplet_ip)
print "Criação de domínio executada com sucesso."
except Exception as err:
msg = "Erro ao executar comando! (%s)" % err
......
......@@ -17,9 +17,9 @@ class ClienteForm(forms.ModelForm):
model = Cliente
fields = "__all__"
def clean_domain_name(self):
data = self.cleaned_data['domain_name']
self.username_domain_name_clean(data)
def clean_subdomain_name(self):
data = self.cleaned_data['subdomain_name']
self.username_subdomain_name_clean(data)
return data
def clean_username(self):
......@@ -27,7 +27,7 @@ class ClienteForm(forms.ModelForm):
self.username_domain_name_clean(data)
return data
def username_domain_name_clean(self, data):
def username_subdomain_name_clean(self, data):
if not data.isalnum() and not data.replace('_', '').isalnum() and not data.replace('_', '').isalnum():
raise forms.ValidationError('Somente letras, números, "_" e "-".')
if data.lower() != data:
......@@ -37,7 +37,7 @@ class ClienteForm(forms.ModelForm):
class ClienteAdmin(admin.ModelAdmin):
list_display = ('__str__', 'email', 'droplet_ip', 'droplet_status')
list_display_links = ('__str__', 'email')
search_fields = ('nome', 'domain_name', 'email', 'username')
search_fields = ('nome', 'subdomain_name', 'email', 'username')
list_per_page = 25
form = ClienteForm
......
from .chave_ssh import ChaveSSH
from .cliente import Cliente
from .sistema import Sistema
from .configuracao import Configuracao
......@@ -12,10 +12,11 @@ class Cliente(models.Model):
# Informações do cliente
nome = models.CharField(max_length=50)
domain_name = models.CharField(_('Subdomínio'), max_length=50, unique=True)
subdomain_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)
sistema = models.ForeignKey('Sistema', models.PROTECT, related_name='clientes')
# Informações do droplet
droplet_id = models.CharField(_('ID do droplet'), max_length=50, blank=True, null=True)
......@@ -32,7 +33,7 @@ class Cliente(models.Model):
"""Representação da classe na forma de String"""
return '{} - {}.{}'.format(
self.nome.title(),
self.domain_name,
self.subdomain_name,
settings.BASE_DOMAIN
)
......@@ -76,3 +77,11 @@ class Cliente(models.Model):
self.droplet_logs,
log
)
@property
def user_data(self):
return self.sistema.droplets_user_data.replace('__domain_name__', self.subdomain_name)
@property
def domain_name(self):
return self.sistema.domain_name
......@@ -15,7 +15,7 @@ class Configuracao(SingletonModel):
droplets_size = models.CharField(_('Tamanho dos Droplets'), max_length=50, default="s-1vcpu-1gb")
droplets_backups = models.BooleanField(default=False)
droplets_ipv6 = models.BooleanField(default=False)
droplets_user_data = models.TextField(blank=True)
#droplets_user_data = models.TextField(blank=True) movido para o model de Sistema
def __str__(self):
"""String representations for configuration"""
......
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
import django_rq
class Sistema(models.Model):
"""Model definition for Sistema."""
# Informações do cliente
nome = models.CharField(max_length=50)
domain_name = models.CharField(_('Domínio'), max_length=50, unique=True)
droplets_user_data = models.TextField(blank=True)
class Meta:
"""Meta definition for Sistema."""
verbose_name = 'Sistema'
verbose_name_plural = 'Sistemas'
def __str__(self):
"""Representação da classe na forma de String"""
return '{} - {} - {}'.format(
self.nome.title(),
self.domain_name,
self.droplets_user_data
)
......@@ -31,14 +31,14 @@ def criar_droplet(cliente):
droplet = digitalocean.Droplet(
token=configuracoes.token,
name="{}-{}".format(
cliente.username, cliente.domain_name
cliente.username, cliente.subdomain_name
).replace('_', '-'),
region=configuracoes.droplets_region,
image=configuracoes.droplets_image,
size_slug=configuracoes.droplets_size,
backups=configuracoes.droplets_backups,
ipv6=configuracoes.droplets_ipv6,
user_data=configuracoes.droplets_user_data.replace('__domain_name__', cliente.domain_name),
user_data=cliente.user_data,
ssh_keys=configuracoes.ssh_keys
)
......@@ -92,7 +92,7 @@ def criar_banco(cliente):
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
cur.execute("CREATE DATABASE {} ;".format(cliente.domain_name))
cur.execute("CREATE DATABASE {} ;".format(cliente.subdomain_name))
except Exception as err:
msg = "Erro ao criar banco de dados. ({})".format(err)
cliente.set_status(msg)
......@@ -104,6 +104,7 @@ def criar_subdominio(cliente):
process = subprocess.run(
[
'/run_add_domain.py',
cliente.subdomain_name,
cliente.domain_name,
cliente.droplet_ip
], stdout=subprocess.PIPE
......
......@@ -4,5 +4,5 @@ from backend.core.views import cliente_droplet_status
urlpatterns = [
path('droplet_status/<domain>', cliente_droplet_status, name='cliente-droplet-status'),
path('droplet_status/<subdomain>', cliente_droplet_status, name='cliente-droplet-status'),
]
......@@ -3,11 +3,11 @@ from django.http import JsonResponse
from backend.core.models import Cliente
def cliente_droplet_status(request, domain):
def cliente_droplet_status(request, subdomain):
data = {}
if request.method == 'GET':
if domain is not None:
cliente = Cliente.objects.get(domain_name=domain)
cliente = Cliente.objects.get(subdomain_name=subdomain)
data['result'] = {
'status': cliente.droplet_status,
'ip': cliente.droplet_ip
......
......@@ -11,7 +11,7 @@ SITE_TITLE = config('SITE_TITLE', default='Administração Infatec')
SITE_HEADER = config('SITE_HEADER', default='Administração Infatec')
# Base Domain
BASE_DOMAIN = config('BASE_DOMAIN', default='diariodigital.pege.com.br')
#BASE_DOMAIN = config('BASE_DOMAIN', default='diariodigital.pege.com.br') movido para o model de Sistema
# Base directory of projetc
......
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