~mpontillo/maas/add-logging-for-bug-1627362

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# Copyright 2016 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Model definition for a `Discovery` (a discovered network device)."""

__all__ = [
    'Discovery',
]

from django.db.models import (
    CharField,
    DateTimeField,
    DO_NOTHING,
    ForeignKey,
    IntegerField,
    Manager,
    NullBooleanField,
)
from django.db.models.query import QuerySet
from maasserver import DefaultViewMeta
from maasserver.fields import (
    CIDRField,
    DomainNameField,
    MAASIPAddressField,
    MACAddressField,
)
from maasserver.models.cleansave import CleanSave
from maasserver.models.viewmodel import ViewModel
from maasserver.utils.orm import MAASQueriesMixin
from provisioningserver.logger import get_maas_logger
from provisioningserver.utils.network import get_mac_organization


maaslog = get_maas_logger("discovery")


class DiscoveryQueriesMixin(MAASQueriesMixin):

    def get_specifiers_q(self, specifiers, separator=':', **kwargs):
        # This dict is used by the constraints code to identify objects
        # with particular properties. Please note that changing the keys here
        # can impact backward compatibility, so use caution.
        specifier_types = {
            None: "__discovery_id",
            'ip': "__ip",
            'mac': "__mac_address",
        }
        return super(DiscoveryQueriesMixin, self).get_specifiers_q(
            specifiers, specifier_types=specifier_types, separator=separator,
            **kwargs)

    def by_unknown_mac(self):
        """Returns a `QuerySet` of discoveries which have a MAC that is unknown
        to MAAS. (That is, is not associated with any known Interface.)
        """
        # Circular imports
        from maasserver.models import Interface
        known_macs = Interface.objects.values_list(
            'mac_address', flat=True).distinct()
        return self.exclude(mac_address__in=known_macs)

    def by_unknown_ip(self):
        """Returns a `QuerySet` of discoveries which have an IP that is unknown
        to MAAS. (That is, is not associated with any known StaticIPAddress.)
        """
        # Circular imports
        from maasserver.models import StaticIPAddress
        known_ips = StaticIPAddress.objects.exclude(
            ip__isnull=True).values_list('ip', flat=True)
        return self.exclude(ip__in=known_ips)

    def by_unknown_ip_and_mac(self):
        """Returns a `QuerySet` of discoveries which have a MAC and IP
        address which are *both* unknown to MAAS. (That is, is not associated
        with any known Interface and StaticIPAddress, respectively.)

        This could happen if a known IP address is seen from an unexpected MAC,
        or if a known MAC address is seen using an unexpected IP. We may want
        to filter these types of irregularities from the user, so that
        unexpected devices do not show up in their discovered devices list.
        However, we may wish to surface the discoveries filtered by this query
        in another way.
        """
        return self.by_unknown_mac().by_unknown_ip()


class DiscoveryQuerySet(DiscoveryQueriesMixin, QuerySet):
    """Custom QuerySet which mixes in some additional queries specific to
    subnets. This needs to be a mixin because an identical method is needed on
    both the Manager and all QuerySets which result from calling the manager.
    """


class DiscoveryManager(Manager, DiscoveryQueriesMixin):
    """A utility to manage collections of Discoverys."""

    def get_queryset(self):
        queryset = DiscoveryQuerySet(self.model, using=self._db)
        return queryset

    def get_discovery_or_404(self, specifiers):
        """Fetch a `Discovery` by its ID or specifiers.

        :param specifiers: The discovery specifiers.
        :type specifiers: str
        :raises: django.http.Http404_,
            :class:`maasserver.exceptions.PermissionDenied`.

        .. _django.http.Http404: https://
           docs.djangoproject.com/en/dev/topics/http/views/
           #the-http404-exception
        """
        discovery = self.get_object_by_specifiers_or_raise(specifiers)
        return discovery

    def clear(self, user=None, all=False, mdns=False, neighbours=False):
        """Deletes discoveries of the specified type(s).

        :param all: Deletes all discovery data.
        :param mdns: Deletes mDNS entries.
        :param neighbours: Deletes neighbour entries.
        """
        # Circular imports.
        from maasserver.models import (
            MDNS,
            Neighbour,
        )
        if True not in (all, mdns, neighbours):
            return
        if mdns or all:
            MDNS.objects.all().delete()
            what = "mDNS"
        if neighbours or all:
            Neighbour.objects.all().delete()
            what = "neighbour"
        if all:
            what = "mDNS and neighbour"
        maaslog.info("%s all %s entries." % (
            "Cleared" if user is None else "User '%s' cleared" % (
                user.username), what))


class Discovery(CleanSave, ViewModel):
    """A `Discovery` object represents the combined data for a network entity
    that MAAS believes has been discovered.

    Note that this class is backed by the `maasserver_discovery` view. Any
    updates to this model must be reflected in `maasserver/dbviews.py` under
    the `maasserver_discovery` view.
    """

    class Meta(DefaultViewMeta):
        # When managed is False, Django will not create a migration for this
        # model class. This is required for model classes based on views.
        verbose_name = "Discovery"
        verbose_name_plural = "Discoveries"

    discovery_id = CharField(
        max_length=256, editable=False, null=True, blank=False, unique=True)

    neighbour = ForeignKey(
        'Neighbour', unique=False, blank=False, null=False, editable=False,
        on_delete=DO_NOTHING)

    # Observed IP address.
    ip = MAASIPAddressField(
        unique=False, null=True, editable=False, blank=True,
        default=None, verbose_name='IP')

    mac_address = MACAddressField(
        unique=False, null=True, blank=True, editable=False)

    first_seen = DateTimeField(editable=False)

    last_seen = DateTimeField(editable=False)

    mdns = ForeignKey(
        'MDNS', unique=False, blank=True, null=True, editable=False,
        on_delete=DO_NOTHING)

    # Hostname observed from mDNS-browse.
    hostname = CharField(
        max_length=256, editable=False, null=True, blank=False, unique=False)

    observer = ForeignKey(
        'Node', unique=False, blank=False, null=False, editable=False,
        on_delete=DO_NOTHING)

    observer_system_id = CharField(
        max_length=41, unique=False, editable=False)

    # The hostname of the node that made the discovery.
    observer_hostname = DomainNameField(
        max_length=256, editable=False, null=True, blank=False, unique=False)

    # Rack interface the discovery was observed on.
    observer_interface = ForeignKey(
        'Interface', unique=False, blank=False, null=False, editable=False,
        on_delete=DO_NOTHING)

    observer_interface_name = CharField(
        blank=False, editable=False, max_length=255)

    fabric = ForeignKey(
        'Fabric', unique=False, blank=False, null=False, editable=False,
        on_delete=DO_NOTHING)

    fabric_name = CharField(
        max_length=256, editable=False, null=True, blank=True, unique=False)

    vlan = ForeignKey(
        'VLAN', unique=False, blank=False, null=False, editable=False,
        on_delete=DO_NOTHING)

    vid = IntegerField(null=True, blank=True)

    # These will only be non-NULL if we found a related Subnet.
    subnet = ForeignKey(
        'Subnet', unique=False, blank=True, null=True, editable=False,
        on_delete=DO_NOTHING)

    subnet_cidr = CIDRField(
        blank=True, unique=False, editable=False, null=True)

    is_external_dhcp = NullBooleanField(
        blank=True, unique=False, editable=False, null=True)

    objects = DiscoveryManager()

    @property
    def mac_organization(self):
        return get_mac_organization(str(self.mac_address))