Example #1
0
class SupplierProfile(Document):
    meta = {"collection": "noc.supplierprofiles", "strict": False, "auto_create_index": False}

    name = StringField(unique=True)
    description = StringField()
    workflow = PlainReferenceField(Workflow)
    style = ForeignKeyField(Style, required=False)
    # Labels
    labels = ListField(StringField())
    effective_labels = ListField(StringField())
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"), lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return SupplierProfile.objects.filter(id=id).first()

    @classmethod
    def can_set_label(cls, label):
        return Label.get_effective_setting(label, setting="enable_supplierprofile")
Example #2
0
class Supplier(Document):
    meta = {
        "collection": "noc.suppliers",
        "indexes": ["name"],
        "strict": False,
        "auto_create_index": False,
    }

    name = StringField()
    description = StringField()
    is_affilated = BooleanField(default=False)
    profile = PlainReferenceField(SupplierProfile)
    state = PlainReferenceField(State)
    project = ForeignKeyField(Project)
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    tags = ListField(StringField())

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return Supplier.objects.filter(id=id).first()
Example #3
0
class PhoneRangeProfile(Document):
    meta = {
        "collection": "noc.phonerangeprofiles",
        "strict": False,
        "auto_create_index": False
    }

    name = StringField(unique=True)
    description = StringField()
    # Default phone number profile
    default_number_profile = PlainReferenceField(PhoneNumberProfile)
    # Cooldown time in days
    # Time when number will be automatically transferred from C to F state
    cooldown = IntField(default=30)
    style = ForeignKeyField(Style)
    workflow = PlainReferenceField(Workflow)

    _id_cache = cachetools.TTLCache(100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return PhoneRangeProfile.objects.filter(id=id).first()
Example #4
0
class AddressProfile(Document):
    meta = {
        "collection": "addressprofiles",
        "strict": False,
        "auto_create_index": False
    }

    name = StringField(unique=True)
    description = StringField()
    # Address workflow
    workflow = PlainReferenceField(Workflow)
    style = ForeignKeyField(Style)
    # Template.subject to render Address.name
    name_template = ForeignKeyField(Template)
    # Template.subject to render Address.fqdn
    fqdn_template = ForeignKeyField(Template)
    # Send seen event to prefix
    seen_propagation_policy = StringField(choices=[("E", "Enable"),
                                                   ("D", "Disable")],
                                          default="D")
    # Labels
    labels = ListField(StringField())
    effective_labels = ListField(StringField())
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _name_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _bi_id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return AddressProfile.objects.filter(id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_name_cache"),
                             lock=lambda _: id_lock)
    def get_by_name(cls, name):
        return AddressProfile.objects.filter(name=name).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_bi_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_bi_id(cls, id):
        return AddressProfile.objects.filter(bi_id=id).first()

    @classmethod
    def can_set_label(cls, label):
        return Label.get_effective_setting(label,
                                           setting="enable_addressprofile")
Example #5
0
class PrefixProfile(Document):
    meta = {"collection": "prefixprofiles", "strict": False, "auto_create_index": False}

    name = StringField(unique=True)
    description = StringField()
    # Enable nested Address discovery
    # via ARP cache
    enable_ip_discovery = BooleanField(default=False)
    # Enable nested Addresses discovery
    # via active PING probes
    enable_ip_ping_discovery = BooleanField(default=False)
    # Enable nested prefix prefix discovery
    enable_prefix_discovery = BooleanField(default=False)
    # Prefix workflow
    workflow = PlainReferenceField(Workflow)
    style = ForeignKeyField(Style)
    # Template.subject to render Prefix.name
    name_template = ForeignKeyField(Template)
    # Discovery policies
    prefix_discovery_policy = StringField(choices=[("E", "Enable"), ("D", "Disable")], default="D")
    address_discovery_policy = StringField(choices=[("E", "Enable"), ("D", "Disable")], default="D")
    # Send seen event to parent
    seen_propagation_policy = StringField(
        choices=[("P", "Propagate"), ("E", "Enable"), ("D", "Disable")], default="P"
    )
    # Include/Exclude broadcast & network addresses from prefix
    prefix_special_address_policy = StringField(
        choices=[("I", "Include"), ("X", "Exclude")], default="X"
    )
    # Labels
    labels = ListField(StringField())
    effective_labels = ListField(StringField())
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _bi_id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"), lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return PrefixProfile.objects.filter(id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_bi_id_cache"), lock=lambda _: id_lock)
    def get_by_bi_id(cls, id):
        return PrefixProfile.objects.filter(bi_id=id).first()

    @classmethod
    def can_set_label(cls, label):
        return Label.get_effective_setting(label, setting="enable_prefixprofile")
Example #6
0
class FirmwarePolicy(Document):
    meta = {
        "collection": "noc.firmwarepolicy",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["platform", "firmware"],
    }
    # Platform (Matched with get_version)
    platform = PlainReferenceField(Platform)
    #
    description = StringField()
    #
    object_profile = ForeignKeyField(ManagedObjectProfile)
    #
    firmware = PlainReferenceField(Firmware)
    status = StringField(choices=[
        (FS_RECOMMENDED, "Recommended"),
        (FS_ACCEPTABLE, "Acceptable"),
        (FS_NOT_RECOMMENDED, "Not recommended"),
        (FS_DENIED, "Denied"),
    ])
    #
    management = ListField(EmbeddedDocumentField(ManagementPolicy))

    @classmethod
    def get_status(cls, platform, version):
        if not platform or not version:
            return None
        fp = FirmwarePolicy.objects.filter(platform=platform.id,
                                           firmware=version.id).first()
        if fp:
            return fp.status
        else:
            return None

    @classmethod
    def get_recommended_version(cls, platform):
        """
        Get recommended version for  platform

        :param platform: Platform instance
        :return: Version string or None
        """
        if not platform:
            return None
        fp = FirmwarePolicy.objects.filter(platform=platform.id,
                                           status=FS_RECOMMENDED).first()
        if fp:
            return fp.firmware.version
        versions = []
        for fp in FirmwarePolicy.objects.filter(platform=platform.id,
                                                status=FS_ACCEPTABLE):
            versions += [fp.firmware.version]
        if versions:
            # Get latest acceptable version
            return list(sorted(versions, key=lambda x: alnum_key(x)))[-1]
        return None
Example #7
0
class VPN(Document):
    meta = {"collection": "vpns", "strict": False, "auto_create_index": False}

    name = StringField(unique=True)
    profile = PlainReferenceField(VPNProfile)
    description = StringField()
    state = PlainReferenceField(State)
    # Link to parent overlay
    parent = PlainReferenceField("self")
    project = ForeignKeyField(Project)
    route_target = ListField(EmbeddedDocumentField(RouteTargetItem))
    tags = ListField(StringField())
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)
    # @todo: last_seen
    # @todo: expired

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _bi_id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"), lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return VPN.objects.filter(id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_bi_id_cache"), lock=lambda _: id_lock)
    def get_by_bi_id(cls, id):
        return VPN.objects.filter(bi_id=id).first()

    def clean(self):
        super(VPN, self).clean()
        if self.id and "parent" in self._changed_fields and self.has_loop:
            raise ValidationError("Creating VPN loop")

    @property
    def has_loop(self):
        """
        Check if object creates loop
        """
        if not self.id:
            return False
        p = self.parent
        while p:
            if p.id == self.id:
                return True
            p = p.parent
        return False
Example #8
0
class ResourceGroup(Document):
    """
    Technology

    Abstraction to restrict ResourceGroup links
    """

    meta = {
        "collection": "resourcegroups",
        "strict": False,
        "auto_create_index": False
    }

    # Group | Name
    name = StringField()
    technology = PlainReferenceField(Technology)
    parent = PlainReferenceField("inv.ResourceGroup")
    description = StringField()
    # @todo: FM integration
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)
    # Tags
    tags = ListField(StringField())

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _bi_id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return "%s (%s)" % (self.name, self.technology.name)

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return ResourceGroup.objects.filter(id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_bi_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_bi_id(cls, id):
        return ResourceGroup.objects.filter(bi_id=id).first()

    def iter_changed_datastream(self, changed_fields=None):
        if config.datastream.enable_resourcegroup:
            yield "resourcegroup", self.id

    @property
    def has_children(self):
        return bool(
            ResourceGroup.objects.filter(parent=self.id).only("id").first())
Example #9
0
class ObjectValidationRule(EmbeddedDocument):
    query = PlainReferenceField(ConfDBQuery)
    query_params = DictField()
    filter_query = PlainReferenceField(ConfDBQuery)
    is_active = BooleanField(default=True)
    error_code = StringField()
    error_text_template = StringField(default="{{error}}")
    alarm_class = PlainReferenceField(AlarmClass)
    is_fatal = BooleanField(default=False)

    def __str__(self):
        return self.query.name
Example #10
0
class VLANProfile(Document):
    meta = {
        "collection": "vlanprofiles",
        "strict": False,
        "auto_create_index": False
    }

    name = StringField(unique=True)
    description = StringField()
    # VLAN is management VLAN
    enable_management = BooleanField(default=False)
    # VLAN is multicast VLAN
    enable_multicast = BooleanField(default=False)
    # VLAN should be automatically provisioned
    enable_provisioning = BooleanField(default=False)
    # VLAN workflow
    workflow = PlainReferenceField(Workflow)
    style = ForeignKeyField(Style)
    # Labels
    labels = ListField(StringField())
    effective_labels = ListField(StringField())
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _bi_id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return VLANProfile.objects.filter(id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_bi_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_bi_id(cls, id):
        return VLANProfile.objects.filter(bi_id=id).first()

    @classmethod
    def can_set_label(cls, label):
        return Label.get_effective_setting(label, "enable_vlanprofile")
Example #11
0
class ThresholdConfig(EmbeddedDocument):
    # Open condition
    op = StringField(choices=["<", "<=", ">=", ">"])
    value = FloatField()
    # Closing condition
    clear_op = StringField(choices=["<", "<=", ">=", ">"])
    clear_value = FloatField()
    # Umbrella alarm class
    alarm_class = PlainReferenceField(AlarmClass)
    # Send event to correlator
    open_event_class = PlainReferenceField(EventClass)
    close_event_class = PlainReferenceField(EventClass)
    # Handlers to call on open and close thresholds
    open_handler = PlainReferenceField(Handler)
    close_handler = PlainReferenceField(Handler)
    #
    template = ForeignKeyField(Template)

    def __str__(self):
        return "%s %s" % (self.op, self.value)

    def is_open_match(self, value):
        """
        Check if threshold profile is matched for open condition
        :param value:
        :return:
        """
        return (
            (self.op == "<" and value < self.value)
            or (self.op == "<=" and value <= self.value)
            or (self.op == ">=" and value >= self.value)
            or (self.op == ">" and value > self.value)
        )

    def is_clear_match(self, value):
        """
        Check if threshold profile is matched for clear condition
        :param value:
        :return:
        """
        return (
            (self.clear_op == "<" and value < self.clear_value)
            or (self.clear_op == "<=" and value <= self.clear_value)
            or (self.clear_op == ">=" and value >= self.clear_value)
            or (self.clear_op == ">" and value > self.clear_value)
        )

    @property
    def name(self):
        return "%s %s" % (self.op, self.value)
Example #12
0
class MACBlacklistAffected(EmbeddedDocument):
    vendor = PlainReferenceField(Vendor)
    platform = PlainReferenceField(Platform)

    def __str__(self):
        if self.platform:
            return "%s:%s" % (self.vendor.name, self.platform.name)
        return self.vendor.name

    def to_json(self):
        r = {"vendor__code": self.vendor.code}
        if self.platform:
            r["platform__name"] = self.platform.name
        return r
Example #13
0
class Change(Document):
    meta = {
        "collection": "noc.changes",
        "strict": False,
        "auto_create_index": False
    }
    document = PlainReferenceField(NormativeDocument)
Example #14
0
class AllocationGroup(Document):
    meta = {"collection": "allocationgroups", "strict": False, "auto_create_index": False}

    name = StringField(unique=True)
    description = StringField()
    tags = ListField(StringField())
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _bi_id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"), lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return AllocationGroup.objects.filter(id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_bi_id_cache"), lock=lambda _: id_lock)
    def get_by_bi_id(cls, id):
        return AllocationGroup.objects.filter(bi_id=id).first()
Example #15
0
class Street(Document):
    meta = {
        "collection": "noc.streets",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["parent", "data"],
    }
    #
    parent = PlainReferenceField(Division)
    # Normalized name
    name = StringField()
    # street/town/city, etc
    short_name = StringField()
    #
    is_active = BooleanField(default=True)
    # Additional data
    # Depends on importer
    data = DictField()
    #
    start_date = DateTimeField()
    end_date = DateTimeField()

    def __str__(self):
        if self.short_name:
            return "%s, %s" % (self.name, self.short_name)
        else:
            return self.name

    @property
    def full_path(self):
        if not self.parent:
            return ""
        r = [self.parent.full_path, smart_text(self)]
        return " | ".join(r)
Example #16
0
class SensorProfile(Document):
    meta = {
        "collection": "sensorprofiles",
        "strict": False,
        "auto_create_index": False
    }

    name = StringField(unique=True)
    description = StringField()
    workflow = PlainReferenceField(Workflow)
    style = ForeignKeyField(Style)
    enable_collect = BooleanField(default=False)
    # Labels
    labels = ListField(StringField())
    effective_labels = ListField(StringField())
    # BI ID
    bi_id = LongField(unique=True)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _bi_id_cache = cachetools.TTLCache(maxsize=100, ttl=60)
    _default_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    DEFAULT_PROFILE_NAME = "default"
    DEFAULT_WORKFLOW_NAME = "Sensor Default"

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id) -> "SensorProfile":
        return SensorProfile.objects.filter(id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_bi_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_bi_id(cls, id) -> "SensorProfile":
        return SensorProfile.objects.filter(bi_id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_default_cache"),
                             lock=lambda _: id_lock)
    def get_default_profile(cls) -> "SensorProfile":
        sp = SensorProfile.objects.filter(
            name=cls.DEFAULT_PROFILE_NAME).first()
        if not sp:
            sp = SensorProfile(
                name=cls.DEFAULT_PROFILE_NAME,
                workflow=Workflow.objects.filter(
                    name=cls.DEFAULT_WORKFLOW_NAME).first(),
            )
            sp.save()
        return sp

    @classmethod
    def can_set_label(cls, label):
        if label.enable_sensorprofile:
            return True
        return False
Example #17
0
class ServiceProfile(Document):
    meta = {
        "collection": "noc.serviceprofiles",
        "strict": False,
        "auto_create_index": False
    }
    name = StringField(unique=True)
    description = StringField()
    # Jinja2 service label template
    card_title_template = StringField()
    # Short service code for reporting
    code = StringField()
    # FontAwesome glyph
    glyph = StringField()
    # Glyph order in summary
    display_order = IntField(default=100)
    # Show in total summary
    show_in_summary = BooleanField(default=True)
    workflow = PlainReferenceField(Workflow)
    # Auto-assign interface profile when service binds to interface
    interface_profile = ReferenceField(InterfaceProfile)
    # Alarm weight
    weight = IntField(default=0)
    # Capabilities
    caps = ListField(EmbeddedDocumentField(CapsItem))
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = ReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)
    # Labels
    labels = ListField(StringField())
    effective_labels = ListField(StringField())

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return ServiceProfile.objects.filter(id=id).first()

    def on_save(self):
        if not hasattr(self, "_changed_fields"
                       ) or "interface_profile" in self._changed_fields:
            call_later(
                "noc.sa.models.serviceprofile.refresh_interface_profiles",
                sp_id=self.id,
                ip_id=self.interface_profile.id
                if self.interface_profile else None,
            )

    @classmethod
    def can_set_label(cls, label):
        return Label.get_effective_setting(label, "enable_serviceprofile")
Example #18
0
class ObjectValidationPolicy(Document):
    meta = {
        "collection": "objectvalidationpolicies",
        "strict": False,
        "auto_create_index": False
    }

    name = StringField(unique=True)
    description = StringField()
    filter_query = PlainReferenceField(ConfDBQuery)
    rules = ListField(EmbeddedDocumentField(ObjectValidationRule))

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return ObjectValidationPolicy.objects.filter(id=id).first()

    def iter_problems(self, engine):
        """
        Check rules against ConfDB engine

        :param engine: ConfDB Engine instance
        :return: List of problems
        """
        # Check filter query, if any
        if self.filter_query:
            if not self.filter_query.any(engine):
                raise StopIteration
        # Process rules
        for rule in self.rules:
            if not rule.is_active:
                continue
            if rule.filter_query:
                if not rule.filter_query.any(engine):
                    continue
            for ctx in rule.query.query(engine, **rule.query_params):
                if "error" in ctx:
                    tpl = Template(rule.error_text_template)
                    path = []
                    if rule.error_code:
                        path += [rule.error_code]
                    problem = {
                        "alarm_class":
                        rule.alarm_class.name if rule.alarm_class else None,
                        "path":
                        path,
                        "message":
                        tpl.render(ctx),
                        "code":
                        rule.error_code or None,
                    }
                    yield problem
                    if rule.is_fatal:
                        raise StopIteration
Example #19
0
class DSFormat(EmbeddedDocument):
    name = StringField()
    is_active = BooleanField()
    handler = PlainReferenceField(Handler)
    role = StringField()

    def __str__(self):
        return self.name
Example #20
0
class CoveredObject(Document):
    meta = {
        "collection": "noc.coveredobjects",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["coverage", "object"],
    }
    coverage = PlainReferenceField(Coverage)
    # Coverage preference.
    # The more is the better
    # Zero means coverage is explicitly disabled for ordering
    preference = IntField(default=100)

    object = PlainReferenceField(Object)

    def __str__(self):
        return "%s %s" % (self.coverage.name, self.object.name
                          or self.object.id)
Example #21
0
class ObjectConnectionItem(EmbeddedDocument):
    _meta = {"strict": False, "auto_create_index": False}
    # Object reference
    object = PlainReferenceField(Object)
    # Connection name
    name = StringField()

    def __str__(self):
        return "%s: %s" % (smart_text(self.object), self.name)
Example #22
0
class AffectedObjects(Document):
    meta = {
        "collection": "noc.affectedobjects",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["affected_objects.object"],
    }
    maintenance = PlainReferenceField(Maintenance)
    affected_objects = ListField(EmbeddedDocumentField(MaintenanceObject))
Example #23
0
class MIBData(Document):
    meta = {
        "collection": "noc.mibdata",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["name", "mib", "aliases"],
    }
    mib = PlainReferenceField(MIB)
    oid = StringField(required=True, unique=True)
    name = StringField(required=True)
    description = StringField(required=False)
    syntax = DictField(required=False)
    aliases = ListField(StringField(), default=[])

    _name_syntax_cache: Dict[str, Tuple[str, Dict[str, Any]]] = {}

    def __str__(self):
        return self.name

    @classmethod
    def preload(cls):
        """
        Preload data and heat up cache
        :return:
        """
        cls._name_syntax_cache = {
            d["oid"]: (d["name"], d["syntax"] or {})
            for d in cls._get_collection().find({}, {
                "_id": 0,
                "oid": 1,
                "name": 1,
                "syntax": 1
            })
        }
        cls.get_name_and_syntax = cls._get_name_and_syntax_cached

    @classmethod
    def _get_name_and_syntax_uncached(
            cls, oid: str) -> Tuple[Optional[str], Optional[Dict[str, Any]]]:
        d = cls._get_collection().find_one({"oid": oid}, {
            "_id": 0,
            "name": 1,
            "syntax": 1
        })
        if d:
            return d["name"], d["syntax"] or {}
        return None, None

    @classmethod
    def _get_name_and_syntax_cached(
            cls, oid: str) -> Tuple[Optional[str], Optional[Dict[str, Any]]]:
        r = cls._name_syntax_cache.get(oid)
        if r:
            return r
        return None, None

    get_name_and_syntax = _get_name_and_syntax_uncached
Example #24
0
class Subscriber(Document):
    meta = {
        "collection": "noc.subscribers",
        "indexes": ["name"],
        "strict": False,
        "auto_create_index": False,
    }

    name = StringField()
    description = StringField()
    profile = PlainReferenceField(SubscriberProfile)
    state = PlainReferenceField(State)
    # Main address
    address = StringField()
    # Technical contacts
    tech_contact_person = StringField()
    tech_contact_phone = StringField()
    project = ForeignKeyField(Project)
    # Labels
    labels = ListField(StringField())
    effective_labels = ListField(StringField())
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"), lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return Subscriber.objects.filter(id=id).first()

    @classmethod
    def can_set_label(cls, label):
        if label.enable_subscriber:
            return True
        return False
Example #25
0
class CoveredBuilding(Document):
    meta = {
        "collection": "noc.coveredbuildings",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["building", "coverage"],
    }
    coverage = PlainReferenceField(Coverage)
    # Coverage preference.
    # The more is the better
    # Zero means coverage is explicitly disabled for ordering
    preference = IntField(default=100)

    building = PlainReferenceField(Building)
    entrance = StringField(required=False)
    # Covered homes
    homes = IntField()

    def __str__(self):
        return "%s %s" % (self.coverage.name,
                          self.building.primary_address.display_ru())
Example #26
0
class VLANTranslation(EmbeddedDocument):
    filter = ForeignKeyField(VCFilter)
    rule = StringField(
        choices=[
            # Rewrite tag to parent vlan's
            ("map", "map"),
            # Append parent tag as S-VLAN
            ("push", "push"),
        ],
        default="push",
    )
    parent_vlan = PlainReferenceField("vc.VLAN")
Example #27
0
class SubscriberProfile(Document):
    meta = {
        "collection": "noc.subscriberprofiles",
        "strict": False,
        "auto_create_index": False
    }

    name = StringField(unique=True)
    description = StringField()
    style = ForeignKeyField(Style, required=False)
    workflow = PlainReferenceField(Workflow)
    # FontAwesome glyph
    glyph = StringField()
    # Glyph order in summary
    display_order = IntField(default=100)
    # Show in total summary
    show_in_summary = BooleanField(default=True)
    # Tags
    tags = ListField(StringField())
    # Alarm weight
    weight = IntField(default=0)
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return SubscriberProfile.objects.filter(id=id).first()
Example #28
0
class ArchivedEvent(Document):
    meta = {
        "collection": "noc.events.archive",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["timestamp", "alarms"],
    }
    status = "S"

    timestamp = DateTimeField(required=True)
    managed_object = ForeignKeyField(ManagedObject, required=True)
    event_class = PlainReferenceField(EventClass, required=True)
    start_timestamp = DateTimeField(required=True)
    repeats = IntField(required=True)
    raw_vars = RawDictField()
    resolved_vars = RawDictField()
    vars = DictField()
    log = ListField(EmbeddedDocumentField(EventLog))
    alarms = ListField(ObjectIdField())

    def __str__(self):
        return "%s" % self.id

    @property
    def duration(self):
        """
        Logged event duration in seconds
        """
        return (self.timestamp - self.start_timestamp).total_seconds()

    def get_template_vars(self):
        """
        Prepare template variables
        """
        vars = self.vars.copy()
        vars.update({"event": self})
        return vars

    @property
    def subject(self):
        ctx = Context(self.get_template_vars())
        s = Template(self.event_class.subject_template).render(ctx)
        if len(s) >= 255:
            s = s[:125] + " ... " + s[-125:]
        return s

    @property
    def body(self):
        ctx = Context(self.get_template_vars())
        s = Template(self.event_class.body_template).render(ctx)
        return s
Example #29
0
class MIBData(Document):
    meta = {
        "collection": "noc.mibdata",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["oid", "name", "mib", "aliases"],
    }
    mib = PlainReferenceField(MIB)
    oid = StringField(required=True, unique=True)
    name = StringField(required=True)
    description = StringField(required=False)
    syntax = DictField(required=False)
    aliases = ListField(StringField(), default=[])

    def __str__(self):
        return self.name
Example #30
0
class PhoneNumberProfile(Document):
    meta = {"collection": "noc.phonenumberprofiles", "strict": False, "auto_create_index": False}

    name = StringField(unique=True)
    description = StringField()
    style = ForeignKeyField(Style)
    workflow = PlainReferenceField(Workflow)

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"), lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return PhoneNumberProfile.objects.filter(id=id).first()