sites.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import decimal
  2. from django.contrib.contenttypes.fields import GenericRelation
  3. from django.core.exceptions import ValidationError
  4. from django.core.validators import MaxValueValidator, MinValueValidator
  5. from django.db import models
  6. from django.utils.translation import gettext_lazy as _
  7. from timezone_field import TimeZoneField
  8. from dcim.choices import *
  9. from dcim.constants import *
  10. from netbox.models import NestedGroupModel, PrimaryModel
  11. from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
  12. __all__ = (
  13. 'Location',
  14. 'Region',
  15. 'Site',
  16. 'SiteGroup',
  17. )
  18. #
  19. # Regions
  20. #
  21. class Region(ContactsMixin, NestedGroupModel):
  22. """
  23. A region represents a geographic collection of sites. For example, you might create regions representing countries,
  24. states, and/or cities. Regions are recursively nested into a hierarchy: all sites belonging to a child region are
  25. also considered to be members of its parent and ancestor region(s).
  26. """
  27. prefixes = GenericRelation(
  28. to='ipam.Prefix',
  29. content_type_field='scope_type',
  30. object_id_field='scope_id',
  31. related_query_name='region'
  32. )
  33. vlan_groups = GenericRelation(
  34. to='ipam.VLANGroup',
  35. content_type_field='scope_type',
  36. object_id_field='scope_id',
  37. related_query_name='region'
  38. )
  39. class Meta:
  40. # Empty tuple triggers Django migration detection for MPTT indexes
  41. # (see #21016, django-mptt/django-mptt#682)
  42. indexes = ()
  43. constraints = (
  44. models.UniqueConstraint(
  45. fields=('parent', 'name'),
  46. name='%(app_label)s_%(class)s_parent_name'
  47. ),
  48. models.UniqueConstraint(
  49. fields=('name',),
  50. name='%(app_label)s_%(class)s_name',
  51. condition=Q(parent__isnull=True),
  52. violation_error_message=_("A top-level region with this name already exists.")
  53. ),
  54. models.UniqueConstraint(
  55. fields=('parent', 'slug'),
  56. name='%(app_label)s_%(class)s_parent_slug'
  57. ),
  58. models.UniqueConstraint(
  59. fields=('slug',),
  60. name='%(app_label)s_%(class)s_slug',
  61. condition=Q(parent__isnull=True),
  62. violation_error_message=_("A top-level region with this slug already exists.")
  63. ),
  64. )
  65. verbose_name = _('region')
  66. verbose_name_plural = _('regions')
  67. def get_site_count(self):
  68. return Site.objects.filter(
  69. Q(region=self) |
  70. Q(region__in=self.get_descendants())
  71. ).count()
  72. #
  73. # Site groups
  74. #
  75. class SiteGroup(ContactsMixin, NestedGroupModel):
  76. """
  77. A site group is an arbitrary grouping of sites. For example, you might have corporate sites and customer sites; and
  78. within corporate sites you might distinguish between offices and data centers. Like regions, site groups can be
  79. nested recursively to form a hierarchy.
  80. """
  81. prefixes = GenericRelation(
  82. to='ipam.Prefix',
  83. content_type_field='scope_type',
  84. object_id_field='scope_id',
  85. related_query_name='site_group'
  86. )
  87. vlan_groups = GenericRelation(
  88. to='ipam.VLANGroup',
  89. content_type_field='scope_type',
  90. object_id_field='scope_id',
  91. related_query_name='site_group'
  92. )
  93. class Meta:
  94. # Empty tuple triggers Django migration detection for MPTT indexes
  95. # (see #21016, django-mptt/django-mptt#682)
  96. indexes = ()
  97. constraints = (
  98. models.UniqueConstraint(
  99. fields=('parent', 'name'),
  100. name='%(app_label)s_%(class)s_parent_name'
  101. ),
  102. models.UniqueConstraint(
  103. fields=('name',),
  104. name='%(app_label)s_%(class)s_name',
  105. condition=Q(parent__isnull=True),
  106. violation_error_message=_("A top-level site group with this name already exists.")
  107. ),
  108. models.UniqueConstraint(
  109. fields=('parent', 'slug'),
  110. name='%(app_label)s_%(class)s_parent_slug'
  111. ),
  112. models.UniqueConstraint(
  113. fields=('slug',),
  114. name='%(app_label)s_%(class)s_slug',
  115. condition=Q(parent__isnull=True),
  116. violation_error_message=_("A top-level site group with this slug already exists.")
  117. ),
  118. )
  119. verbose_name = _('site group')
  120. verbose_name_plural = _('site groups')
  121. def get_site_count(self):
  122. return Site.objects.filter(
  123. Q(group=self) |
  124. Q(group__in=self.get_descendants())
  125. ).count()
  126. #
  127. # Sites
  128. #
  129. class Site(ContactsMixin, ImageAttachmentsMixin, PrimaryModel):
  130. """
  131. A Site represents a geographic location within a network; typically a building or campus. The optional facility
  132. field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
  133. """
  134. name = models.CharField(
  135. verbose_name=_('name'),
  136. max_length=100,
  137. unique=True,
  138. help_text=_("Full name of the site"),
  139. db_collation="natural_sort"
  140. )
  141. slug = models.SlugField(
  142. verbose_name=_('slug'),
  143. max_length=100,
  144. unique=True
  145. )
  146. status = models.CharField(
  147. verbose_name=_('status'),
  148. max_length=50,
  149. choices=SiteStatusChoices,
  150. default=SiteStatusChoices.STATUS_ACTIVE
  151. )
  152. region = models.ForeignKey(
  153. to='dcim.Region',
  154. on_delete=models.SET_NULL,
  155. related_name='sites',
  156. blank=True,
  157. null=True
  158. )
  159. group = models.ForeignKey(
  160. to='dcim.SiteGroup',
  161. on_delete=models.SET_NULL,
  162. related_name='sites',
  163. blank=True,
  164. null=True
  165. )
  166. tenant = models.ForeignKey(
  167. to='tenancy.Tenant',
  168. on_delete=models.PROTECT,
  169. related_name='sites',
  170. blank=True,
  171. null=True
  172. )
  173. facility = models.CharField(
  174. verbose_name=_('facility'),
  175. max_length=50,
  176. blank=True,
  177. help_text=_('Local facility ID or description')
  178. )
  179. asns = models.ManyToManyField(
  180. to='ipam.ASN',
  181. related_name='sites',
  182. blank=True
  183. )
  184. time_zone = TimeZoneField(
  185. blank=True,
  186. null=True
  187. )
  188. physical_address = models.CharField(
  189. verbose_name=_('physical address'),
  190. max_length=200,
  191. blank=True,
  192. help_text=_('Physical location of the building')
  193. )
  194. shipping_address = models.CharField(
  195. verbose_name=_('shipping address'),
  196. max_length=200,
  197. blank=True,
  198. help_text=_('If different from the physical address')
  199. )
  200. latitude = models.DecimalField(
  201. verbose_name=_('latitude'),
  202. max_digits=8,
  203. decimal_places=6,
  204. blank=True,
  205. null=True,
  206. validators=[
  207. MinValueValidator(decimal.Decimal('-90.0')),
  208. MaxValueValidator(decimal.Decimal('90.0'))
  209. ],
  210. help_text=_('GPS coordinate in decimal format (xx.yyyyyy)')
  211. )
  212. longitude = models.DecimalField(
  213. verbose_name=_('longitude'),
  214. max_digits=9,
  215. decimal_places=6,
  216. blank=True,
  217. null=True,
  218. validators=[
  219. MinValueValidator(decimal.Decimal('-180.0')),
  220. MaxValueValidator(decimal.Decimal('180.0'))
  221. ],
  222. help_text=_('GPS coordinate in decimal format (xx.yyyyyy)')
  223. )
  224. # Generic relations
  225. prefixes = GenericRelation(
  226. to='ipam.Prefix',
  227. content_type_field='scope_type',
  228. object_id_field='scope_id',
  229. related_query_name='site'
  230. )
  231. vlan_groups = GenericRelation(
  232. to='ipam.VLANGroup',
  233. content_type_field='scope_type',
  234. object_id_field='scope_id',
  235. related_query_name='site'
  236. )
  237. clone_fields = (
  238. 'status', 'region', 'group', 'tenant', 'facility', 'time_zone', 'physical_address', 'shipping_address',
  239. 'latitude', 'longitude', 'description',
  240. )
  241. class Meta:
  242. ordering = ('name',)
  243. verbose_name = _('site')
  244. verbose_name_plural = _('sites')
  245. def __str__(self):
  246. return self.name
  247. def get_status_color(self):
  248. return SiteStatusChoices.colors.get(self.status)
  249. #
  250. # Locations
  251. #
  252. class Location(ContactsMixin, ImageAttachmentsMixin, NestedGroupModel):
  253. """
  254. A Location represents a subgroup of Racks and/or Devices within a Site. A Location may represent a building within a
  255. site, or a room within a building, for example.
  256. """
  257. site = models.ForeignKey(
  258. to='dcim.Site',
  259. on_delete=models.CASCADE,
  260. related_name='locations'
  261. )
  262. status = models.CharField(
  263. verbose_name=_('status'),
  264. max_length=50,
  265. choices=LocationStatusChoices,
  266. default=LocationStatusChoices.STATUS_ACTIVE
  267. )
  268. tenant = models.ForeignKey(
  269. to='tenancy.Tenant',
  270. on_delete=models.PROTECT,
  271. related_name='locations',
  272. blank=True,
  273. null=True
  274. )
  275. facility = models.CharField(
  276. verbose_name=_('facility'),
  277. max_length=50,
  278. blank=True,
  279. help_text=_('Local facility ID or description')
  280. )
  281. # Generic relations
  282. prefixes = GenericRelation(
  283. to='ipam.Prefix',
  284. content_type_field='scope_type',
  285. object_id_field='scope_id',
  286. related_query_name='location'
  287. )
  288. vlan_groups = GenericRelation(
  289. to='ipam.VLANGroup',
  290. content_type_field='scope_type',
  291. object_id_field='scope_id',
  292. related_query_name='location'
  293. )
  294. clone_fields = ('site', 'parent', 'status', 'tenant', 'facility', 'description')
  295. prerequisite_models = (
  296. 'dcim.Site',
  297. )
  298. class Meta:
  299. ordering = ['site', 'name']
  300. # Empty tuple triggers Django migration detection for MPTT indexes
  301. # (see #21016, django-mptt/django-mptt#682)
  302. indexes = ()
  303. constraints = (
  304. models.UniqueConstraint(
  305. fields=('site', 'parent', 'name'),
  306. name='%(app_label)s_%(class)s_parent_name'
  307. ),
  308. models.UniqueConstraint(
  309. fields=('site', 'name'),
  310. name='%(app_label)s_%(class)s_name',
  311. condition=Q(parent__isnull=True),
  312. violation_error_message=_("A location with this name already exists within the specified site.")
  313. ),
  314. models.UniqueConstraint(
  315. fields=('site', 'parent', 'slug'),
  316. name='%(app_label)s_%(class)s_parent_slug'
  317. ),
  318. models.UniqueConstraint(
  319. fields=('site', 'slug'),
  320. name='%(app_label)s_%(class)s_slug',
  321. condition=Q(parent__isnull=True),
  322. violation_error_message=_("A location with this slug already exists within the specified site.")
  323. ),
  324. )
  325. verbose_name = _('location')
  326. verbose_name_plural = _('locations')
  327. def get_status_color(self):
  328. return LocationStatusChoices.colors.get(self.status)
  329. def clean(self):
  330. super().clean()
  331. # Parent Location (if any) must belong to the same Site
  332. if self.parent and self.parent.site != self.site:
  333. raise ValidationError(_(
  334. "Parent location ({parent}) must belong to the same site ({site})."
  335. ).format(parent=self.parent, site=self.site))