Statistics
| Branch: | Tag: | Revision:

root / flowspec / models.py @ c1509909

History | View | Annotate | Download (12.7 kB)

1
# -*- coding: utf-8 -*- vim:encoding=utf-8:
2
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
3

    
4
from django.db import models
5
from django.conf import settings
6
from django.contrib.auth.models import User
7
from utils import proxy as PR
8
from ipaddr import *
9
import datetime
10
import logging
11
from flowspec.tasks import *
12
from time import sleep
13

    
14
from flowspy.utils import beanstalkc
15
from flowspy.utils.randomizer import id_generator as id_gen
16

    
17

    
18
FORMAT = '%(asctime)s %(levelname)s: %(message)s'
19
logging.basicConfig(format=FORMAT)
20
logger = logging.getLogger(__name__)
21
logger.setLevel(logging.DEBUG)
22

    
23

    
24
FRAGMENT_CODES = (
25
    ("dont-fragment", "Don't fragment"),
26
    ("first-fragment", "First fragment"),
27
    ("is-fragment", "Is fragment"),
28
    ("last-fragment", "Last fragment"),
29
    ("not-a-fragment", "Not a fragment")
30
)
31

    
32
THEN_CHOICES = (
33
    ("accept", "Accept"),
34
    ("discard", "Discard"),
35
    ("community", "Community"),
36
    ("next-term", "Next term"),
37
    ("routing-instance", "Routing Instance"),
38
    ("rate-limit", "Rate limit"),
39
    ("sample", "Sample")                
40
)
41

    
42
ROUTE_STATES = (
43
    ("ACTIVE", "ACTIVE"),
44
    ("ERROR", "ERROR"),
45
    ("EXPIRED", "EXPIRED"),
46
    ("PENDING", "PENDING"),
47
    ("OUTOFSYNC", "OUTOFSYNC"),
48
    ("INACTIVE", "INACTIVE"),            
49
)
50

    
51

    
52
def days_offset(): return datetime.date.today() + datetime.timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
53
    
54
class MatchPort(models.Model):
55
    port = models.CharField(max_length=24, unique=True)
56
    def __unicode__(self):
57
        return self.port
58
    class Meta:
59
        db_table = u'match_port'    
60

    
61
class MatchDscp(models.Model):
62
    dscp = models.CharField(max_length=24)
63
    def __unicode__(self):
64
        return self.dscp
65
    class Meta:
66
        db_table = u'match_dscp'
67

    
68
   
69
class ThenAction(models.Model):
70
    action = models.CharField(max_length=60, choices=THEN_CHOICES, verbose_name="Action")
71
    action_value = models.CharField(max_length=255, blank=True, null=True, verbose_name="Action Value")
72
    def __unicode__(self):
73
        ret = "%s:%s" %(self.action, self.action_value)
74
        return ret.rstrip(":")
75
    class Meta:
76
        db_table = u'then_action'
77

    
78
class Route(models.Model):
79
    name = models.SlugField(max_length=128)
80
    applier = models.ForeignKey(User, blank=True, null=True)
81
    source = models.CharField(max_length=32, blank=True, null=True, help_text=u"Network address. Use address/CIDR notation", verbose_name="Source Address")
82
    sourceport = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchSourcePort", verbose_name="Source Port")
83
    destination = models.CharField(max_length=32, help_text=u"Network address. Use address/CIDR notation", verbose_name="Destination Address")
84
    destinationport = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchDestinationPort", verbose_name="Destination Port")
85
    port = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchPort", verbose_name="Port" )
86
    dscp = models.ManyToManyField(MatchDscp, blank=True, null=True, verbose_name="DSCP")
87
    fragmenttype = models.CharField(max_length=20, choices=FRAGMENT_CODES, blank=True, null=True, verbose_name="Fragment Type")
88
    icmpcode = models.CharField(max_length=32, blank=True, null=True, verbose_name="ICMP Code")
89
    icmptype = models.CharField(max_length=32, blank=True, null=True, verbose_name="ICMP Type")
90
    packetlength = models.IntegerField(blank=True, null=True, verbose_name="Packet Length")
91
    protocol = models.CharField(max_length=32, blank=True, null=True, verbose_name="Protocol")
92
    tcpflag = models.CharField(max_length=128, blank=True, null=True, verbose_name="TCP flag")
93
    then = models.ManyToManyField(ThenAction, verbose_name="Then")
94
    filed = models.DateTimeField(auto_now_add=True)
95
    last_updated = models.DateTimeField(auto_now=True)
96
    status = models.CharField(max_length=20, choices=ROUTE_STATES, blank=True, null=True, verbose_name="Status", default="PENDING")
97
#    is_online = models.BooleanField(default=False)
98
#    is_active = models.BooleanField(default=False)
99
    expires = models.DateField(default=days_offset, blank=True, null=True,)
100
    response = models.CharField(max_length=512, blank=True, null=True)
101
    comments = models.TextField(null=True, blank=True, verbose_name="Comments")
102

    
103
    
104
    def __unicode__(self):
105
        return self.name
106
    
107
    class Meta:
108
        db_table = u'route'
109
    
110
    def save(self, *args, **kwargs):
111
        if not self.pk:
112
            hash = id_gen()
113
            self.name = "%s_%s" %(self.name, hash)
114
        super(Route, self).save(*args, **kwargs) # Call the "real" save() method.
115

    
116
        
117
    def clean(self, *args, **kwargs):
118
        from django.core.exceptions import ValidationError
119
        if self.destination:
120
            try:
121
                address = IPNetwork(self.destination)
122
                self.destination = address.exploded
123
            except Exception:
124
                raise ValidationError('Invalid network address format at Destination Field')
125
        if self.source:
126
            try:
127
                address = IPNetwork(self.source)
128
                self.source = address.exploded
129
            except Exception:
130
                raise ValidationError('Invalid network address format at Source Field')
131
    
132
#    def save(self, *args, **kwargs):
133
#        edit = False
134
#        if self.pk:
135
#            #This is an edit
136
#            edit = True
137
#        super(Route, self).save(*args, **kwargs)
138
#        if not edit:
139
#            response = add.delay(self)
140
#            logger.info("Got save job id: %s" %response)
141
    
142
    def commit_add(self, *args, **kwargs):
143
        peer = self.applier.get_profile().peer.domain_name
144
        send_message("[%s] Adding route %s. Please wait..." %(self.applier.username, self.name), peer)
145
        response = add.delay(self)
146
        logger.info("Got save job id: %s" %response)
147

    
148
    def deactivate(self):
149
        self.status = "INACTIVE"
150
        self.save()
151
#    def delete(self, *args, **kwargs):
152
#        response = delete.delay(self)
153
#        logger.info("Got delete job id: %s" %response)
154
        
155
    def commit_edit(self, *args, **kwargs):
156
        peer = self.applier.get_profile().peer.domain_name
157
        send_message("[%s] Editing route %s. Please wait..." %(self.applier.username, self.name), peer)
158
        response = edit.delay(self)
159
        logger.info("Got edit job id: %s" %response)
160

    
161
    def commit_delete(self, *args, **kwargs):
162
        peer = self.applier.get_profile().peer.domain_name
163
        send_message("[%s] Removing route %s. Please wait..." %(self.applier.username, self.name), peer)
164
        response = delete.delay(self)
165
        logger.info("Got edit job id: %s" %response)
166
#    
167
#    def delete(self, *args, **kwargs):
168
#        response = delete.delay(self)
169
#        logger.info("Got delete job id: %s" %response)
170
    def has_expired(self):
171
        today = datetime.date.today()
172
        if today > self.expires:
173
            return True
174
        return False
175

    
176
    def is_synced(self):      
177
        found = False
178
        get_device = PR.Retriever()
179
        device = get_device.fetch_device()
180
        try:
181
            routes = device.routing_options[0].routes
182
        except Exception as e:
183
            self.status = "EXPIRED"
184
            self.save()
185
            logger.error("No routing options on device. Exception: %s" %e)
186
            return False
187
        for route in routes:
188
            if route.name == self.name:
189
                found = True
190
                logger.info('Found a matching route name')
191
                devicematch = route.match
192
                try:
193
                    assert(self.destination)
194
                    assert(devicematch['destination'][0])
195
                    if self.destination == devicematch['destination'][0]:
196
                        found = found and True
197
                        logger.info('Found a matching destination')
198
                    else:
199
                        found = False
200
                        logger.info('Destination fields do not match')
201
                except:
202
                    pass
203
                try:
204
                    assert(self.source)
205
                    assert(devicematch['source'][0])
206
                    if self.source == devicematch['source'][0]:
207
                        found = found and True
208
                        logger.info('Found a matching source')
209
                    else:
210
                        found = False
211
                        logger.info('Source fields do not match')
212
                except:
213
                    pass
214
                try:
215
                    assert(self.fragmenttype)
216
                    assert(devicematch['fragment'][0])
217
                    if self.fragmenttype == devicematch['fragment'][0]:
218
                        found = found and True
219
                        logger.info('Found a matching fragment type')
220
                    else:
221
                        found = False
222
                        logger.info('Fragment type fields do not match')
223
                except:
224
                    pass
225
                try:
226
                    assert(self.icmpcode)
227
                    assert(devicematch['icmp-code'][0])
228
                    if self.icmpcode == devicematch['icmp-code'][0]:
229
                        found = found and True
230
                        logger.info('Found a matching icmp code')
231
                    else:
232
                        found = False
233
                        logger.info('Icmp code fields do not match')
234
                except:
235
                    pass
236
                try:
237
                    assert(self.icmptype)
238
                    assert(devicematch['icmp-type'][0])
239
                    if self.icmptype == devicematch['icmp-type'][0]:
240
                        found = found and True
241
                        logger.info('Found a matching icmp type')
242
                    else:
243
                        found = False
244
                        logger.info('Icmp type fields do not match')
245
                except:
246
                    pass
247
                try:
248
                    assert(self.protocol)
249
                    assert(devicematch['protocol'][0])
250
                    if self.protocol == devicematch['protocol'][0]:
251
                        found = found and True
252
                        logger.info('Found a matching protocol')
253
                    else:
254
                        found = False
255
                        logger.info('Protocol fields do not match')
256
                except:
257
                    pass
258
                if found and self.status != "ACTIVE":
259
                     logger.error('Rule is applied on device but appears as offline')
260
                     found = False
261
        
262
        return found
263

    
264
    def get_then(self):
265
        ret = ''
266
        then_statements = self.then.all()
267
        for statement in then_statements:
268
            if statement.action_value:
269
                ret = "%s %s:<strong>%s</strong><br/>" %(ret, statement.action, statement.action_value)
270
            else: 
271
                ret = "%s %s<br>" %(ret, statement.action)
272
        return ret.rstrip(',')
273
    
274
    get_then.short_description = 'Then statement'
275
    get_then.allow_tags = True
276
#
277
    def get_match(self):
278
        ret = ''
279
        if self.destination:
280
            ret = '%s Dst Addr:<strong>%s</strong><br/>' %(ret, self.destination)
281
        if self.fragmenttype:
282
            ret = "%s Fragment Type:<strong>%s</strong><br/>" %(ret, self.fragmenttype)
283
        if self.icmpcode:
284
            ret = "%s ICMP code:<strong>%s</strong><br/>" %(ret, self.icmpcode)
285
        if self.icmptype:
286
            ret = "%s ICMP Type:<strong>%s</strong><br/>" %(ret, self.icmptype)
287
        if self.packetlength:
288
            ret = "%s Packet Length:<strong>%s</strong><br/>" %(ret, self.packetlength)
289
        if self.protocol:
290
            ret = "%s Protocol:<strong>%s</strong><br/>" %(ret, self.protocol)
291
        if self.source:
292
            ret = "%s Src Addr:<strong>%s</strong><br/>" %(ret, self.source)
293
        if self.tcpflag:
294
            ret = "%s TCP flag:<strong>%s</strong><br/>" %(ret, self.tcpflag)
295
        if self.port:
296
            for port in self.port.all():
297
                    ret = ret + "Port:<strong>%s</strong><br/>" %(port)
298
        if self.destinationport:
299
            for port in self.destinationport.all():
300
                    ret = ret + "Dst Port:<strong>%s</strong><br/>" %(port)
301
        if self.sourceport:
302
            for port in self.sourceport.all():
303
                    ret = ret +"Src Port:<strong>%s</strong><br/>" %(port)
304
        if self.dscp:
305
            for dscp in self.dscp.all():
306
                    ret = ret + "%s Port:<strong>%s</strong><br/>" %(ret, dscp)
307
        return ret.rstrip('<br/>')
308
        
309
    get_match.short_description = 'Match statement'
310
    get_match.allow_tags = True
311

    
312
def send_message(msg, user):
313
#    username = user.username
314
    peer = user
315
    b = beanstalkc.Connection()
316
    b.use(settings.POLLS_TUBE)
317
    tube_message = json.dumps({'message': str(msg), 'username':peer})
318
    b.put(tube_message)
319
    b.close()