Commit 2bfcba1c authored by stammy31's avatar stammy31

Apply change of ForeginKey peer to M2M relationship peers on UserProfile model...

Apply change of ForeginKey peer to M2M relationship peers on UserProfile model to whole project. Make use of model PeerNotify to notify peers on users actions.
parent d0501fe0
...@@ -59,7 +59,8 @@ class RouteForm(forms.ModelForm): ...@@ -59,7 +59,8 @@ class RouteForm(forms.ModelForm):
def clean_source(self): def clean_source(self):
user = User.objects.get(pk=self.data['applier']) 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'] data = self.cleaned_data['source']
private_error = False private_error = False
protected_error = False protected_error = False
...@@ -71,7 +72,7 @@ class RouteForm(forms.ModelForm): ...@@ -71,7 +72,7 @@ class RouteForm(forms.ModelForm):
for net in settings.PROTECTED_SUBNETS: for net in settings.PROTECTED_SUBNETS:
if address in IPNetwork(net): if address in IPNetwork(net):
protected_error = True 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", send_mail(settings.EMAIL_SUBJECT_PREFIX + "Caught an attempt to set a protected IP/network as a source address",
mail_body, settings.SERVER_EMAIL, mail_body, settings.SERVER_EMAIL,
settings.NOTIFY_ADMIN_MAILS, fail_silently=True) settings.NOTIFY_ADMIN_MAILS, fail_silently=True)
...@@ -101,7 +102,8 @@ class RouteForm(forms.ModelForm): ...@@ -101,7 +102,8 @@ class RouteForm(forms.ModelForm):
def clean_destination(self): def clean_destination(self):
user = User.objects.get(pk=self.data['applier']) 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'] data = self.cleaned_data['destination']
error = None error = None
protected_error = False protected_error = False
...@@ -113,13 +115,13 @@ class RouteForm(forms.ModelForm): ...@@ -113,13 +115,13 @@ class RouteForm(forms.ModelForm):
for net in settings.PROTECTED_SUBNETS: for net in settings.PROTECTED_SUBNETS:
if address in IPNetwork(net): if address in IPNetwork(net):
protected_error = True 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", send_mail(settings.EMAIL_SUBJECT_PREFIX + "Caught an attempt to set a protected IP/network as the destination address",
mail_body, settings.SERVER_EMAIL, mail_body, settings.SERVER_EMAIL,
settings.NOTIFY_ADMIN_MAILS, fail_silently=True) settings.NOTIFY_ADMIN_MAILS, fail_silently=True)
raise Exception raise Exception
if address.prefixlen < settings.PREFIX_LENGTH: 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 raise Exception
if address.version == 4 and int(address.prefixlen) == 32: if address.version == 4 and int(address.prefixlen) == 32:
if int(address.network.compressed.split('.')[-1]) == 0: if int(address.network.compressed.split('.')[-1]) == 0:
...@@ -152,7 +154,7 @@ class RouteForm(forms.ModelForm): ...@@ -152,7 +154,7 @@ class RouteForm(forms.ModelForm):
def clean(self): def clean(self):
if self.errors: 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) name = self.cleaned_data.get('name', None)
source = self.cleaned_data.get('source', None) source = self.cleaned_data.get('source', None)
sourceports = self.cleaned_data.get('sourceport', None) sourceports = self.cleaned_data.get('sourceport', None)
...@@ -163,8 +165,10 @@ class RouteForm(forms.ModelForm): ...@@ -163,8 +165,10 @@ class RouteForm(forms.ModelForm):
protocols = self.cleaned_data.get('protocol', None) protocols = self.cleaned_data.get('protocol', None)
user = self.cleaned_data.get('applier', None) user = self.cleaned_data.get('applier', None)
issuperuser = self.data.get('issuperuser') issuperuser = self.data.get('issuperuser')
peer = user.get_profile().peer peers = user.get_profile().peers.all()
networks = peer.networks.all() networks = []
for peer in peers:
networks.extend(peer.networks.all())
if issuperuser: if issuperuser:
networks = PeerRange.objects.filter(peer__in=Peer.objects.all()).distinct() networks = PeerRange.objects.filter(peer__in=Peer.objects.all()).distinct()
mynetwork = False mynetwork = False
...@@ -187,9 +191,9 @@ class RouteForm(forms.ModelForm): ...@@ -187,9 +191,9 @@ class RouteForm(forms.ModelForm):
if not (source or sourceports or ports or destination or destinationports): if not (source or sourceports or ports or destination or destinationports):
raise forms.ValidationError(_('Fill at least a Rule Match Condition')) 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: 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 = Route.objects.all()
existing_routes = existing_routes.filter(applier__userprofile__peer=peer) existing_routes = existing_routes.filter(applier__userprofile__peer__in=peers)
if source: if source:
source = IPNetwork(source).compressed source = IPNetwork(source).compressed
existing_routes = existing_routes.filter(source=source) existing_routes = existing_routes.filter(source=source)
...@@ -225,7 +229,7 @@ class RouteForm(forms.ModelForm): ...@@ -225,7 +229,7 @@ class RouteForm(forms.ModelForm):
if name != route.name: if name != route.name:
existing_url = reverse('edit-route', args=[route.name]) existing_url = reverse('edit-route', args=[route.name])
if IPNetwork(destination) in IPNetwork(route.destination) or IPNetwork(route.destination) in IPNetwork(destination): 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 return self.cleaned_data
......
...@@ -6,13 +6,15 @@ def send_new_mail(subject, message, from_email, recipient_list, bcc_list): ...@@ -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() 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 = [] mail = []
additional_mail = [] additional_mail = []
techmails_list = [] techmails_list = []
user_mail = '%s' % user.email user_mail = '%s' % user.email
user_mail = user_mail.split(';') user_mail = user_mail.split(';')
techmails = user.get_profile().peer.techc_emails.all() techmails = []
if peer:
techmails = peer.techc_emails.all()
if techmails: if techmails:
for techmail in techmails: for techmail in techmails:
techmails_list.append(techmail.email) techmails_list.append(techmail.email)
......
...@@ -29,7 +29,6 @@ from utils import proxy as PR ...@@ -29,7 +29,6 @@ from utils import proxy as PR
from ipaddr import * from ipaddr import *
import datetime import datetime
import logging import logging
from time import sleep
from junos import create_junos_name from junos import create_junos_name
...@@ -40,19 +39,6 @@ from utils.randomizer import id_generator as id_gen ...@@ -40,19 +39,6 @@ from utils.randomizer import id_generator as id_gen
from tasks import * 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' FORMAT = '%(asctime)s %(levelname)s: %(message)s'
logging.basicConfig(format=FORMAT) logging.basicConfig(format=FORMAT)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -193,10 +179,9 @@ class Route(models.Model): ...@@ -193,10 +179,9 @@ class Route(models.Model):
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if not self.pk: if not self.pk:
hash = id_gen() 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. super(Route, self).save(*args, **kwargs) # Call the "real" save() method.
def clean(self, *args, **kwargs): def clean(self, *args, **kwargs):
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
if self.destination: if self.destination:
...@@ -213,7 +198,20 @@ class Route(models.Model): ...@@ -213,7 +198,20 @@ class Route(models.Model):
raise ValidationError(_('Invalid network address format at Source Field')) raise ValidationError(_('Invalid network address format at Source Field'))
def commit_add(self, *args, **kwargs): 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) send_message("[%s] Adding rule %s. Please wait..." % (self.applier.username, self.name), peer)
response = add.delay(self) response = add.delay(self)
logger.info('Got add job id: %s' % response) logger.info('Got add job id: %s' % response)
...@@ -228,7 +226,8 @@ class Route(models.Model): ...@@ -228,7 +226,8 @@ class Route(models.Model):
'route': self, 'route': self,
'address': self.requesters_address, 'address': self.requesters_address,
'action': 'creation', 'action': 'creation',
'url': admin_url 'url': admin_url,
'peer': username
} }
) )
user_mail = '%s' % self.applier.email user_mail = '%s' % self.applier.email
...@@ -237,7 +236,7 @@ class Route(models.Model): ...@@ -237,7 +236,7 @@ class Route(models.Model):
settings.EMAIL_SUBJECT_PREFIX + 'Rule %s creation request submitted by %s' % (self.name, self.applier.username), settings.EMAIL_SUBJECT_PREFIX + 'Rule %s creation request submitted by %s' % (self.name, self.applier.username),
mail_body, mail_body,
settings.SERVER_EMAIL, user_mail, settings.SERVER_EMAIL, user_mail,
get_peer_techc_mails(self.applier) get_peer_techc_mails(self.applier, username)
) )
d = { d = {
'clientip': '%s' % self.requesters_address, 'clientip': '%s' % self.requesters_address,
...@@ -246,7 +245,20 @@ class Route(models.Model): ...@@ -246,7 +245,20 @@ class Route(models.Model):
logger.info(mail_body, extra=d) logger.info(mail_body, extra=d)
def commit_edit(self, *args, **kwargs): 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( send_message(
'[%s] Editing rule %s. Please wait...' % '[%s] Editing rule %s. Please wait...' %
( (
...@@ -270,7 +282,8 @@ class Route(models.Model): ...@@ -270,7 +282,8 @@ class Route(models.Model):
'route': self, 'route': self,
'address': self.requesters_address, 'address': self.requesters_address,
'action': 'edit', 'action': 'edit',
'url': admin_url 'url': admin_url,
'peer': username
} }
) )
user_mail = '%s' % self.applier.email user_mail = '%s' % self.applier.email
...@@ -278,7 +291,7 @@ class Route(models.Model): ...@@ -278,7 +291,7 @@ class Route(models.Model):
send_new_mail( send_new_mail(
settings.EMAIL_SUBJECT_PREFIX + 'Rule %s edit request submitted by %s' % (self.name, self.applier.username), settings.EMAIL_SUBJECT_PREFIX + 'Rule %s edit request submitted by %s' % (self.name, self.applier.username),
mail_body, settings.SERVER_EMAIL, user_mail, mail_body, settings.SERVER_EMAIL, user_mail,
get_peer_techc_mails(self.applier) get_peer_techc_mails(self.applier, username)
) )
d = { d = {
'clientip': self.requesters_address, 'clientip': self.requesters_address,
...@@ -287,12 +300,25 @@ class Route(models.Model): ...@@ -287,12 +300,25 @@ class Route(models.Model):
logger.info(mail_body, extra=d) logger.info(mail_body, extra=d)
def commit_delete(self, *args, **kwargs): def commit_delete(self, *args, **kwargs):
username = None
reason_text = '' reason_text = ''
reason = '' reason = ''
if "reason" in kwargs: if "reason" in kwargs:
reason = kwargs['reason'] reason = kwargs['reason']
reason_text = 'Reason: %s.' % 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( send_message(
'[%s] Suspending rule %s. %sPlease wait...' % ( '[%s] Suspending rule %s. %sPlease wait...' % (
self.applier.username, self.applier.username,
...@@ -316,7 +342,8 @@ class Route(models.Model): ...@@ -316,7 +342,8 @@ class Route(models.Model):
'route': self, 'route': self,
'address': self.requesters_address, 'address': self.requesters_address,
'action': 'removal', 'action': 'removal',
'url': admin_url 'url': admin_url,
'peer': username
} }
) )
user_mail = '%s' % self.applier.email user_mail = '%s' % self.applier.email
...@@ -326,7 +353,7 @@ class Route(models.Model): ...@@ -326,7 +353,7 @@ class Route(models.Model):
mail_body, mail_body,
settings.SERVER_EMAIL, settings.SERVER_EMAIL,
user_mail, user_mail,
get_peer_techc_mails(self.applier) get_peer_techc_mails(self.applier, username)
) )
d = { d = {
'clientip': self.requesters_address, 'clientip': self.requesters_address,
...@@ -560,12 +587,13 @@ class Route(models.Model): ...@@ -560,12 +587,13 @@ class Route(models.Model):
get_match.allow_tags = True get_match.allow_tags = True
@property @property
def applier_peer(self): def applier_peers(self):
try: 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: except:
applier_peer = None applier_peers = None
return applier_peer return applier_peers
@property @property
def days_to_expire(self): def days_to_expire(self):
...@@ -591,6 +619,6 @@ def send_message(msg, user): ...@@ -591,6 +619,6 @@ def send_message(msg, user):
peer = user peer = user
b = beanstalkc.Connection() b = beanstalkc.Connection()
b.use(settings.POLLS_TUBE) 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.put(tube_message)
b.close() b.close()
...@@ -30,6 +30,7 @@ from django.core.mail import send_mail ...@@ -30,6 +30,7 @@ from django.core.mail import send_mail
from django.template.loader import render_to_string from django.template.loader import render_to_string
import os import os
from celery.exceptions import TimeLimitExceeded, SoftTimeLimitExceeded from celery.exceptions import TimeLimitExceeded, SoftTimeLimitExceeded
from ipaddr import *
LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log') LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log')
...@@ -57,22 +58,22 @@ def add(route, callback=None): ...@@ -57,22 +58,22 @@ def add(route, callback=None):
route.status = status route.status = status
route.response = response route.response = response
route.save() 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: except TimeLimitExceeded:
route.status = "ERROR" route.status = "ERROR"
route.response = "Task timeout" route.response = "Task timeout"
route.save() 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: except SoftTimeLimitExceeded:
route.status = "ERROR" route.status = "ERROR"
route.response = "Task timeout" route.response = "Task timeout"
route.save() 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: except Exception:
route.status = "ERROR" route.status = "ERROR"
route.response = "Error" route.response = "Error"
route.save() 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) @task(ignore_result=True)
...@@ -87,22 +88,22 @@ def edit(route, callback=None): ...@@ -87,22 +88,22 @@ def edit(route, callback=None):
route.status = status route.status = status
route.response = response route.response = response
route.save() 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: except TimeLimitExceeded:
route.status = "ERROR" route.status = "ERROR"
route.response = "Task timeout" route.response = "Task timeout"
route.save() 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: except SoftTimeLimitExceeded:
route.status = "ERROR" route.status = "ERROR"
route.response = "Task timeout" route.response = "Task timeout"
route.save() 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: except Exception:
route.status = "ERROR" route.status = "ERROR"
route.response = "Error" route.response = "Error"
route.save() 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) @task(ignore_result=True)
...@@ -113,30 +114,30 @@ def delete(route, **kwargs): ...@@ -113,30 +114,30 @@ def delete(route, **kwargs):
reason_text = '' reason_text = ''
if commit: if commit:
status = "INACTIVE" status = "INACTIVE"
if "reason" in kwargs and kwargs['reason']=='EXPIRED': if "reason" in kwargs and kwargs['reason'] == 'EXPIRED':
status = 'EXPIRED' status = 'EXPIRED'
reason_text = " Reason: %s " %status reason_text = " Reason: %s " % status
else: else:
status = "ERROR" status = "ERROR"
route.status = status route.status = status
route.response = response route.response = response
route.save() 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: except TimeLimitExceeded:
route.status = "ERROR" route.status = "ERROR"
route.response = "Task timeout" route.response = "Task timeout"
route.save() 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: except SoftTimeLimitExceeded:
route.status = "ERROR" route.status = "ERROR"
route.response = "Task timeout" route.response = "Task timeout"
route.save() 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: except Exception:
route.status = "ERROR" route.status = "ERROR"
route.response = "Error" route.response = "Error"
route.save() 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 # May not work in the first place... proxy is not aware of Route models
...@@ -144,19 +145,19 @@ def delete(route, **kwargs): ...@@ -144,19 +145,19 @@ def delete(route, **kwargs):
def batch_delete(routes, **kwargs): def batch_delete(routes, **kwargs):
if routes: if routes:
for route in routes: for route in routes:
route.status='PENDING';route.save() route.status = 'PENDING';route.save()
applier = PR.Applier(route_objects=routes) applier = PR.Applier(route_objects=routes)
conf = applier.delete_routes() conf = applier.delete_routes()
commit, response = applier.apply(configuration = conf) commit, response = applier.apply(configuration=conf)
reason_text = '' reason_text = ''
if commit: if commit:
status = "INACTIVE" status = "INACTIVE"
if "reason" in kwargs and kwargs['reason']=='EXPIRED': if "reason" in kwargs and kwargs['reason'] == 'EXPIRED':
status = 'EXPIRED' status = 'EXPIRED'
reason_text = " Reason: %s " %status reason_text = " Reason: %s " % status
elif "reason" in kwargs and kwargs['reason']!='EXPIRED': elif "reason" in kwargs and kwargs['reason'] != 'EXPIRED':
status = kwargs['reason'] status = kwargs['reason']
reason_text = " Reason: %s " %status reason_text = " Reason: %s " % status
else: else:
status = "ERROR" status = "ERROR"
for route in routes: for route in routes:
...@@ -164,15 +165,24 @@ def batch_delete(routes, **kwargs): ...@@ -164,15 +165,24 @@ def batch_delete(routes, **kwargs):
route.response = response route.response = response
route.expires = datetime.date.today() route.expires = datetime.date.today()
route.save() route.save()
announce("[%s] Rule removal: %s%s- Result %s" % (route.applier, route.name, reason_text, response), route.applier) announce("[%s] Rule removal: %s%s- Result %s" % (route.applier, route.name, reason_text, response), route.applier, route)
else: else:
return False return False
#@task(ignore_result=True) #@task(ignore_result=True)
def announce(messg, user): def announce(messg, user, route):
peers = user.get_profile().peers.all()
username = None
for peer in peers:
if username:
break
for network in peer.networks.all():
net = IPNetwork(network)
if IPNetwork(route.destination) in net:
username = peer.peer_tag
break
messg = str(messg) messg = str(messg)
username = user.get_profile().peer.peer_tag
b = beanstalkc.Connection() b = beanstalkc.Connection()
b.use(settings.POLLS_TUBE) b.use(settings.POLLS_TUBE)
tube_message = json.dumps({'message': messg, 'username': username}) tube_message = json.dumps({'message': messg, 'username': username})
......
This diff is collapsed.
...@@ -21,6 +21,14 @@ from django.conf.urls.defaults import patterns, url ...@@ -21,6 +21,14 @@ from django.conf.urls.defaults import patterns, url
urlpatterns = patterns( urlpatterns = patterns(
'poller.views', 'poller.views',
('^$', 'main'), ('^$', 'main'),
url('^message/existing$', 'message_existing', name='fetch-existing'), url(
url('^message/updates$', 'message_updates', name='fetch-updates') '^message/existing/(?P<peer_id>[\w\-]+)/$',
'message_existing',
name='fetch-existing'
),
url(
'^message/updates/(?P<peer_id>[\w\-]+)/$',
'message_updates',
name='fetch-updates'
)
) )
...@@ -29,6 +29,7 @@ from gevent.event import Event ...@@ -29,6 +29,7 @@ from gevent.event import Event
from django.conf import settings from django.conf import settings
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from peers.models import Peer
import beanstalkc import beanstalkc
...@@ -79,10 +80,10 @@ class Msgs(object): ...@@ -79,10 +80,10 @@ class Msgs(object):
request.session['cursor'] = self.user_cache[-1]['id'] request.session['cursor'] = self.user_cache[-1]['id']
return render_to_response('poll.html', {'messages': self.user_cache}) return render_to_response('poll.html', {'messages': self.user_cache})
def message_existing(self, request): def message_existing(self, request, peer_id):
if request.is_ajax(): if request.is_ajax():
try: try:
user = request.user.get_profile().peer.peer_tag user = Peer.objects.get(pk=peer_id).peer_tag
except: except:
user = None user = None
return False return False
...@@ -125,11 +126,11 @@ class Msgs(object): ...@@ -125,11 +126,11 @@ class Msgs(object):
self.new_message_user_event[user].clear() self.new_message_user_event[user].clear()
return json_response(msg) return json_response(msg)
def message_updates(self, request): def message_updates(self, request, peer_id):
if request.is_ajax(): if request.is_ajax():
cursor = {} cursor = {}
try: try:
user = request.user.get_profile().peer.peer_tag user = Peer.objects.get(pk=peer_id).peer_tag
except: