Commit b436bd51 authored by Stauros Kroustouris's avatar Stauros Kroustouris

code cleanup, signals

parent e542d74b
===========
1.1.2 RELEASE
Updates and enhancements. Check documentation for updating from previous versions
- Rest Api
- Use Django signals for notifications
=======
1.1.1 RELEASE
......
from django.core.mail.message import EmailMessage
from django.conf import settings
def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
def get_peer_techc_mails(user):
mail = []
additional_mail = []
techmails_list = []
user_mail = '%s' % user.email
user_mail = user_mail.split(';')
techmails = user.get_profile().peer.techc_emails.all()
if techmails:
for techmail in techmails:
techmails_list.append(techmail.email)
if settings.NOTIFY_ADMIN_MAILS:
additional_mail = settings.NOTIFY_ADMIN_MAILS
mail.extend(additional_mail)
mail.extend(techmails_list)
return mail
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Route.requesters_address'
db.add_column(u'route', 'requesters_address',
self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Route.requesters_address'
db.delete_column(u'route', 'requesters_address')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'flowspec.fragmenttype': {
'Meta': {'object_name': 'FragmentType'},
'fragmenttype': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'flowspec.matchdscp': {
'Meta': {'object_name': 'MatchDscp', 'db_table': "u'match_dscp'"},
'dscp': ('django.db.models.fields.CharField', [], {'max_length': '24'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'flowspec.matchport': {
'Meta': {'object_name': 'MatchPort', 'db_table': "u'match_port'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'port': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '24'})
},
'flowspec.matchprotocol': {
'Meta': {'object_name': 'MatchProtocol', 'db_table': "u'match_protocol'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'protocol': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '24'})
},
'flowspec.route': {
'Meta': {'object_name': 'Route', 'db_table': "u'route'"},
'applier': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'destination': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'destinationport': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'matchDestinationPort'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['flowspec.MatchPort']"}),
'dscp': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['flowspec.MatchDscp']", 'null': 'True', 'blank': 'True'}),
'expires': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2015, 1, 15, 0, 0)'}),
'filed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'fragmenttype': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['flowspec.FragmentType']", 'null': 'True', 'blank': 'True'}),
'icmpcode': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'icmptype': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.SlugField', [], {'max_length': '128'}),
'packetlength': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'port': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'matchPort'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['flowspec.MatchPort']"}),
'protocol': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['flowspec.MatchProtocol']", 'null': 'True', 'blank': 'True'}),
'requesters_address': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'response': ('django.db.models.fields.CharField', [], {'max_length': '512', 'null': 'True', 'blank': 'True'}),
'source': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'sourceport': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'matchSourcePort'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['flowspec.MatchPort']"}),
'status': ('django.db.models.fields.CharField', [], {'default': "'PENDING'", 'max_length': '20', 'null': 'True', 'blank': 'True'}),
'tcpflag': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'then': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['flowspec.ThenAction']", 'symmetrical': 'False'})
},
'flowspec.thenaction': {
'Meta': {'ordering': "['action', 'action_value']", 'unique_together': "(('action', 'action_value'),)", 'object_name': 'ThenAction', 'db_table': "u'then_action'"},
'action': ('django.db.models.fields.CharField', [], {'max_length': '60'}),
'action_value': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['flowspec']
\ No newline at end of file
......@@ -20,13 +20,18 @@
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from flowspec.helpers import send_new_mail, get_peer_techc_mails
from utils import proxy as PR
from ipaddr import *
import datetime
import logging
from time import sleep
from junos import create_junos_name, policer_name
from junos import create_junos_name
import beanstalkc
from utils.randomizer import id_generator as id_gen
......@@ -167,7 +172,7 @@ class Route(models.Model):
expires = models.DateField(default=days_offset, verbose_name=_("Expires"))
response = models.CharField(max_length=512, blank=True, null=True, verbose_name=_("Response"))
comments = models.TextField(null=True, blank=True, verbose_name=_("Comments"))
requesters_address = models.CharField(max_length=255, blank=True, null=True)
def __unicode__(self):
return self.name
......@@ -183,7 +188,6 @@ class Route(models.Model):
self.name = "%s_%s" %(self.name, hash)
super(Route, self).save(*args, **kwargs) # Call the "real" save() method.
def clean(self, *args, **kwargs):
from django.core.exceptions import ValidationError
if self.destination:
......@@ -201,26 +205,125 @@ class Route(models.Model):
def commit_add(self, *args, **kwargs):
peer = self.applier.get_profile().peer.peer_tag
send_message("[%s] Adding rule %s. Please wait..." %(self.applier.username, self.name), peer)
send_message("[%s] Adding rule %s. Please wait..." % (self.applier.username, self.name), peer)
response = add.delay(self)
logger.info("Got add job id: %s" %response)
logger.info('Got add job id: %s' % response)
fqdn = Site.objects.get_current().domain
admin_url = 'https://%s%s' % (
fqdn,
reverse('edit-route', kwargs={'route_slug': self.name})
)
mail_body = render_to_string(
'rule_action.txt',
{
'route': self,
'address': self.requesters_address,
'action': 'creation',
'url': admin_url
}
)
user_mail = '%s' % self.applier.email
user_mail = user_mail.split(';')
send_new_mail(
settings.EMAIL_SUBJECT_PREFIX + 'Rule %s creation request submitted by %s' % (self.name, self.applier.username),
mail_body,
settings.SERVER_EMAIL, user_mail,
get_peer_techc_mails(self.applier)
)
d = {
'clientip': '%s' % self.requesters_address,
'user': self.applier.username
}
logger.info(mail_body, extra=d)
def commit_edit(self, *args, **kwargs):
peer = self.applier.get_profile().peer.peer_tag
send_message("[%s] Editing rule %s. Please wait..." %(self.applier.username, self.name), peer)
send_message(
'[%s] Editing rule %s. Please wait...' %
(
self.applier.username,
self.name
), peer
)
response = edit.delay(self)
logger.info("Got edit job id: %s" %response)
logger.info('Got edit job id: %s' % response)
fqdn = Site.objects.get_current().domain
admin_url = 'https://%s%s' % (
fqdn,
reverse(
'edit-route',
kwargs={'route_slug': self.name}
)
)
mail_body = render_to_string(
'rule_action.txt',
{
'route': self,
'address': self.requesters_address,
'action': 'edit',
'url': admin_url
}
)
user_mail = '%s' % self.applier.email
user_mail = user_mail.split(';')
send_new_mail(
settings.EMAIL_SUBJECT_PREFIX + 'Rule %s edit request submitted by %s' % (self.name, self.applier.username),
mail_body, settings.SERVER_EMAIL, user_mail,
get_peer_techc_mails(self.applier)
)
d = {
'clientip': self.requesters_address,
'user': self.applier.username
}
logger.info(mail_body, extra=d)
def commit_delete(self, *args, **kwargs):
reason_text = ''
reason = ''
if "reason" in kwargs:
reason = kwargs['reason']
reason_text = "Reason: %s. " %reason
reason_text = 'Reason: %s.' % reason
peer = self.applier.get_profile().peer.peer_tag
send_message("[%s] Suspending rule %s. %sPlease wait..." %(self.applier.username, self.name, reason_text), peer)
send_message(
'[%s] Suspending rule %s. %sPlease wait...' % (
self.applier.username,
self.name,
reason_text
), peer
)
response = delete.delay(self, reason=reason)
logger.info("Got delete job id: %s" %response)
logger.info('Got delete job id: %s' % response)
fqdn = Site.objects.get_current().domain
admin_url = 'https://%s%s' % (
fqdn,
reverse(
'edit-route',
kwargs={'route_slug': self.name}
)
)
mail_body = render_to_string(
'rule_action.txt',
{
'route': self,
'address': self.requesters_address,
'action': 'removal',
'url': admin_url
}
)
user_mail = '%' % self.applier.email
user_mail = user_mail.split(';')
send_new_mail(
settings.EMAIL_SUBJECT_PREFIX + 'Rule %s removal request submitted by %s' % (self.name, self.applier.username),
mail_body,
settings.SERVER_EMAIL,
user_mail,
get_peer_techc_mails(self.applier)
)
d = {
'clientip': self.requesters_address,
'user': self.applier.username
}
logger.info(mail_body, extra=d)
def has_expired(self):
today = datetime.date.today()
......@@ -242,7 +345,7 @@ class Route(models.Model):
except Exception as e:
self.status = "EXPIRED"
self.save()
logger.error("No routing options on device. Exception: %s" %e)
logger.error('No routing options on device. Exception: %s' % e)
return True
for route in routes:
if route.name == self.name:
......@@ -478,3 +581,16 @@ def send_message(msg, user):
tube_message = json.dumps({'message': str(msg), 'username':peer})
b.put(tube_message)
b.close()
def notify_user(sender, instance, created, **kwargs):
if created:
instance.commit_add()
else:
if instance.has_expired():
instance.commit_delete()
else:
instance.commit_edit()
post_save.connect(notify_user, sender=Route)
This diff is collapsed.
......@@ -36,6 +36,9 @@ class RouteViewSet(viewsets.ModelViewSet):
queryset = Route.objects.all()
serializer_class = RouteSerializer
def pre_save(self, obj):
obj.requesters_address = self.request.META['HTTP_X_FORWARDED_FOR']
class PortViewSet(viewsets.ModelViewSet):
queryset = MatchPort.objects.all()
......
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