Commit a49defdf authored by Kroustouris Stavros's avatar Kroustouris Stavros

Merge pull request #1 from skatsaounis/master

A user can belong to more than one peers
parents 7ed6dcd0 1941b846
......@@ -87,6 +87,16 @@ And here is a PUT request example:
curl -X PUT -F "name=Example" -F "comments=Description" -F "source=0.0.0.0/0" -F "sourceport=https://fod.example.com/api/ports/7/" -F "destination=83.212.9.93" https://fod.example.com/api/routes/12/ -H 'Authorization: Token <Your users token>'
##Limitations##
A user can belong to more than one peer, without any limitation. This fact may
produce some limitations though, to FoD application. FoD uses polling for updating
dashboard and let users know about other users' actions, who belong to the same
peer. In order to fetch updates from all user's peers, FoD makes ajax calls for
any one of them. It is recommended not to add more than 5 peers to any user,
because it may cause malfunction to FoD application.
##Contact##
You can find more about FoD or raise your issues at GRNET FoD
......
......@@ -28,8 +28,15 @@ from accounts.models import UserProfile
class UserPrAdmin(admin.ModelAdmin):
search_fields = ['user__username', 'peer__peer_name']
list_display = ('user', 'peer')
search_fields = ['user__username']
list_display = ('username', 'get_userprofile_peers')
def get_userprofile_peers(self, instance):
# instance is User instance
peers = instance.peers.all()
return ''.join(('%s, ' % (peer.peer_name)) for peer in peers)[:-2]
get_userprofile_peers.short_description = "User Peer(s)"
admin.site.register(UserProfile, UserPrAdmin)
......
# encoding: 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 M2M table for field peers on 'UserProfile'
db.create_table('accounts_userprofile_peers', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('userprofile', models.ForeignKey(orm['accounts.userprofile'], null=False)),
('peer', models.ForeignKey(orm['peers.peer'], null=False))
))
db.create_unique('accounts_userprofile_peers', ['userprofile_id', 'peer_id'])
def backwards(self, orm):
# Removing M2M table for field peers on 'UserProfile'
db.delete_table('accounts_userprofile_peers')
models = {
'accounts.userprofile': {
'Meta': {'object_name': 'UserProfile'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'peer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['peers.Peer']"}),
'peers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'peer_info'", 'symmetrical': 'False', 'to': "orm['peers.Peer']"}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'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': {'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(2015, 9, 28, 11, 12, 34, 315403)'}),
'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', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2015, 9, 28, 11, 12, 34, 315358)'}),
'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': {'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'})
},
'peers.peer': {
'Meta': {'object_name': 'Peer', 'db_table': "u'peer'"},
'domain_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'networks': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['peers.PeerRange']", 'null': 'True', 'blank': 'True'}),
'peer_as': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'peer_id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'peer_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'peer_tag': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'techc_emails': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['peers.TechcEmail']", 'null': 'True', 'blank': 'True'})
},
'peers.peerrange': {
'Meta': {'object_name': 'PeerRange', 'db_table': "u'peer_range'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'network': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'peers.techcemail': {
'Meta': {'object_name': 'TechcEmail', 'db_table': "'techc_email'"},
'email': ('django.db.models.fields.CharField', [], {'max_length': '352', 'db_column': "'email'"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['accounts']
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
for user in orm.UserProfile.objects.all():
user.peers.add(user.peer)
user.save()
def backwards(self, orm):
pass
models = {
'accounts.userprofile': {
'Meta': {'object_name': 'UserProfile'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'peer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['peers.Peer']"}),
'peers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'peer_info'", 'symmetrical': 'False', 'to': "orm['peers.Peer']"}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'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': {'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(2015, 9, 28, 11, 16, 39, 453057)'}),
'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', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2015, 9, 28, 11, 16, 39, 453010)'}),
'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': {'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'})
},
'peers.peer': {
'Meta': {'object_name': 'Peer', 'db_table': "u'peer'"},
'domain_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'networks': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['peers.PeerRange']", 'null': 'True', 'blank': 'True'}),
'peer_as': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'peer_id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'peer_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'peer_tag': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'techc_emails': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['peers.TechcEmail']", 'null': 'True', 'blank': 'True'})
},
'peers.peerrange': {
'Meta': {'object_name': 'PeerRange', 'db_table': "u'peer_range'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'network': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'peers.techcemail': {
'Meta': {'object_name': 'TechcEmail', 'db_table': "'techc_email'"},
'email': ('django.db.models.fields.CharField', [], {'max_length': '352', 'db_column': "'email'"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['accounts']
......@@ -25,14 +25,18 @@ from peers.models import Peer
class UserProfile(models.Model):
user = models.OneToOneField(User)
peer = models.ForeignKey(Peer)
peers = models.ManyToManyField(Peer, related_name='user_profile')
class Meta:
permissions = (
("overview", "Can see registered users and rules"),
)
def username(self):
return "%s" % (self.user.username)
def __unicode__(self):
return "%s:%s" % (self.user.username, self.peer.peer_name)
return self.username()
def get_address_space(self):
networks = self.domain.networks.all()
......
......@@ -51,7 +51,7 @@ class RouteAdmin(admin.ModelAdmin):
def has_delete_permission(self, request, obj=None):
return False
list_display = ('name', 'status', 'applier', 'applier_peer', 'get_match', 'get_then', 'response', "expires", "comments")
list_display = ('name', 'status', 'applier_username', 'applier_peers', 'get_match', 'get_then', 'response', "expires", "comments")
fieldsets = [
(None, {'fields': ['name', 'applier']}),
......@@ -73,7 +73,7 @@ class UserProfileAdmin(UserAdmin):
add_form = UserCreationForm
form = UserChangeForm
actions = ['deactivate', 'activate']
list_display = ('username', 'email', 'first_name' , 'last_name', 'is_staff', 'is_active', 'is_superuser', 'get_userprofile_peer')
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'get_userprofile_peers')
inlines = [UserProfileInline]
def deactivate(self, request, queryset):
......@@ -84,10 +84,12 @@ class UserProfileAdmin(UserAdmin):
queryset = queryset.update(is_active=True)
activate.short_description = "Activate Selected Users"
def get_userprofile_peer(self, instance):
def get_userprofile_peers(self, instance):
# instance is User instance
return instance.get_profile().peer
get_userprofile_peer.short_description = "User Peer"
peers = instance.get_profile().peers.all()
return ''.join(('%s, ' % (peer.peer_name)) for peer in peers)[:-2]
get_userprofile_peers.short_description = "User Peer(s)"
# fields = ('name', 'applier', 'expires')
#def formfield_for_dbfield(self, db_field, **kwargs):
......
......@@ -59,7 +59,8 @@ class RouteForm(forms.ModelForm):
def clean_source(self):
user = User.objects.get(pk=self.data['applier'])
peer = user.get_profile().peer
peers = user.get_profile().peers.all()
peers_names = ''.join(('%s, ' % (peer.peer_name)) for peer in peers)[:-2]
data = self.cleaned_data['source']
private_error = False
protected_error = False
......@@ -71,7 +72,7 @@ class RouteForm(forms.ModelForm):
for net in settings.PROTECTED_SUBNETS:
if address in IPNetwork(net):
protected_error = True
mail_body = "User %s %s (%s) attempted to set %s as the source address in a firewall rule" %(user.username, user.email, peer.peer_name, data)
mail_body = "User %s %s (%s) attempted to set %s as the source address in a firewall rule" % (user.username, user.email, peers_names, data)
send_mail(settings.EMAIL_SUBJECT_PREFIX + "Caught an attempt to set a protected IP/network as a source address",
mail_body, settings.SERVER_EMAIL,
settings.NOTIFY_ADMIN_MAILS, fail_silently=True)
......@@ -101,7 +102,8 @@ class RouteForm(forms.ModelForm):
def clean_destination(self):
user = User.objects.get(pk=self.data['applier'])
peer = user.get_profile().peer
peers = user.get_profile().peers.all()
peers_names = ''.join(('%s, ' % (peer.peer_name)) for peer in peers)[:-2]
data = self.cleaned_data['destination']
error = None
protected_error = False
......@@ -113,13 +115,13 @@ class RouteForm(forms.ModelForm):
for net in settings.PROTECTED_SUBNETS:
if address in IPNetwork(net):
protected_error = True
mail_body = "User %s %s (%s) attempted to set %s as the destination address in a firewall rule" %(user.username, user.email, peer.peer_name, data)
mail_body = "User %s %s (%s) attempted to set %s as the destination address in a firewall rule" % (user.username, user.email, peers_names, data)
send_mail(settings.EMAIL_SUBJECT_PREFIX + "Caught an attempt to set a protected IP/network as the destination address",
mail_body, settings.SERVER_EMAIL,
settings.NOTIFY_ADMIN_MAILS, fail_silently=True)
raise Exception
if address.prefixlen < settings.PREFIX_LENGTH:
error = _("Currently no prefix lengths < %s are allowed") %settings.PREFIX_LENGTH
error = _("Currently no prefix lengths < %s are allowed") % settings.PREFIX_LENGTH
raise Exception
if address.version == 4 and int(address.prefixlen) == 32:
if int(address.network.compressed.split('.')[-1]) == 0:
......@@ -152,7 +154,7 @@ class RouteForm(forms.ModelForm):
def clean(self):
if self.errors:
raise forms.ValidationError(_('Errors in form. Please review and fix them: %s'%", ".join(self.errors)))
raise forms.ValidationError(_('Errors in form. Please review and fix them: %s' % ", ".join(self.errors)))
name = self.cleaned_data.get('name', None)
source = self.cleaned_data.get('source', None)
sourceports = self.cleaned_data.get('sourceport', None)
......@@ -163,8 +165,10 @@ class RouteForm(forms.ModelForm):
protocols = self.cleaned_data.get('protocol', None)
user = self.cleaned_data.get('applier', None)
issuperuser = self.data.get('issuperuser')
peer = user.get_profile().peer
networks = peer.networks.all()
peers = user.get_profile().peers.all()
networks = []
for peer in peers:
networks.extend(peer.networks.all())
if issuperuser:
networks = PeerRange.objects.filter(peer__in=Peer.objects.all()).distinct()
mynetwork = False
......@@ -187,9 +191,9 @@ class RouteForm(forms.ModelForm):
if not (source or sourceports or ports or destination or destinationports):
raise forms.ValidationError(_('Fill at least a Rule Match Condition'))
if not user.is_superuser and then[0].action not in settings.UI_USER_THEN_ACTIONS:
raise forms.ValidationError(_('This action "%s" is not permitted') %(then[0].action))
raise forms.ValidationError(_('This action "%s" is not permitted') % (then[0].action))
existing_routes = Route.objects.all()
existing_routes = existing_routes.filter(applier__userprofile__peer=peer)
existing_routes = existing_routes.filter(applier__userprofile__peer__in=peers)
if source:
source = IPNetwork(source).compressed
existing_routes = existing_routes.filter(source=source)
......@@ -225,7 +229,7 @@ class RouteForm(forms.ModelForm):
if name != route.name:
existing_url = reverse('edit-route', args=[route.name])
if IPNetwork(destination) in IPNetwork(route.destination) or IPNetwork(route.destination) in IPNetwork(destination):
raise forms.ValidationError('Found an exact %s rule, %s with destination prefix %s<br>To avoid overlapping try editing rule <a href=\'%s\'>%s</a>' %(route.status, route.name, route.destination, existing_url, route.name))
raise forms.ValidationError('Found an exact %s rule, %s with destination prefix %s<br>To avoid overlapping try editing rule <a href=\'%s\'>%s</a>' % (route.status, route.name, route.destination, existing_url, route.name))
return self.cleaned_data
......
......@@ -6,13 +6,15 @@ 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):
def get_peer_techc_mails(user, peer):
mail = []
additional_mail = []
techmails_list = []
user_mail = '%s' % user.email
user_mail = user_mail.split(';')
techmails = user.get_profile().peer.techc_emails.all()
techmails = []
if peer:
techmails = peer.techc_emails.all()
if techmails:
for techmail in techmails:
techmails_list.append(techmail.email)
......
......@@ -29,7 +29,6 @@ from utils import proxy as PR
from ipaddr import *
import datetime
import logging
from time import sleep
from junos import create_junos_name
......@@ -40,19 +39,6 @@ from utils.randomizer import id_generator as id_gen
from tasks import *
def user_unicode_patch(self):
peer = None
try:
peer = self.get_profile().peer.peer_tag
except:
pass
if peer:
return '%s.::.%s' % (self.username, peer)
return self.username
User.__unicode__ = user_unicode_patch
FORMAT = '%(asctime)s %(levelname)s: %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger(__name__)
......@@ -193,10 +179,9 @@ class Route(models.Model):
def save(self, *args, **kwargs):
if not self.pk:
hash = id_gen()
self.name = "%s_%s" %(self.name, hash)
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:
......@@ -213,7 +198,20 @@ class Route(models.Model):
raise ValidationError(_('Invalid network address format at Source Field'))
def commit_add(self, *args, **kwargs):
peer = self.applier.get_profile().peer.peer_tag
peers = self.applier.get_profile().peers.all()
username = None
for peer in peers:
if username:
break
for network in peer.networks.all():
net = IPNetwork(network)
if IPNetwork(self.destination) in net:
username = peer
break
if username:
peer = username.peer_tag
else:
peer = None
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)
......@@ -228,7 +226,8 @@ class Route(models.Model):
'route': self,
'address': self.requesters_address,
'action': 'creation',
'url': admin_url
'url': admin_url,
'peer': username
}
)
user_mail = '%s' % self.applier.email
......@@ -237,7 +236,7 @@ class Route(models.Model):
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)
get_peer_techc_mails(self.applier, username)
)
d = {
'clientip': '%s' % self.requesters_address,
......@@ -246,7 +245,20 @@ class Route(models.Model):
logger.info(mail_body, extra=d)
def commit_edit(self, *args, **kwargs):
peer = self.applier.get_profile().peer.peer_tag
peers = self.applier.get_profile().peers.all()
username = None
for peer in peers:
if username:
break
for network in peer.networks.all():
net = IPNetwork(network)
if IPNetwork(self.destination) in net:
username = peer
break
if username:
peer = username.peer_tag
else:
peer = None
send_message(
'[%s] Editing rule %s. Please wait...' %
(
......@@ -270,7 +282,8 @@ class Route(models.Model):
'route': self,
'address': self.requesters_address,
'action': 'edit',
'url': admin_url
'url': admin_url,
'peer': username
}
)
user_mail = '%s' % self.applier.email
......@@ -278,7 +291,7 @@ class Route(models.Model):
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)
get_peer_techc_mails(self.applier, username)
)
d = {
'clientip': self.requesters_address,
......@@ -287,12 +300,25 @@ class Route(models.Model):
logger.info(mail_body, extra=d)
def commit_delete(self, *args, **kwargs):
username = None
reason_text = ''
reason = ''
if "reason" in kwargs:
reason = kwargs['reason']
reason_text = 'Reason: %s.' % reason
peer = self.applier.get_profile().peer.peer_tag
peers = self.applier.get_profile().peers.all()
for peer in peers:
if username:
break
for network in peer.networks.all():
net = IPNetwork(network)
if IPNetwork(self.destination) in net:
username = peer
break
if username:
peer = username.peer_tag
else:
peer = None
send_message(
'[%s] Suspending rule %s. %sPlease wait...' % (
self.applier.username,
......@@ -316,7 +342,8 @@ class Route(models.Model):
'route': self,
'address': self.requesters_address,
'action': 'removal',
'url': admin_url
'url': admin_url,
'peer': username
}
)
user_mail = '%s' % self.applier.email
......@@ -326,7 +353,7 @@ class Route(models.Model):
mail_body,
settings.SERVER_EMAIL,
user_mail,
get_peer_techc_mails(self.applier)
get_peer_techc_mails(self.applier, username)
)
d = {
'clientip': self.requesters_address,
......@@ -560,12 +587,13 @@ class Route(models.Model):
get_match.allow_tags = True
@property
def applier_peer(self):
def applier_peers(self):
try:
applier_peer = self.applier.get_profile().peer
peers = self.applier.get_profile().peers.all()
applier_peers = ''.join(('%s, ' % (peer.peer_name)) for peer in peers)[:-2]
except:
applier_peer = None
return applier_peer
applier_peers = None
return applier_peers
@property
def days_to_expire(self):
......@@ -591,6 +619,6 @@ def send_message(msg, user):
peer = user
b = beanstalkc.Connection()
b.use(settings.POLLS_TUBE)
tube_message = json.dumps({'message': str(msg), 'username':peer})
tube_message = json.dumps({'message': str(msg), 'username': peer})
b.put(tube_message)
b.close()
......@@ -30,6 +30,7 @@ from django.core.mail import send_mail
from django.template.loader import render_to_string
import os
from celery.exceptions import TimeLimitExceeded, SoftTimeLimitExceeded
from ipaddr import *
LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log')
......@@ -57,22 +58,22 @@ def add(route, callback=None):
route.status = status
route.response = response
route.save()
announce("[%s] Rule add: %s - Result: %s" %(route.applier, route.name, response), route.applier)
announce("[%s] Rule add: %s - Result: %s" % (route.applier, route.name, response), route.applier, route)
except TimeLimitExceeded:
route.status = "ERROR"
route.response = "Task timeout"
route.save()
announce("[%s] Rule add: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Rule add: %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
except SoftTimeLimitExceeded:
route.status = "ERROR"
route.response = "Task timeout"
route.save()
announce("[%s] Rule add: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Rule add: %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
except Exception:
route.status = "ERROR"
route.response = "Error"
route.save()
announce("[%s] Rule add: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Rule add: %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
@task(ignore_result=True)
......@@ -87,22 +88,22 @@ def edit(route, callback=None):
route.status = status
route.response = response
route.save()
announce("[%s] Rule edit: %s - Result: %s"%(route.applier, route.name, response), route.applier)
announce("[%s] Rule edit: %s - Result: %s" % (route.applier, route.name, response), route.applier, route)
except TimeLimitExceeded:
route.status = "ERROR"
route.response = "Task timeout"
route.save()
announce("[%s] Rule edit: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Rule edit: %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
except SoftTimeLimitExceeded:
route.status = "ERROR"
route.response = "Task timeout"
route.save()
announce("[%s] Rule edit: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Rule edit: %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
except Exception:
route.status = "ERROR"
route.response = "Error"
route.save()
announce("[%s] Rule edit: %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Rule edit: %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
@task(ignore_result=True)
......@@ -113,30 +114,30 @@ def delete(route, **kwargs):
reason_text = ''
if commit:
status = "INACTIVE"
if "reason" in kwargs and kwargs['reason']=='EXPIRED':
if "reason" in kwargs and kwargs['reason'] == 'EXPIRED':
status = 'EXPIRED'
reason_text = " Reason: %s " %status
reason_text = " Reason: %s " % status
else:
status = "ERROR"
route.status = status
route.response = response
route.save()
announce("[%s] Suspending rule : %s%s- Result %s" %(route.applier, route.name, reason_text, response), route.applier)
announce("[%s] Suspending rule : %s%s- Result %s" % (route.applier, route.name, reason_text, response), route.applier, route)
except TimeLimitExceeded:
route.status = "ERROR"
route.response = "Task timeout"
route.save()
announce("[%s] Suspending rule : %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Suspending rule : %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
except SoftTimeLimitExceeded:
route.status = "ERROR"
route.response = "Task timeout"
route.save()
announce("[%s] Suspending rule : %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Suspending rule : %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
except Exception:
route.status = "ERROR"
route.response = "Error"
route.save()
announce("[%s] Suspending rule : %s - Result: %s"%(route.applier, route.name, route.response), route.applier)
announce("[%s] Suspending rule : %s - Result: %s" % (route.applier, route.name, route.response), route.applier, route)
# May not work in the first place... proxy is not aware of Route models
......@@ -144,19 +145,19 @@ def delete(route, **kwargs):
def batch_delete(routes, **kwargs):
if routes:
for route in routes:
route.status='PENDING';route.save()
route.status = 'PENDING';route.save()
applier = PR.Applier(route_objects=routes)
conf = applier.delete_routes()
commit, response = applier.apply(configuration = conf)
commit, response = applier.apply(configuration=conf)
reason_text = ''
if commit:
status = "INACTIVE"
if "reason" in kwargs and kwargs['reason']=='EXPIRED':
if "reason" in kwargs and kwargs['reason'] == 'EXPIRED':
status = 'EXPIRED'
reason_text = " Reason: %s " %status
elif "reason" in kwargs and kwargs['reason']!='EXPIRED':
reason_text = " Reason: %s " % status
elif "reason" in kwargs and kwargs['reason'] != 'EXPIRED':
status = kwargs['reason']
reason_text = " Reason: %s " %status
reason_text = " Reason: %s " % status