sites.py 11 KB

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