models.py 19 KB
Newer Older
Dmitry Volodin's avatar
Dmitry Volodin committed
1
2
3
4
5
6
7
# -*- coding: utf-8 -*-
##----------------------------------------------------------------------
## Copyright (C) 2007-2009 The NOC Project
## See LICENSE for details
##----------------------------------------------------------------------
"""
"""
8
from django.db import models
Dmitry Volodin's avatar
Dmitry Volodin committed
9
10
from django.db.models import Q
from django.contrib.auth.models import User
11
import datetime,random,cPickle,time
12
from noc.sa.profiles import profile_registry
Dmitry Volodin's avatar
Dmitry Volodin committed
13
from noc.sa.periodic import periodic_registry
14
from noc.sa.scripts import reduce_script_registry
Dmitry Volodin's avatar
Dmitry Volodin committed
15
from noc.sa.script import script_registry
Dmitry Volodin's avatar
Dmitry Volodin committed
16
from noc.sa.protocols.sae_pb2 import TELNET,SSH,HTTP
Dmitry Volodin's avatar
Dmitry Volodin committed
17
from noc.main.menu import Menu
Dmitry Volodin's avatar
Dmitry Volodin committed
18
from noc.main.search import SearchResult
19
from noc.lib.fields import PickledField
20
21

profile_registry.register_all()
Dmitry Volodin's avatar
Dmitry Volodin committed
22
periodic_registry.register_all()
Dmitry Volodin's avatar
Dmitry Volodin committed
23
script_registry.register_all()
24
reduce_script_registry.register_all()
25
scheme_choices=[(TELNET,"telnet"),(SSH,"ssh"),(HTTP,"http")]
Dmitry Volodin's avatar
Dmitry Volodin committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
##
##
##
class AdministrativeDomain(models.Model):
    class Meta:
        verbose_name="Administrative Domain"
        verbose_name_plural="Administrative Domains"
    name=models.CharField("Name",max_length=32,unique=True)
    description=models.TextField("Description",null=True,blank=True)
    def __unicode__(self):
        return self.name
##
##
##
class ObjectGroup(models.Model):
    class Meta:
        verbose_name="Object Group"
        verbose_name_plural="Object Groups"
    name=models.CharField("Name",max_length=32,unique=True)
    description=models.TextField("Description",null=True,blank=True)
    def __unicode__(self):
        return self.name
##
##
##
Dmitry Volodin's avatar
Dmitry Volodin committed
51
52
53
54
55
class Activator(models.Model):
    class Meta:
        verbose_name="Activator"
        verbose_name_plural="Activators"
    name=models.CharField("Name",max_length=32,unique=True)
56
57
    ip=models.IPAddressField("From IP")
    to_ip=models.IPAddressField("To IP")
Dmitry Volodin's avatar
Dmitry Volodin committed
58
59
60
61
    auth=models.CharField("Auth String",max_length=64)
    is_active=models.BooleanField("Is Active",default=True)
    def __unicode__(self):
        return self.name
62
63
64
65
66
67
    ##
    ## Returns true if IP can belong to any activator
    ##
    @classmethod
    def check_ip_access(self,ip):
        return Activator.objects.filter(ip__gte=ip,to_ip__lte=ip).count()>0
Dmitry Volodin's avatar
Dmitry Volodin committed
68
69
70
71
72
73
74
75
76
##
##
##
class ManagedObject(models.Model):
    class Meta:
        verbose_name="Managed Object"
        verbose_name_plural="Managed Objects"
    name=models.CharField("Name",max_length=64,unique=True)
    is_managed=models.BooleanField("Is Managed?",default=True)
Dmitry Volodin's avatar
Dmitry Volodin committed
77
    administrative_domain=models.ForeignKey(AdministrativeDomain,verbose_name="Administrative Domain")
Dmitry Volodin's avatar
Dmitry Volodin committed
78
79
    activator=models.ForeignKey(Activator,verbose_name="Activator")
    profile_name=models.CharField("Profile",max_length=128,choices=profile_registry.choices)
80
    description=models.CharField("Description",max_length=256,null=True,blank=True)
Dmitry Volodin's avatar
Dmitry Volodin committed
81
    # Access
82
    scheme=models.IntegerField("Scheme",choices=scheme_choices)
Dmitry Volodin's avatar
Dmitry Volodin committed
83
84
85
86
87
88
89
90
    address=models.CharField("Address",max_length=64)
    port=models.PositiveIntegerField("Port",blank=True,null=True)
    user=models.CharField("User",max_length=32,blank=True,null=True)
    password=models.CharField("Password",max_length=32,blank=True,null=True)
    super_password=models.CharField("Super Password",max_length=32,blank=True,null=True)
    remote_path=models.CharField("Path",max_length=32,blank=True,null=True)
    trap_source_ip=models.IPAddressField("Trap Source IP",null=True)
    trap_community=models.CharField("Trap Community",blank=True,null=True,max_length=64)
91
92
    snmp_ro=models.CharField("RO Community",blank=True,null=True,max_length=64)
    snmp_rw=models.CharField("RW Community",blank=True,null=True,max_length=64)
Dmitry Volodin's avatar
Dmitry Volodin committed
93
94
95
96
97
98
99
100
    # CM
    is_configuration_managed=models.BooleanField("Is Configuration Managed?",default=True)
    repo_path=models.CharField("Repo Path",max_length=128,blank=True,null=True)
    #
    groups=models.ManyToManyField(ObjectGroup,verbose_name="Groups",null=True,blank=True)
    #
    def __unicode__(self):
        return self.name
101
102
103
104
105
106
107
108
    # Returns object's profile
    def _profile(self):
        try:
            return self._cached_profile
        except AttributeError:
            self._cached_profile=profile_registry[self.profile_name]()
            return self._cached_profile
    profile=property(_profile)
109
        
Dmitry Volodin's avatar
Dmitry Volodin committed
110
111
112
113
114
115
116
117
118
119
120
121
    def config_link(self):
        try:
            return "<A HREF='/cm/view/config/%d/'>Config</A>"%(self.config.id)
        except:
            return ""
    config_link.short_description="Config"
    config_link.allow_tags=True
    
    def scripts_link(self):
        return "<A HREF='/sa/%d/scripts/'>Scripts</A>"%(self.id)
    scripts_link.short_description="Scripts"
    scripts_link.allow_tags=True
122
123
124
125
126
127
128
129
130
131
132
    
    def action_links(self):
        try:
            l="<A HREF='/cm/view/config/%d/'>Config</A>"%(self.config.id)
        except:
            l=""
        l+="<br/><A HREF='/sa/%d/scripts/'>Scripts</A>"%(self.id)
        return l
    action_links.short_description="Actions"
    action_links.allow_tags=True
        
Dmitry Volodin's avatar
Dmitry Volodin committed
133
134
135
136
137
138
139
140
141
142
    ##
    ## Access control
    ##
    def has_access(self,user):
        if user.is_superuser:
            return True
        return user.useraccess_set.filter(
                    (Q(administrative_domain__isnull=True)|Q(administrative_domain=self.administrative_domain))\
                    &(Q(group__isnull=True)|Q(group__in=self.groups.all))
                    ).count()>0
Dmitry Volodin's avatar
Dmitry Volodin committed
143

Dmitry Volodin's avatar
Dmitry Volodin committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    def can_change(self,user,administrative_domain,groups):
        if user.is_superuser:
            return True
        if user.useraccess_set.filter(
                (Q(administrative_domain__isnull=True)|Q(administrative_domain=self.administrative_domain))\
                &Q(group__isnull=True)
                ).count()>0:
            return True
        if groups:
            for g in groups:
                if user.useraccess_set.filter(
                        (Q(administrative_domain__isnull=True)|Q(administrative_domain__isnull=self.administrative_domain))\
                        &Q(group=g)
                        ).count()==0:
                    return False
            return True
        return False
        
    @classmethod
    def queryset(cls,user):
Dmitry Volodin's avatar
Dmitry Volodin committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
        if user.is_superuser:
            return cls.objects.all()
        # Build query
        r=[]
        p=[]
        for a in user.useraccess_set.all():
            if a.administrative_domain is None and a.group is None: # Full access
                return cls.objects.all()
            rr=[]
            pp=[]
            if a.administrative_domain:
                rr.append("(sa_managedobject.administrative_domain_id=%s)")
                pp.append(a.administrative_domain.id)
            if a.group:
Dmitry Volodin's avatar
Dmitry Volodin committed
178
                rr.append("(sa_managedobject.id IN (SELECT managedobject_id FROM sa_managedobject_groups WHERE objectgroup_id=%s))")
Dmitry Volodin's avatar
Dmitry Volodin committed
179
180
181
182
183
184
185
186
187
188
                pp.append(a.group.id)
            if len(rr)==1: # Single clause
                r+=rr
            else: # AND together
                r+=["(%s AND %s)"%(r[0],r[1])]
            p+=pp
        if not r: # No access
            return cls.objects.extra(where=["0=1"]) # Return empty queryset
        where=" OR ".join(r)
        return cls.objects.extra(where=[where],params=p)
189
190
191
192
    ##
    ## Override model's save()
    ## Change related Config object as well
    ##
Dmitry Volodin's avatar
Dmitry Volodin committed
193
194
195
    def save(self):
        super(ManagedObject,self).save()
        try:
196
            config=self.config # self.config is OneToOne field created by Config
Dmitry Volodin's avatar
Dmitry Volodin committed
197
198
        except:
            config=None
199
200
201
202
203
204
205
206
207
208
209
210
        if config is None: # No related Config object
            if self.is_configuration_managed: # Object is configuration managed, create related object
                from noc.cm.models import Config
                config=Config(managed_object=self,repo_path=self.repo_path,pull_every=86400)
                config.save()
        else: # Update existing config entry when necessary
            if self.repo_path!=self.config.repo_path: # Repo path changed
                config.repo_path=self.repo_path
            if self.is_configuration_managed and config.pull_every is None: # Device is configuration managed but not on periodic pull
                config.pull_every=86400
            elif not self.is_configuration_managed and config.pull_every: # Reset pull_every for unmanaged devices
                config.pull_every=None
Dmitry Volodin's avatar
Dmitry Volodin committed
211
212
213
214
215
216
217
218
219
220
            config.save()
    
    def delete(self):
        try:
            config=self.config
        except:
            config=None
        if config:
            config.delete()
        super(ManagedObject,self).delete()
Dmitry Volodin's avatar
Dmitry Volodin committed
221
222
223
224
225
    ##
    ## Search engine
    ##
    @classmethod
    def search(cls,user,query,limit):
226
        q=Q(repo_path__icontains=query)|Q(name__icontains=query)|Q(address__icontains=query)|Q(user__icontains=query)|Q(description__icontains=query)
Dmitry Volodin's avatar
Dmitry Volodin committed
227
228
229
230
231
232
233
234
        for o in [o for o in cls.objects.filter(q) if o.has_access(user)]:
            relevancy=1.0
            yield SearchResult(
                url="/admin/sa/managedobject/%d/"%o.id,
                title="SA: "+unicode(o),
                text=unicode(o),
                relevancy=relevancy
            )
Dmitry Volodin's avatar
Dmitry Volodin committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

##
##
##
class UserAccess(models.Model):
    class Meta:
        verbose_name="User Access"
        verbose_name_plural="User Access"
    user=models.ForeignKey(User,verbose_name="User")
    administrative_domain=models.ForeignKey(AdministrativeDomain,verbose_name="Administrative Domain",blank=True,null=True)
    group=models.ForeignKey(ObjectGroup,verbose_name="Group",blank=True,null=True)
    def __unicode__(self):
        def q(o):
            if o:
                return o.name
            else:
                return "*"
        return "(%s,%s,%s)"%(self.user.username,q(self.administrative_domain),q(self.group))
##
##
##
Dmitry Volodin's avatar
Dmitry Volodin committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
class TaskSchedule(models.Model):
    periodic_name=models.CharField("Periodic Task",max_length=64,choices=periodic_registry.choices)
    is_enabled=models.BooleanField("Enabled?",default=False)
    run_every=models.PositiveIntegerField("Run Every (secs)",default=86400)
    retries=models.PositiveIntegerField("Retries",default=1)
    retry_delay=models.PositiveIntegerField("Retry Delay (secs)",default=60)
    timeout=models.PositiveIntegerField("Timeout (secs)",default=300)
    next_run=models.DateTimeField("Next Run",auto_now_add=True)
    retries_left=models.PositiveIntegerField("Retries Left",default=1)

    def __unicode__(self):
        return self.periodic_name

    def _periodic_class(self):
        return periodic_registry[self.periodic_name]
    periodic_class=property(_periodic_class)

    @classmethod
    def get_pending_tasks(cls,exclude=None):
        if exclude:
            TaskSchedule.objects.filter(next_run__lte=datetime.datetime.now(),is_enabled=True).exclude(id__in=exclude).order_by("-next_run")
        else:
            return TaskSchedule.objects.filter(next_run__lte=datetime.datetime.now(),is_enabled=True).order_by("-next_run")
Dmitry Volodin's avatar
Dmitry Volodin committed
279
280
281
282
283
284
285
286
287
288
289

    ##
    ## Link to relaunch task
    ##
    def run_now_link(self):
        try:
            return "<A HREF='/sa/task/%d/now/'>Run Now</A>"%(self.id)
        except:
            return ""
    run_now_link.short_description="Run Now"
    run_now_link.allow_tags=True
Dmitry Volodin's avatar
Dmitry Volodin committed
290
##
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
## Object Selector
##
class ManagedObjectSelector(models.Model):
    class Meta:
        verbose_name="Managed Object Selector"
        verbose_name_plural="Managed Object Selectors"
        ordering=["name"]
    name=models.CharField("Name",max_length=64,unique=True)
    description=models.TextField("Description",blank=True,null=True)
    is_enabled=models.BooleanField("Is Enabled",default=True)
    filter_id=models.IntegerField("Filter by ID",null=True,blank=True)
    filter_name=models.CharField("Filter by Name (REGEXP)",max_length=256,null=True,blank=True)
    filter_profile=models.CharField("Filter by Profile",max_length=64,null=True,blank=True,choices=profile_registry.choices)
    filter_address=models.CharField("Filter by Address (REGEXP)",max_length=256,null=True,blank=True)
    filter_administrative_domain=models.ForeignKey(AdministrativeDomain,verbose_name="Filter by Administrative Domain",null=True,blank=True)
306
    filter_activator=models.ForeignKey(Activator,verbose_name="Filter by Activator",null=True,blank=True)
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
    filter_user=models.CharField("Filter by User (REGEXP)",max_length=256,null=True,blank=True)
    filter_remote_path=models.CharField("Filter by Remote Path (REGEXP)",max_length=256,null=True,blank=True)
    filter_groups=models.ManyToManyField(ObjectGroup,verbose_name="Filter by Groups",null=True,blank=True)
    filter_description=models.CharField("Filter by Description (REGEXP)",max_length=256,null=True,blank=True)
    filter_repo_path=models.CharField("Filter by Repo Path (REGEXP)",max_length=256,null=True,blank=True)
    source_combine_method=models.CharField("Source Combine Method",max_length=1,default="O",choices=[("A","AND"),("O","OR")])
    sources=models.ManyToManyField("ManagedObjectSelector",verbose_name="Sources",symmetrical=False,null=True,blank=True)
    
    def __unicode__(self):
        return self.name
    ##
    ## Returns a queryset containing selected managed objects
    ##
    def _managed_objects(self):
        # Apply restrictions
        q=Q(is_managed=True)
        if self.filter_id:
            q&=Q(id=self.filter_id)
        if self.filter_name:
            q&=Q(name__regex=self.filter_name)
        if self.filter_profile:
            q&=Q(profile_name=self.filter_profile)
        if self.filter_address:
            q&=Q(address__regex=self.filter_address)
        if self.filter_administrative_domain:
            q&=Q(administrative_domain=self.filter_administrative_domain)
333
334
        if self.filter_activator:
            q&=Q(activator=self.filter_activator)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
        if self.filter_user:
            q&=Q(user__regex=self.filter_user)
        if self.filter_remote_path:
            q&=Q(remote_path__regex=self.filter_remote_path)
        if self.filter_description:
            q&=Q(description__regex=self.filter_description)
        if self.filter_repo_path:
            q&=Q(repo_path__regex=self.filter_repo_path)
        r=ManagedObject.objects.filter(q)
        # Restrict to groups when necessary
        for g in self.filter_groups.all():
            r=r.extra(where=["id IN (SELECT managedobject_id FROM sa_managedobject_groups WHERE objectgroup_id=%s)"],
                params=[g.id])
        # Restrict to sources
        if self.sources.count():
            sm=self.source_combine_method
            for s in self.sources.all():
                if s.id==self.id: # Do not include self
                    continue
                if sm=="A": # AND
                    r&=s.managed_objects
                else: # OR
                    r|=s.managed_objects
358
        return r.exclude(profile_name="NOC")
359
360
361
362
363
364
365
366
367
368
369
    managed_objects=property(_managed_objects)
    ##
    ## Link to the test
    ##
    def test_link(self):
        try:
            return "<A HREF='/sa/test_selector/%d/'>Test Selector</A>"%(self.id)
        except:
            return ""
    test_link.short_description="Test Selector"
    test_link.allow_tags=True
Dmitry Volodin's avatar
Dmitry Volodin committed
370
371
372
373
374
    ##
    ## Check Managed Object matches selector
    ##
    def match(self,managed_object):
        return self.managed_objects.filter(id=managed_object.id).count()>0
375
376
377
378
379
380
##
## Reduce Tasks
##
class ReduceTask(models.Model):
    class Meta:
        verbose_name="Map/Reduce Task"
Dmitry Volodin's avatar
Dmitry Volodin committed
381
        verbose_name_plural="Map/Reduce Tasks"
382
383
384
385
386
387
    start_time=models.DateTimeField("Start Time")
    stop_time=models.DateTimeField("Stop Time")
    reduce_script=models.CharField("Script",max_length=256,choices=reduce_script_registry.choices)
    script_params=PickledField("Params",null=True,blank=True)
    
    def __unicode__(self):
388
389
390
391
        if self.id:
            return u"%d: %s"%(self.id,self.reduce_script)
        else:
            return u"New: %s"%(self.reduce_script)
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    ##
    ## Check all map tasks are completed
    ##
    def _complete(self):
        return self.stop_time<=datetime.datetime.now()\
            or (self.maptask_set.all().count()==self.maptask_set.filter(status__in=["C","F"]).count())
    complete=property(_complete)
    ##
    ## Create map/reduce tasks
    ##
    @classmethod
    def create_task(self,object_selector,reduce_script,reduce_script_params,map_script,map_script_params,timeout):
        start_time=datetime.datetime.now()
        r_task=ReduceTask(
            start_time=start_time,
            stop_time=start_time+datetime.timedelta(seconds=timeout),
            reduce_script=reduce_script,
            script_params=reduce_script_params,
        )
        r_task.save()
        prepend_profile=len(map_script.split("."))!=3
        for o in object_selector.managed_objects:
            # Prepend profile name when necessary
            if prepend_profile:
                ms="%s.%s"%(o.profile_name,map_script)
            else:
                ms=map_script
            #
            status="W"
            # Check script is present
            if not ms.startswith(o.profile_name+".")\
                or map_script not in profile_registry[o.profile_name].scripts:
                    # No such script
                    status="F"
            #
            MapTask(
                task=r_task,
                managed_object=o,
                map_script=ms,
                script_params=map_script_params,
                next_try=start_time,
                status=status
            ).save()
        return r_task
    ##
    ## Perform reduce script and execute result
    ##
    def get_result(self):
        return reduce_script_registry[self.reduce_script].execute(self)
##
## Map Tasks
##
class MapTask(models.Model):
    class Meta:
        verbose_name="Map/Reduce Task Data"
        verbose_name="Map/Reduce Task Data"
    task=models.ForeignKey(ReduceTask,verbose_name="Task")
    managed_object=models.ForeignKey(ManagedObject,verbose_name="Managed Object")
    map_script=models.CharField("Script",max_length=256)
    script_params=PickledField("Params",null=True,blank=True)
    next_try=models.DateTimeField("Next Try")
    retries_left=models.IntegerField("Retries Left",default=1)
    status=models.CharField("Status",max_length=1,choices=[("W","Wait"),("R","Running"),("C","Complete"),("F","Failed")],default="W")
    script_result=PickledField("Result",null=True,blank=True)
    def __unicode__(self):
457
458
459
460
        if self.id:
            return u"%d: %s %s"%(self.id,self.managed_object,self.map_script)
        else:
            return u"New: %s %s"%(self.managed_object,self.map_script)
461
##
Dmitry Volodin's avatar
Dmitry Volodin committed
462
463
464
465
466
467
468
## Application Menu
##
class AppMenu(Menu):
    app="sa"
    title="Service Activation"
    items=[
        ("Managed Objects", "/admin/sa/managedobject/", "sa.change_managedobject"),
469
        ("Map/Reduce Tasks","/sa/mr_task/",             "sa.add_reducetask"),
Dmitry Volodin's avatar
Dmitry Volodin committed
470
471
472
473
474
475
        ("Task Schedules",  "/admin/sa/taskschedule/",  "sa.change_taskschedule"),
        ("Setup", [
            ("Activators",             "/admin/sa/activator/"            , "sa.change_activator"),
            ("Administrative Domains", "/admin/sa/administrativedomain/" , "sa.change_administrativedomain"),
            ("Object Groups",          "/admin/sa/objectgroup/"          , "sa.change_objectgroup"),
            ("User Access",            "/admin/sa/useraccess/"           , "sa.change_useraccess"),
476
            ("Object Selectors",       "/admin/sa/managedobjectselector/", "sa.change_managedobjectselector"),
Dmitry Volodin's avatar
Dmitry Volodin committed
477
478
        ])
    ]