Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27673ee68f | ||
|
|
174a41e838 | ||
|
|
d7c86289b1 | ||
|
|
9735164da1 | ||
|
|
38b3ec2a27 | ||
|
|
4405a65653 | ||
|
|
ca29980aa6 | ||
|
|
55c70814c3 | ||
|
|
4ec96bf65d | ||
|
|
59ffd2a4b5 | ||
|
|
cd4357f417 | ||
|
|
c888a65180 | ||
|
|
74dfa0ec61 | ||
|
|
2c0e026cb9 |
No files matched your search
@@ -28,7 +28,7 @@ Before exporting, the technician selects which content the document contains:
|
|||||||
| Group | Content |
|
| Group | Content |
|
||||||
|---|---|
|
|---|---|
|
||||||
| General | Overview & site data (address, location tree, key figures), contacts |
|
| General | Overview & site data (address, location tree, key figures), contacts |
|
||||||
| Infrastructure | Racks by site → location with rack elevation (front/rear, optionally with device images as in NetBox) and occupancy list, devices by **selectable device roles** (servers, switches, APs, routers …) with **selectable columns**, power, VMs, **disks & RAID** from [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) (if installed) |
|
| Infrastructure | Racks by site → location with rack elevation (front/rear, optionally with device images as in NetBox) occupancy list and optional **rack photos** in an appendix, devices by **selectable device roles** (servers, switches, APs, routers …) with **selectable columns**, power, **virtualization clusters** with resources, VMs, **disks & RAID** from [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) (if installed), **floor plans** from [NetBox-FloorPlan](https://git.mrblake.cc/MrBlake/NetBox-FloorPlan2.0) (if installed) |
|
||||||
| Network | VRFs (incl. RTs), prefixes by VRF, VLANs, IP addresses (detailed), WLANs/SSIDs, circuits, **network topology** |
|
| Network | VRFs (incl. RTs), prefixes by VRF, VLANs, IP addresses (detailed), WLANs/SSIDs, circuits, **network topology** |
|
||||||
| Contracts & licenses | Licenses from [NetBox-SLM](https://git.mrblake.cc/MrBlake/NetBox-SLM) (detected automatically) or another license plugin (e.g. `netbox-lifecycle`) |
|
| Contracts & licenses | Licenses from [NetBox-SLM](https://git.mrblake.cc/MrBlake/NetBox-SLM) (detected automatically) or another license plugin (e.g. `netbox-lifecycle`) |
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ All queries respect NetBox permissions (`.restrict(user, "view")`) — a
|
|||||||
technician only exports what they are allowed to see.
|
technician only exports what they are allowed to see.
|
||||||
|
|
||||||
Open it via the **Customer Docs** button on site, location, tenant and tenant
|
Open it via the **Customer Docs** button on site, location, tenant and tenant
|
||||||
group pages, or via **Plugins → Customer Documentation**. Output formats:
|
group pages, or via **Customer Export → Customer Documentation** in the main navigation. Output formats:
|
||||||
**PDF**, **Word** and **HTML preview** (opens in a new tab).
|
**PDF**, **Word** and **HTML preview** (opens in a new tab).
|
||||||
|
|
||||||
## Compatibility
|
## Compatibility
|
||||||
@@ -182,7 +182,7 @@ sudo systemctl restart netbox netbox-rq
|
|||||||
|
|
||||||
### Branding in NetBox (recommended)
|
### Branding in NetBox (recommended)
|
||||||
|
|
||||||
Under **Plugins → Branding profiles**, admins create design profiles directly in NetBox:
|
Under **Customer Export → Branding Profiles**, admins create design profiles directly in NetBox:
|
||||||
|
|
||||||
- name, company name, footer and **logo upload** (PNG/JPG)
|
- name, company name, footer and **logo upload** (PNG/JPG)
|
||||||
- colours via colour picker: primary, accent, table header text, labels, zebra stripes
|
- colours via colour picker: primary, accent, table header text, labels, zebra stripes
|
||||||
@@ -257,13 +257,16 @@ style of Cisco Packet Tracer:
|
|||||||
- Links come from NetBox **cable paths**; paths through patch panels are traced to the end device.
|
- Links come from NetBox **cable paths**; paths through patch panels are traced to the end device.
|
||||||
- The top-to-bottom layout follows the cabling: provider → firewall/router → core → access → end devices, with ordering optimised for as few crossings as possible.
|
- The top-to-bottom layout follows the cabling: provider → firewall/router → core → access → end devices, with ordering optimised for as few crossings as possible.
|
||||||
- Lines are routed **orthogonally** on bus bars, coloured per upstream device. Port names sit at the target device; multiple uplinks are drawn thicker and marked "2×".
|
- Lines are routed **orthogonally** on bus bars, coloured per upstream device. Port names sit at the target device; multiple uplinks are drawn thicker and marked "2×".
|
||||||
- **Scope**: *entire network* (one page per site) and/or *per rack* (one page per rack). In the rack view, directly connected devices outside the rack appear faded and dashed, with their rack.
|
- **Scope**: *entire network* (one page per site), *location overview* and/or *per rack* (one page per rack). In the rack view, directly connected devices outside the rack appear faded and dashed, with their rack.
|
||||||
|
- The **location overview** draws one diagram per site with the **locations as nodes** (server room, halls, sub-distributions …). Lines are the physical cables between locations, labelled with count and cable type (e.g. `2× SMF, 4× CAT6a`), so you can follow the cabling from the server room to the last sub-distribution. Locations containing firewalls, routers or core switches are placed at the top; each node shows its parent location and the number of racks and devices. Devices without a location (e.g. radio bridges on the roof) are grouped in a node for their site ("without location").
|
||||||
|
- The **cross-site location overview** puts all locations of all sites in scope into **one diagram**; each node shows its site (and parent location), so you can see how buildings and their locations are connected to each other.
|
||||||
- Each topology gets its **own landscape page** (PDF and Word) and is scaled as large as possible.
|
- Each topology gets its **own landscape page** (PDF and Word) and is scaled as large as possible.
|
||||||
- Provider circuits appear as a cloud, devices of other sites dashed (can be disabled).
|
- Provider circuits appear as a cloud, devices of other sites dashed (can be disabled).
|
||||||
|
- **Wireless links** (NetBox *Wireless links*, e.g. point-to-point radio bridges) appear as blue dotted lines labelled "Wireless", in the network view as well as in the location overviews.
|
||||||
- Selectable labels: management IP, model, ports on links.
|
- Selectable labels: management IP, model, ports on links.
|
||||||
- Device names longer than 15 characters are wrapped, preferably at `-`, `_`, `.` or spaces.
|
- Device names longer than 15 characters are wrapped, preferably at `-`, `_`, `.` or spaces.
|
||||||
|
|
||||||
**Symbols** (menu **Plugins → Topology symbols**, or the "Topology symbol"
|
**Symbols** (menu **Customer Export → Topology Symbols**, or the "Topology symbol"
|
||||||
button on device type and device role pages):
|
button on device type and device role pages):
|
||||||
|
|
||||||
1. per **device type**: choose a built-in symbol or **upload a custom icon** (PNG/JPG, ideally transparent)
|
1. per **device type**: choose a built-in symbol or **upload a custom icon** (PNG/JPG, ideally transparent)
|
||||||
@@ -271,7 +274,7 @@ button on device type and device role pages):
|
|||||||
3. otherwise **automatic**, first by role, then by model and manufacturer
|
3. otherwise **automatic**, first by role, then by model and manufacturer
|
||||||
|
|
||||||
Built-in symbols: internet/provider, modem/NTU, firewall, router, layer-3
|
Built-in symbols: internet/provider, modem/NTU, firewall, router, layer-3
|
||||||
switch, switch, radio link, WLAN controller, PoE injector, access point, server,
|
switch, switch, radio link, patch panel, WLAN controller, PoE injector, access point, server,
|
||||||
storage/SAN, NAS, tape library, UPS/ATS, PBX, IP phone, PC/client, printer,
|
storage/SAN, NAS, tape library, UPS/ATS, PBX, IP phone, PC/client, printer,
|
||||||
camera and "other".
|
camera and "other".
|
||||||
|
|
||||||
@@ -306,6 +309,40 @@ slot, status, type, model, size, serial number, firmware, RAID group, optionally
|
|||||||
expired/expiring soon, too old – thresholds from the Utilities configuration). Removed disks (history) are not shown.
|
expired/expiring soon, too old – thresholds from the Utilities configuration). Removed disks (history) are not shown.
|
||||||
Without the plugin the section stays empty.
|
Without the plugin the section stays empty.
|
||||||
|
|
||||||
|
### Floor plans (NetBox-FloorPlan)
|
||||||
|
|
||||||
|
If [NetBox-FloorPlan](https://git.mrblake.cc/MrBlake/NetBox-FloorPlan2.0) (`netbox_floorplanner`) is installed, the
|
||||||
|
**Floor plans** section (off by default) shows every floor plan in scope (site, location, or – for tenants – plans of the
|
||||||
|
tenant or containing its racks/devices) as a full-width drawing with room size, the background image (JPEG/PNG), and a
|
||||||
|
table of the placed racks and devices. The plugin is optional and never imported directly; without it the section stays empty.
|
||||||
|
For Word the drawing is converted with cairosvg, otherwise a simplified Pillow rendering is used.
|
||||||
|
|
||||||
|
### Rack photos
|
||||||
|
|
||||||
|
Images attached to racks in NetBox (*Attach an image*) show up as thumbnails in the
|
||||||
|
**Rack photos** card of the export form, grouped by rack. Selected photos are
|
||||||
|
placed in an appendix at the end of the document. Below each rack elevation a link
|
||||||
|
points to that rack's photos, and each appendix entry links back to the rack. Photos
|
||||||
|
are rotated according to EXIF and scaled down to 1600 px. In Word the links are internal
|
||||||
|
hyperlinks to bookmarks.
|
||||||
|
|
||||||
|
### Virtualization clusters
|
||||||
|
|
||||||
|
The **Virtualization clusters** section (off by default) lists every cluster with hosts
|
||||||
|
or VMs in scope: an overview table, then per cluster type, group, status, tenant and the
|
||||||
|
summed vCPU, RAM and disk of its VMs, plus a host table with VMs, vCPU and RAM per host.
|
||||||
|
Only VMs inside the export scope are counted, so a tenant export does not reveal other
|
||||||
|
tenants' VMs on a shared cluster.
|
||||||
|
|
||||||
|
### CPU & RAM (Netbox-Utilities)
|
||||||
|
|
||||||
|
If [Netbox-Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities) with CPU & RAM is installed:
|
||||||
|
|
||||||
|
- Device tables offer the columns **CPU** (model, count, cores/threads) and **RAM** (total, modules, type and speed).
|
||||||
|
- The **Virtualization clusters** section adds the physical cores/threads and RAM of the hosts and shows the overcommitment: vCPU per physical core (e.g. `2,6 : 1`) and assigned VM RAM as a percentage of host RAM, per cluster and per host.
|
||||||
|
|
||||||
|
RAM is shown in binary units like in Netbox-Utilities (1 GB = 1024 MB), so VM and host values are comparable. Without the plugin the columns stay empty and the cluster section shows VM totals only.
|
||||||
|
|
||||||
### Rack elevations
|
### Rack elevations
|
||||||
|
|
||||||
By default the plugin uses NetBox's own `dcim.svg.RackElevationSVG` in-process
|
By default the plugin uses NetBox's own `dcim.svg.RackElevationSVG` in-process
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ class CustomerExportConfig(PluginConfig):
|
|||||||
name = "netbox_customer_export"
|
name = "netbox_customer_export"
|
||||||
verbose_name = _("Customer Export")
|
verbose_name = _("Customer Export")
|
||||||
description = _("Export customer documentation as PDF or Word")
|
description = _("Export customer documentation as PDF or Word")
|
||||||
version = "0.11.0"
|
version = "0.19.1"
|
||||||
author = "Claude"
|
author = "Claude"
|
||||||
base_url = "customer-export"
|
base_url = "customer-export"
|
||||||
min_version = "4.6.8"
|
min_version = "4.6.8"
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ EMPTY = "—"
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Block:
|
class Block:
|
||||||
kind: str # heading | paragraph | table | kv | images | pagebreak
|
kind: str # heading | paragraph | ref | table | kv | images | pagebreak | landscape
|
||||||
level: int = 0
|
level: int = 0
|
||||||
text: str = ""
|
text: str = ""
|
||||||
headers: list = field(default_factory=list)
|
headers: list = field(default_factory=list)
|
||||||
@@ -48,6 +48,11 @@ def P(text):
|
|||||||
return Block("paragraph", text=str(text))
|
return Block("paragraph", text=str(text))
|
||||||
|
|
||||||
|
|
||||||
|
def REF(text, target, prefix=""):
|
||||||
|
"""Interner Verweis auf eine Überschrift (target = deren anchor); prefix bleibt unverlinkt."""
|
||||||
|
return Block("ref", text=str(text), anchor=target, rows=[prefix])
|
||||||
|
|
||||||
|
|
||||||
def T(headers, rows):
|
def T(headers, rows):
|
||||||
return Block("table", headers=[str(h) for h in headers], rows=[[fmt(c) for c in r] for r in rows])
|
return Block("table", headers=[str(h) for h in headers], rows=[[fmt(c) for c in r] for r in rows])
|
||||||
|
|
||||||
@@ -57,18 +62,20 @@ def KV(pairs, skip_empty=True):
|
|||||||
return Block("kv", rows=rows)
|
return Block("kv", rows=rows)
|
||||||
|
|
||||||
|
|
||||||
def IMAGES(images, wide=False):
|
def IMAGES(images, wide=False, photos=False):
|
||||||
"""images: Liste von (svg_string oder None, caption, png_bytes_oder_None)."""
|
"""images: Liste von (svg_string oder None, caption, png_bytes_oder_None). Statt PNG geht auch JPEG."""
|
||||||
out = []
|
out = []
|
||||||
for svg, caption, png in images:
|
for svg, caption, png in images:
|
||||||
if svg:
|
if svg:
|
||||||
data_uri = "data:image/svg+xml;base64," + base64.b64encode(svg.encode("utf-8")).decode("ascii")
|
data_uri = "data:image/svg+xml;base64," + base64.b64encode(svg.encode("utf-8")).decode("ascii")
|
||||||
elif png:
|
elif png:
|
||||||
data_uri = "data:image/png;base64," + base64.b64encode(png).decode("ascii")
|
mime = "image/jpeg" if png[:2] == bytes((0xFF, 0xD8)) else "image/png"
|
||||||
|
data_uri = f"data:{mime};base64," + base64.b64encode(png).decode("ascii")
|
||||||
else:
|
else:
|
||||||
continue
|
continue
|
||||||
out.append({"svg": svg, "png": png, "caption": caption, "data_uri": data_uri})
|
out.append({"svg": svg, "png": png, "caption": caption, "data_uri": data_uri})
|
||||||
return Block("images", images=out, level=1 if wide else 0) # level=1: volle Seitenbreite
|
# level=1: volle Seitenbreite, level=2: Fotos (zwei je Zeile)
|
||||||
|
return Block("images", images=out, level=2 if photos else 1 if wide else 0)
|
||||||
|
|
||||||
|
|
||||||
def LANDSCAPE(headings, png):
|
def LANDSCAPE(headings, png):
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ def disk_blocks(scope, opts):
|
|||||||
by_device.setdefault(disk.device, []).append(disk)
|
by_device.setdefault(disk.device, []).append(disk)
|
||||||
|
|
||||||
show_installed = bool(opts.get("disk_install_date"))
|
show_installed = bool(opts.get("disk_install_date"))
|
||||||
headers = [_("Slot"), _("Status"), _("Type"), _("Manufacturer / model"), _("Size"), _("Serial number"), _("Firmware"), "RAID"]
|
headers = [_("Slot"), _("Status"), _("Disk"), _("Size"), _("Serial number"), "RAID"]
|
||||||
headers += [_("Installed")] * show_installed + [_("Warranty until"), _("Notes")]
|
headers += [_("Installed")] * show_installed + [_("Warranty until"), _("Notes")]
|
||||||
blocks = []
|
blocks = []
|
||||||
for device, items in by_device.items():
|
for device, items in by_device.items():
|
||||||
@@ -91,12 +91,13 @@ def disk_blocks(scope, opts):
|
|||||||
row = [
|
row = [
|
||||||
_slot(d),
|
_slot(d),
|
||||||
d.get_status_display(),
|
d.get_status_display(),
|
||||||
" / ".join(x for x in (d.get_disk_type_display(), d.get_interface_display()) if x),
|
"\n".join(x for x in (
|
||||||
" ".join(x for x in (d.manufacturer, d.model) if x),
|
" ".join(x for x in (d.manufacturer, d.model) if x),
|
||||||
|
" / ".join(x for x in (d.get_disk_type_display(), d.get_interface_display()) if x),
|
||||||
|
) if x),
|
||||||
fmt(d.capacity_gb) if d.capacity_gb else None,
|
fmt(d.capacity_gb) if d.capacity_gb else None,
|
||||||
d.serial,
|
"\n".join(x for x in (d.serial, f"FW {d.firmware}" if d.firmware else "") if x),
|
||||||
d.firmware,
|
d.raid_group.name if d.raid_group_id else None,
|
||||||
d.raid_group,
|
|
||||||
]
|
]
|
||||||
if show_installed:
|
if show_installed:
|
||||||
row.append(_date(getattr(d, "install_date", None)))
|
row.append(_date(getattr(d, "install_date", None)))
|
||||||
|
|||||||
@@ -0,0 +1,278 @@
|
|||||||
|
"""Raumpläne aus dem Plugin NetBox-FloorPlan (netbox_floorplanner.FloorPlan / FloorPlanItem).
|
||||||
|
|
||||||
|
Optional: Ohne das Plugin liefert ``is_installed()`` False und der Abschnitt bleibt leer.
|
||||||
|
Es wird nichts aus ``netbox_floorplanner`` importiert, Modelle kommen nur über die App-Registry.
|
||||||
|
Das SVG ist eigenständig (feste Farben, eingebettetes Hintergrundbild), damit es in PDF und Word
|
||||||
|
(cairosvg) gleich aussieht; für Word ohne cairosvg gibt es ein vereinfachtes Pillow-PNG.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import math
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.db.models import Q
|
||||||
|
from django.utils.html import escape
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
|
from .blocks import H, IMAGES, KV, P, T
|
||||||
|
|
||||||
|
APP = "netbox_floorplanner"
|
||||||
|
|
||||||
|
TYPE_COLORS = {
|
||||||
|
"area": "#22c55e", "wall": "#475569", "door": "#b45309", "window": "#0ea5e9", "column": "#64748b",
|
||||||
|
"rack": "#3b82f6", "device": "#8b5cf6", "cooling": "#06b6d4", "power": "#f59e0b", "label": "#334155",
|
||||||
|
}
|
||||||
|
FILLED = ("rack", "device", "cooling", "power")
|
||||||
|
FLOOR, WALL, MUTED = "#ffffff", "#334155", "#6c757d"
|
||||||
|
|
||||||
|
|
||||||
|
def is_installed():
|
||||||
|
if not apps.is_installed(APP):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
apps.get_model(APP, "FloorPlan")
|
||||||
|
apps.get_model(APP, "FloorPlanItem")
|
||||||
|
except LookupError:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _models():
|
||||||
|
return apps.get_model(APP, "FloorPlan"), apps.get_model(APP, "FloorPlanItem")
|
||||||
|
|
||||||
|
|
||||||
|
def floorplans(scope):
|
||||||
|
"""Raumpläne im Scope. Mandanten: Pläne des Mandanten oder mit dessen Racks/Geräten."""
|
||||||
|
FloorPlan, _ = _models()
|
||||||
|
if scope.kind == "site":
|
||||||
|
q = Q(site=scope.obj)
|
||||||
|
elif scope.kind == "location":
|
||||||
|
q = Q(location__in=scope.locations)
|
||||||
|
else:
|
||||||
|
q = Q(tenant__in=scope.tenants) | Q(items__rack__tenant__in=scope.tenants) | Q(items__device__tenant__in=scope.tenants)
|
||||||
|
qs = FloorPlan.objects.filter(q).distinct().select_related("site", "location", "tenant")
|
||||||
|
return scope.restrict(qs).order_by("site__name", "location__name", "name")
|
||||||
|
|
||||||
|
|
||||||
|
def meters(cm):
|
||||||
|
return f"{cm / 100:.2f}".rstrip("0").rstrip(".").replace(".", ",")
|
||||||
|
|
||||||
|
|
||||||
|
def _items(plan):
|
||||||
|
_, Item = _models()
|
||||||
|
return list(Item.objects.filter(floorplan=plan).select_related("rack", "device").order_by("z_index", "pk"))
|
||||||
|
|
||||||
|
|
||||||
|
def _text(item):
|
||||||
|
return item.label or (item.rack.name if item.rack_id else item.device.name if item.device_id else "")
|
||||||
|
|
||||||
|
|
||||||
|
def _shade(hex_color, f=0.7):
|
||||||
|
try:
|
||||||
|
n = int(hex_color.lstrip("#"), 16)
|
||||||
|
except ValueError:
|
||||||
|
return hex_color
|
||||||
|
return "#{:02x}{:02x}{:02x}".format(*(round(((n >> s) & 255) * f) for s in (16, 8, 0)))
|
||||||
|
|
||||||
|
|
||||||
|
def _color(item):
|
||||||
|
c = item.color or TYPE_COLORS.get(item.item_type, "#868e96")
|
||||||
|
return c if len(c) == 7 and c.startswith("#") else "#868e96"
|
||||||
|
|
||||||
|
|
||||||
|
# --- SVG ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _item_svg(item):
|
||||||
|
x, y, w, h, t = item.x, item.y, item.width, item.height, item.item_type
|
||||||
|
cx, cy = x + w / 2, y + h / 2
|
||||||
|
color = _color(item)
|
||||||
|
sw = 'stroke-width="3"'
|
||||||
|
parts = []
|
||||||
|
if t == "area":
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="4" fill="{color}" fill-opacity="0.12" stroke="{color}" {sw} stroke-dasharray="12 6"/>')
|
||||||
|
elif t in ("wall", "door"):
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{color}"/>')
|
||||||
|
if t == "door":
|
||||||
|
parts.append(f'<path d="M {x + w} {y} A {w} {w} 0 0 0 {x} {y - w} L {x} {y}" fill="{color}" fill-opacity="0.08" stroke="{color}" stroke-width="2" stroke-dasharray="6 4"/>')
|
||||||
|
elif t == "window":
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{FLOOR}" stroke="{color}" {sw}/>')
|
||||||
|
elif t == "column":
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{color}" fill-opacity="0.35" stroke="{color}" {sw}/>'
|
||||||
|
f'<path d="M {x} {y} L {x + w} {y + h} M {x + w} {y} L {x} {y + h}" stroke="{color}" stroke-width="2"/>')
|
||||||
|
elif t in FILLED:
|
||||||
|
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="2" fill="{color}" fill-opacity="0.85" stroke="{_shade(color)}" {sw}/>')
|
||||||
|
if t == "rack":
|
||||||
|
fh = min(h * 0.12, 10)
|
||||||
|
parts.append(f'<rect x="{x}" y="{y + h - fh}" width="{w}" height="{fh}" fill="{_shade(color)}"/>')
|
||||||
|
text = _text(item)
|
||||||
|
if text:
|
||||||
|
fs = max(8, h * 0.6) if t == "label" else max(6, min(h * 0.3, (w * 1.6) / max(len(text), 3), 60))
|
||||||
|
fill = "#ffffff" if t in FILLED else color if t == "label" else _shade(color)
|
||||||
|
anchor, tx, ty = ("start", x + fs * 0.5, y + fs * 1.2) if t == "area" else ("middle", cx, cy)
|
||||||
|
flip = f' transform="rotate(180 {tx} {ty})"' if 90 < item.rotation % 360 <= 270 else ""
|
||||||
|
parts.append(f'<text x="{tx}" y="{ty}" dy="0.35em" font-size="{fs:.1f}" font-weight="bold" text-anchor="{anchor}" fill="{fill}"{flip}>{escape(text)}</text>')
|
||||||
|
transform = f' transform="rotate({item.rotation} {cx} {cy})"' if item.rotation else ""
|
||||||
|
return f'<g{transform}>{"".join(parts)}</g>'
|
||||||
|
|
||||||
|
|
||||||
|
def _background(plan):
|
||||||
|
"""Hintergrundbild als (Bytes, MIME) oder None."""
|
||||||
|
if not plan.background_image:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
with plan.background_image.open("rb") as f:
|
||||||
|
data = f.read()
|
||||||
|
except Exception: # noqa: BLE001 – Datei fehlt o.Ä.: Plan ohne Hintergrund
|
||||||
|
return None
|
||||||
|
mime = "image/jpeg" if data[:2] == b"\xff\xd8" else "image/png" if data[:4] == b"\x89PNG" else "image/webp" if data[8:12] == b"WEBP" else "image/gif"
|
||||||
|
return data, mime
|
||||||
|
|
||||||
|
|
||||||
|
def render_svg(plan, items):
|
||||||
|
width, depth = plan.width, plan.depth
|
||||||
|
fs = max(10, min(max(width, depth) * 0.025, 200))
|
||||||
|
m = fs * 2
|
||||||
|
bg = ""
|
||||||
|
if (b := _background(plan)) and b[1] in ("image/jpeg", "image/png"):
|
||||||
|
uri = f"data:{b[1]};base64," + base64.b64encode(b[0]).decode("ascii")
|
||||||
|
bg = f'<image href="{uri}" xlink:href="{uri}" x="0" y="0" width="{width}" height="{depth}" preserveAspectRatio="none" opacity="{plan.background_opacity / 100}"/>'
|
||||||
|
vw, vh = width + 2 * m, depth + 2 * m
|
||||||
|
px = 1600 / vw # feste Pixelgröße für Renderer ohne viewBox-Skalierung
|
||||||
|
return (
|
||||||
|
f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
|
||||||
|
f'width="{vw * px:.0f}" height="{vh * px:.0f}" viewBox="{-m} {-m} {vw} {vh}" font-family="DejaVu Sans, Arial, sans-serif">'
|
||||||
|
f'<rect x="{-m}" y="{-m}" width="{vw}" height="{vh}" fill="#ffffff"/>'
|
||||||
|
f'<rect x="0" y="0" width="{width}" height="{depth}" fill="{FLOOR}"/>{bg}'
|
||||||
|
f'{"".join(_item_svg(i) for i in items)}'
|
||||||
|
f'<rect x="0" y="0" width="{width}" height="{depth}" fill="none" stroke="{WALL}" stroke-width="{max(4, fs * 0.15):.1f}"/>'
|
||||||
|
f'<text x="{width / 2}" y="{-fs * 0.6}" font-size="{fs:.1f}" text-anchor="middle" fill="{MUTED}">{meters(width)} m</text>'
|
||||||
|
f'<text transform="translate({-fs * 0.6} {depth / 2}) rotate(-90)" font-size="{fs:.1f}" text-anchor="middle" fill="{MUTED}">{meters(depth)} m</text>'
|
||||||
|
f"</svg>"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --- PNG (Pillow, für Word ohne cairosvg) ---------------------------------------
|
||||||
|
|
||||||
|
def _rgb(hex_color):
|
||||||
|
n = int(hex_color.lstrip("#"), 16)
|
||||||
|
return (n >> 16) & 255, (n >> 8) & 255, n & 255
|
||||||
|
|
||||||
|
|
||||||
|
def _mix(rgb, alpha, base=(255, 255, 255)):
|
||||||
|
return tuple(round(c * alpha + b * (1 - alpha)) for c, b in zip(rgb, base))
|
||||||
|
|
||||||
|
|
||||||
|
def render_png(plan, items):
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
from .rack_png import _font
|
||||||
|
|
||||||
|
width, depth = plan.width, plan.depth
|
||||||
|
fs = max(10, min(max(width, depth) * 0.025, 200))
|
||||||
|
m = fs * 2
|
||||||
|
s = 1600 / (width + 2 * m)
|
||||||
|
img = Image.new("RGB", (round((width + 2 * m) * s), round((depth + 2 * m) * s)), "white")
|
||||||
|
if (b := _background(plan)):
|
||||||
|
try:
|
||||||
|
bgi = Image.open(BytesIO(b[0])).convert("RGB").resize((max(1, round(width * s)), max(1, round(depth * s))))
|
||||||
|
img.paste(Image.blend(Image.new("RGB", bgi.size, "white"), bgi, plan.background_opacity / 100), (round(m * s), round(m * s)))
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
def pt(px_, py_):
|
||||||
|
return (px_ + m) * s, (py_ + m) * s
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
x, y, w, h, t = item.x, item.y, item.width, item.height, item.item_type
|
||||||
|
cx, cy = x + w / 2, y + h / 2
|
||||||
|
a = math.radians(item.rotation or 0)
|
||||||
|
|
||||||
|
def rot(px_, py_):
|
||||||
|
dx, dy = px_ - cx, py_ - cy
|
||||||
|
return pt(cx + dx * math.cos(a) - dy * math.sin(a), cy + dx * math.sin(a) + dy * math.cos(a))
|
||||||
|
|
||||||
|
poly = [rot(x, y), rot(x + w, y), rot(x + w, y + h), rot(x, y + h)]
|
||||||
|
c = _rgb(_color(item))
|
||||||
|
if t == "area":
|
||||||
|
d.polygon(poly, fill=_mix(c, 0.12), outline=c, width=2)
|
||||||
|
elif t in ("wall", "door"):
|
||||||
|
d.polygon(poly, fill=c)
|
||||||
|
elif t == "window":
|
||||||
|
d.polygon(poly, fill=(255, 255, 255), outline=c, width=2)
|
||||||
|
elif t == "column":
|
||||||
|
d.polygon(poly, fill=_mix(c, 0.35), outline=c, width=2)
|
||||||
|
d.line([poly[0], poly[2]], fill=c, width=1)
|
||||||
|
d.line([poly[1], poly[3]], fill=c, width=1)
|
||||||
|
elif t in FILLED:
|
||||||
|
d.polygon(poly, fill=_mix(c, 0.85), outline=_rgb(_shade(_color(item))), width=2)
|
||||||
|
text = _text(item)
|
||||||
|
if text:
|
||||||
|
size = max(8, h * 0.6) if t == "label" else max(6, min(h * 0.3, (w * 1.6) / max(len(text), 3), 60))
|
||||||
|
# bei 90°/270° steht der Text quer – dann an der Höhe statt der Breite ausrichten
|
||||||
|
vertical = 45 < (item.rotation or 0) % 180 < 135
|
||||||
|
if vertical and t != "label":
|
||||||
|
size = max(6, min(w * 0.3, (h * 1.6) / max(len(text), 3), 60))
|
||||||
|
fill = (255, 255, 255) if t in FILLED else c if t == "label" else _rgb(_shade(_color(item)))
|
||||||
|
font = _font(max(8, round(size * s)))
|
||||||
|
if t == "area":
|
||||||
|
d.text(rot(x + size * 0.5, y + size * 1.2), text, fill=fill, font=font, anchor="lm")
|
||||||
|
else:
|
||||||
|
d.text(pt(cx, cy), text, fill=fill, font=font, anchor="mm")
|
||||||
|
d.rectangle([pt(0, 0), pt(width, depth)], outline=_rgb(WALL), width=3)
|
||||||
|
font = _font(max(10, round(fs * s)))
|
||||||
|
d.text(pt(width / 2, -fs * 0.6), f"{meters(width)} m", fill=_rgb(MUTED), font=font, anchor="ms")
|
||||||
|
label = Image.new("RGBA", (round(fs * s * 8), round(fs * s * 1.6)), (255, 255, 255, 0))
|
||||||
|
ImageDraw.Draw(label).text((label.width / 2, label.height / 2), f"{meters(depth)} m", fill=_rgb(MUTED), font=font, anchor="mm")
|
||||||
|
label = label.rotate(90, expand=True)
|
||||||
|
lx, ly = pt(-fs * 0.6, depth / 2)
|
||||||
|
img.paste(label, (round(lx - label.width * 0.7), round(ly - label.height / 2)), label)
|
||||||
|
out = BytesIO()
|
||||||
|
img.save(out, "PNG", optimize=True)
|
||||||
|
return out.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
# --- Abschnitt ----------------------------------------------------------------
|
||||||
|
|
||||||
|
def floorplan_blocks(scope, opts):
|
||||||
|
blocks = []
|
||||||
|
for plan in floorplans(scope):
|
||||||
|
items = _items(plan)
|
||||||
|
where = " / ".join(str(x) for x in (plan.site, plan.location) if x)
|
||||||
|
blocks.append(H(2, f"{plan.name} ({where})" if where else plan.name))
|
||||||
|
blocks.append(
|
||||||
|
KV(
|
||||||
|
[
|
||||||
|
(_("Site"), plan.site),
|
||||||
|
(_("Location"), plan.location),
|
||||||
|
(_("Tenant"), plan.tenant),
|
||||||
|
(_("Room size"), f"{meters(plan.width)} × {meters(plan.depth)} m"),
|
||||||
|
(_("Description"), plan.description),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
svg, png, error = None, None, None
|
||||||
|
try:
|
||||||
|
svg = render_svg(plan, items)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
error = f"{type(e).__name__}: {e}"
|
||||||
|
if opts.get("format") == "docx" or not svg:
|
||||||
|
try:
|
||||||
|
png = render_png(plan, items)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
error = f"{error or ''} / PNG: {type(e).__name__}: {e}".strip(" /")
|
||||||
|
if svg or png:
|
||||||
|
blocks.append(IMAGES([(svg, "", png)], wide=True))
|
||||||
|
else:
|
||||||
|
blocks.append(P(_("Floor plan could not be generated: %(error)s") % {"error": error}))
|
||||||
|
placed = [i for i in items if i.rack_id or i.device_id]
|
||||||
|
if placed and opts.get("floorplan_objects", True):
|
||||||
|
rows = []
|
||||||
|
for i in sorted(placed, key=lambda i: _text(i).lower()):
|
||||||
|
obj = i.rack or i.device
|
||||||
|
kind = _("Rack") if i.rack_id else _("Device")
|
||||||
|
rows.append([obj.name or str(obj), kind, i.label if i.label and i.label != obj.name else None])
|
||||||
|
blocks.append(T([_("Name"), _("Type"), _("Label in plan")], rows))
|
||||||
|
if plan.comments:
|
||||||
|
blocks.append(P(plan.comments))
|
||||||
|
return blocks
|
||||||
@@ -67,6 +67,7 @@ class ExportForm(forms.Form):
|
|||||||
)
|
)
|
||||||
rack_devices = forms.BooleanField(required=False, initial=True, label=_("Device list per rack"))
|
rack_devices = forms.BooleanField(required=False, initial=True, label=_("Device list per rack"))
|
||||||
rack_pagebreak = forms.BooleanField(required=False, initial=True, label=_("Page break after each rack"))
|
rack_pagebreak = forms.BooleanField(required=False, initial=True, label=_("Page break after each rack"))
|
||||||
|
rack_photos = forms.MultipleChoiceField(choices=(), required=False, widget=forms.CheckboxSelectMultiple, label=_("Rack photos"))
|
||||||
|
|
||||||
topo_details = forms.MultipleChoiceField(
|
topo_details = forms.MultipleChoiceField(
|
||||||
choices=(("model", _("Model")), ("primary_ip", _("Management IP")), ("ports", _("Ports on links"))),
|
choices=(("model", _("Model")), ("primary_ip", _("Management IP")), ("ports", _("Ports on links"))),
|
||||||
@@ -76,7 +77,12 @@ class ExportForm(forms.Form):
|
|||||||
label=_("Labels"),
|
label=_("Labels"),
|
||||||
)
|
)
|
||||||
topo_scope = forms.MultipleChoiceField(
|
topo_scope = forms.MultipleChoiceField(
|
||||||
choices=(("site", _("Whole network (per site)")), ("rack", _("Per rack"))),
|
choices=(
|
||||||
|
("site", _("Whole network (per site)")),
|
||||||
|
("locations", _("Location overview (connections between locations)")),
|
||||||
|
("locations_all", _("Cross-site location overview (all locations in one diagram)")),
|
||||||
|
("rack", _("Per rack")),
|
||||||
|
),
|
||||||
initial=["site"],
|
initial=["site"],
|
||||||
required=False,
|
required=False,
|
||||||
widget=forms.CheckboxSelectMultiple,
|
widget=forms.CheckboxSelectMultiple,
|
||||||
@@ -109,6 +115,12 @@ class ExportForm(forms.Form):
|
|||||||
elif isinstance(field.widget, forms.TextInput):
|
elif isinstance(field.widget, forms.TextInput):
|
||||||
field.widget.attrs["class"] = "form-control"
|
field.widget.attrs["class"] = "form-control"
|
||||||
self.fields["branding"].choices = [(k, b["name"]) for k, b in get_brandings().items()]
|
self.fields["branding"].choices = [(k, b["name"]) for k, b in get_brandings().items()]
|
||||||
|
self.photo_groups = []
|
||||||
|
if scope is not None:
|
||||||
|
from .rack_photos import grouped
|
||||||
|
|
||||||
|
self.photo_groups = grouped(scope)
|
||||||
|
self.fields["rack_photos"].choices = [(str(a.pk), a.name) for _r, atts in self.photo_groups for a in atts]
|
||||||
if scope is not None:
|
if scope is not None:
|
||||||
role_ids = scope.devices().values("role")
|
role_ids = scope.devices().values("role")
|
||||||
roles = DeviceRole.objects.filter(pk__in=role_ids).order_by("name")
|
roles = DeviceRole.objects.filter(pk__in=role_ids).order_by("name")
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""CPU & RAM aus dem Plugin Netbox-Utilities (netbox_utilities.DeviceHardware)."""
|
||||||
|
from django.apps import apps
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
|
|
||||||
|
def is_installed():
|
||||||
|
if not apps.is_installed("netbox_utilities"):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
apps.get_model("netbox_utilities", "DeviceHardware")
|
||||||
|
except LookupError: # ältere Version ohne CPU & RAM
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def hardware(device):
|
||||||
|
"""DeviceHardware des Geräts oder None (nicht installiert / nicht gepflegt)."""
|
||||||
|
if not is_installed():
|
||||||
|
return None
|
||||||
|
return getattr(device, "netbox_utilities_hardware", None) # RelatedObjectDoesNotExist ist ein AttributeError
|
||||||
|
|
||||||
|
|
||||||
|
def cores_threads(hw):
|
||||||
|
"""(Kerne, Threads) gesamt oder (None, None)."""
|
||||||
|
if not hw or not hw.cpu_id:
|
||||||
|
return None, None
|
||||||
|
return hw.total_cores, hw.total_threads
|
||||||
|
|
||||||
|
|
||||||
|
def format_memory(gigabytes):
|
||||||
|
from netbox_utilities import hardware as helpers
|
||||||
|
|
||||||
|
return helpers.format_memory(gigabytes)
|
||||||
|
|
||||||
|
|
||||||
|
def cpu_text(device):
|
||||||
|
"""„2 × Intel Xeon Gold 6130“ + Zeile „32 Kerne / 64 Threads“."""
|
||||||
|
hw = hardware(device)
|
||||||
|
if not hw or not hw.cpu_id:
|
||||||
|
return None
|
||||||
|
cores, threads = cores_threads(hw)
|
||||||
|
return f"{hw.cpu_display}\n" + _("%(cores)s cores / %(threads)s threads") % {"cores": cores, "threads": threads}
|
||||||
|
|
||||||
|
|
||||||
|
def ram_text(device):
|
||||||
|
"""„384 GB“ + Zeile „12 × 32 GB · DDR4-2666“."""
|
||||||
|
hw = hardware(device)
|
||||||
|
if not hw or not hw.memory_gb:
|
||||||
|
return None
|
||||||
|
detail = hw.memory_detail
|
||||||
|
return f"{format_memory(hw.memory_gb)}\n{detail}" if detail else format_memory(hw.memory_gb)
|
||||||
Binary file not shown.
@@ -73,7 +73,9 @@ msgstr "Anschrift"
|
|||||||
msgid ""
|
msgid ""
|
||||||
"1 Sample Street\n"
|
"1 Sample Street\n"
|
||||||
"Sample City"
|
"Sample City"
|
||||||
msgstr "Musterstraße 1\n12345 Musterstadt"
|
msgstr ""
|
||||||
|
"Musterstraße 1\n"
|
||||||
|
"12345 Musterstadt"
|
||||||
|
|
||||||
#: branding_views.py:77 sections.py:104 sections.py:235 sections.py:237
|
#: branding_views.py:77 sections.py:104 sections.py:235 sections.py:237
|
||||||
#: templates/netbox_customer_export/export.html:100
|
#: templates/netbox_customer_export/export.html:100
|
||||||
@@ -339,12 +341,16 @@ msgstr "PNG oder JPG, erscheint auf dem Deckblatt."
|
|||||||
|
|
||||||
#: forms.py:150
|
#: forms.py:150
|
||||||
msgid ".docx or .dotx: styles, header/footer and margins are applied."
|
msgid ".docx or .dotx: styles, header/footer and margins are applied."
|
||||||
msgstr ".docx oder .dotx: Formatvorlagen, Kopf-/Fußzeile und Ränder werden übernommen."
|
msgstr ""
|
||||||
|
".docx oder .dotx: Formatvorlagen, Kopf-/Fußzeile und Ränder werden "
|
||||||
|
"übernommen."
|
||||||
|
|
||||||
#: forms.py:151
|
#: forms.py:151
|
||||||
msgid ""
|
msgid ""
|
||||||
"Name as shown in Word, e.g. Grid Table 4 – Accent 1. Empty = own colouring."
|
"Name as shown in Word, e.g. Grid Table 4 – Accent 1. Empty = own colouring."
|
||||||
msgstr "Name wie in Word angezeigt, z.B. Gitternetztabelle 4 – Akzent 1. Leer = eigene Einfärbung."
|
msgstr ""
|
||||||
|
"Name wie in Word angezeigt, z.B. Gitternetztabelle 4 – Akzent 1. Leer = "
|
||||||
|
"eigene Einfärbung."
|
||||||
|
|
||||||
#: forms.py:165 models.py:84 models.py:106
|
#: forms.py:165 models.py:84 models.py:106
|
||||||
msgid "Device type"
|
msgid "Device type"
|
||||||
@@ -368,7 +374,9 @@ msgstr "Symbol"
|
|||||||
msgid ""
|
msgid ""
|
||||||
"PNG, JPG or GIF, ideally square with a transparent background. Replaces the "
|
"PNG, JPG or GIF, ideally square with a transparent background. Replaces the "
|
||||||
"selected symbol."
|
"selected symbol."
|
||||||
msgstr "PNG, JPG oder GIF, am besten quadratisch mit transparentem Hintergrund. Ersetzt das gewählte Symbol."
|
msgstr ""
|
||||||
|
"PNG, JPG oder GIF, am besten quadratisch mit transparentem Hintergrund. "
|
||||||
|
"Ersetzt das gewählte Symbol."
|
||||||
|
|
||||||
#: licenses_slm.py:61
|
#: licenses_slm.py:61
|
||||||
msgid "unlimited"
|
msgid "unlimited"
|
||||||
@@ -578,14 +586,17 @@ msgstr "Branding-Profile"
|
|||||||
#, python-format
|
#, python-format
|
||||||
msgid ""
|
msgid ""
|
||||||
"PDF export requires WeasyPrint (pip install weasyprint + Pango): %(error)s"
|
"PDF export requires WeasyPrint (pip install weasyprint + Pango): %(error)s"
|
||||||
msgstr "PDF-Export benötigt WeasyPrint (pip install weasyprint + Pango): %(error)s"
|
msgstr ""
|
||||||
|
"PDF-Export benötigt WeasyPrint (pip install weasyprint + Pango): %(error)s"
|
||||||
|
|
||||||
#: renderers/docx.py:51
|
#: renderers/docx.py:51
|
||||||
#, python-format
|
#, python-format
|
||||||
msgid ""
|
msgid ""
|
||||||
"Word export requires python-docx (pip install python-docx cairosvg): "
|
"Word export requires python-docx (pip install python-docx cairosvg): "
|
||||||
"%(error)s"
|
"%(error)s"
|
||||||
msgstr "Word-Export benötigt python-docx (pip install python-docx cairosvg): %(error)s"
|
msgstr ""
|
||||||
|
"Word-Export benötigt python-docx (pip install python-docx cairosvg): "
|
||||||
|
"%(error)s"
|
||||||
|
|
||||||
#: renderers/docx.py:61
|
#: renderers/docx.py:61
|
||||||
#, python-format
|
#, python-format
|
||||||
@@ -784,7 +795,9 @@ msgstr "Aus Netbox-Utilities (falls installiert)"
|
|||||||
|
|
||||||
#: sections.py:264
|
#: sections.py:264
|
||||||
msgid "Netbox-Utilities with disk management is not installed – see README."
|
msgid "Netbox-Utilities with disk management is not installed – see README."
|
||||||
msgstr "Netbox-Utilities mit Datenträger-Verwaltung ist nicht installiert – siehe README."
|
msgstr ""
|
||||||
|
"Netbox-Utilities mit Datenträger-Verwaltung ist nicht installiert – siehe "
|
||||||
|
"README."
|
||||||
|
|
||||||
#: sections.py:269 sections.py:272
|
#: sections.py:269 sections.py:272
|
||||||
msgid "Power"
|
msgid "Power"
|
||||||
@@ -946,7 +959,9 @@ msgstr "Aus NetBox-SLM oder anderem Lizenz-Plugin"
|
|||||||
#: sections.py:444
|
#: sections.py:444
|
||||||
msgid ""
|
msgid ""
|
||||||
"No license plugin installed (NetBox-SLM or netbox-lifecycle) – see README."
|
"No license plugin installed (NetBox-SLM or netbox-lifecycle) – see README."
|
||||||
msgstr "Kein Lizenz-Plugin installiert (NetBox-SLM oder netbox-lifecycle) – siehe README."
|
msgstr ""
|
||||||
|
"Kein Lizenz-Plugin installiert (NetBox-SLM oder netbox-lifecycle) – siehe "
|
||||||
|
"README."
|
||||||
|
|
||||||
#: sections.py:448 sections.py:452
|
#: sections.py:448 sections.py:452
|
||||||
msgid "Network topology"
|
msgid "Network topology"
|
||||||
@@ -973,7 +988,9 @@ msgstr "Topologie-Symbol für „%(name)s“ gespeichert."
|
|||||||
#, python-format
|
#, python-format
|
||||||
msgid ""
|
msgid ""
|
||||||
"Topology symbol for “%(name)s” deleted – automatic detection applies again."
|
"Topology symbol for “%(name)s” deleted – automatic detection applies again."
|
||||||
msgstr "Topologie-Symbol für „%(name)s“ gelöscht – es gilt wieder die automatische Erkennung."
|
msgstr ""
|
||||||
|
"Topologie-Symbol für „%(name)s“ gelöscht – es gilt wieder die automatische "
|
||||||
|
"Erkennung."
|
||||||
|
|
||||||
#: symbols.py:12
|
#: symbols.py:12
|
||||||
msgid "Internet / provider"
|
msgid "Internet / provider"
|
||||||
@@ -1099,9 +1116,12 @@ msgstr "%(object)s löschen"
|
|||||||
#: templates/netbox_customer_export/branding_delete.html:9
|
#: templates/netbox_customer_export/branding_delete.html:9
|
||||||
#, python-format
|
#, python-format
|
||||||
msgid ""
|
msgid ""
|
||||||
"Do you really want to delete the branding profile <strong>%(object)s</"
|
"Do you really want to delete the branding profile "
|
||||||
"strong>? The profile's logo and Word template will be removed as well."
|
"<strong>%(object)s</strong>? The profile's logo and Word template will be "
|
||||||
msgstr "Soll das Branding-Profil <strong>%(object)s</strong> wirklich gelöscht werden? Logo und Word-Vorlage des Profils werden ebenfalls entfernt."
|
"removed as well."
|
||||||
|
msgstr ""
|
||||||
|
"Soll das Branding-Profil <strong>%(object)s</strong> wirklich gelöscht "
|
||||||
|
"werden? Logo und Word-Vorlage des Profils werden ebenfalls entfernt."
|
||||||
|
|
||||||
#: templates/netbox_customer_export/branding_delete.html:13
|
#: templates/netbox_customer_export/branding_delete.html:13
|
||||||
#: templates/netbox_customer_export/branding_edit.html:77
|
#: templates/netbox_customer_export/branding_edit.html:77
|
||||||
@@ -1162,7 +1182,9 @@ msgstr "Akzent"
|
|||||||
msgid ""
|
msgid ""
|
||||||
"No branding profiles yet. Until then, the settings from "
|
"No branding profiles yet. Until then, the settings from "
|
||||||
"<code>configuration.py</code> apply."
|
"<code>configuration.py</code> apply."
|
||||||
msgstr "Noch keine Branding-Profile angelegt. Bis dahin gelten die Einstellungen aus <code>configuration.py</code>."
|
msgstr ""
|
||||||
|
"Noch keine Branding-Profile angelegt. Bis dahin gelten die Einstellungen aus"
|
||||||
|
" <code>configuration.py</code>."
|
||||||
|
|
||||||
#: templates/netbox_customer_export/document.html:10
|
#: templates/netbox_customer_export/document.html:10
|
||||||
msgid "Page"
|
msgid "Page"
|
||||||
@@ -1184,7 +1206,8 @@ msgstr "Leer = dein Benutzername"
|
|||||||
#: templates/netbox_customer_export/export.html:62
|
#: templates/netbox_customer_export/export.html:62
|
||||||
msgid ""
|
msgid ""
|
||||||
"Applies to management/OOB IPs, VMs, topology, IP networks and IP addresses."
|
"Applies to management/OOB IPs, VMs, topology, IP networks and IP addresses."
|
||||||
msgstr "Gilt für Management-/OOB-IPs, VMs, Topologie, IP-Netze und IP-Adressen."
|
msgstr ""
|
||||||
|
"Gilt für Management-/OOB-IPs, VMs, Topologie, IP-Netze und IP-Adressen."
|
||||||
|
|
||||||
#: templates/netbox_customer_export/export.html:64
|
#: templates/netbox_customer_export/export.html:64
|
||||||
msgid "Options"
|
msgid "Options"
|
||||||
@@ -1229,7 +1252,9 @@ msgstr "Symbole verwalten"
|
|||||||
msgid ""
|
msgid ""
|
||||||
"“Per rack” additionally shows each rack separately; connected devices "
|
"“Per rack” additionally shows each rack separately; connected devices "
|
||||||
"outside appear dashed."
|
"outside appear dashed."
|
||||||
msgstr "„Je Rack“ zeigt zusätzlich jedes Rack einzeln; verbundene Geräte außerhalb erscheinen gestrichelt."
|
msgstr ""
|
||||||
|
"„Je Rack“ zeigt zusätzlich jedes Rack einzeln; verbundene Geräte außerhalb "
|
||||||
|
"erscheinen gestrichelt."
|
||||||
|
|
||||||
#: templates/netbox_customer_export/export.html:158
|
#: templates/netbox_customer_export/export.html:158
|
||||||
msgid "Create document"
|
msgid "Create document"
|
||||||
@@ -1257,7 +1282,10 @@ msgid ""
|
|||||||
"Delete the symbol assignment for <strong>%(label)s %(object)s</strong>? "
|
"Delete the symbol assignment for <strong>%(label)s %(object)s</strong>? "
|
||||||
"Automatic detection applies again afterwards. An uploaded icon will be "
|
"Automatic detection applies again afterwards. An uploaded icon will be "
|
||||||
"removed as well."
|
"removed as well."
|
||||||
msgstr "Soll die Symbol-Zuordnung für <strong>%(label)s %(object)s</strong> gelöscht werden? Danach gilt wieder die automatische Erkennung. Ein hochgeladenes Icon wird ebenfalls entfernt."
|
msgstr ""
|
||||||
|
"Soll die Symbol-Zuordnung für <strong>%(label)s %(object)s</strong> gelöscht"
|
||||||
|
" werden? Danach gilt wieder die automatische Erkennung. Ein hochgeladenes "
|
||||||
|
"Icon wird ebenfalls entfernt."
|
||||||
|
|
||||||
#: templates/netbox_customer_export/symbol_edit.html:4
|
#: templates/netbox_customer_export/symbol_edit.html:4
|
||||||
#, python-format
|
#, python-format
|
||||||
@@ -1276,7 +1304,9 @@ msgstr "Gilt für"
|
|||||||
msgid ""
|
msgid ""
|
||||||
"Select either a device type <em>or</em> a device role. The device type takes"
|
"Select either a device type <em>or</em> a device role. The device type takes"
|
||||||
" precedence."
|
" precedence."
|
||||||
msgstr "Entweder einen Gerätetyp <em>oder</em> eine Geräterolle wählen. Gerätetyp hat Vorrang."
|
msgstr ""
|
||||||
|
"Entweder einen Gerätetyp <em>oder</em> eine Geräterolle wählen. Gerätetyp "
|
||||||
|
"hat Vorrang."
|
||||||
|
|
||||||
#: templates/netbox_customer_export/symbol_edit.html:48
|
#: templates/netbox_customer_export/symbol_edit.html:48
|
||||||
msgid "Custom icon (optional)"
|
msgid "Custom icon (optional)"
|
||||||
@@ -1290,7 +1320,8 @@ msgstr "Aktuelles Icon"
|
|||||||
msgid ""
|
msgid ""
|
||||||
"If no symbol is selected, automatic detection determines the level in the "
|
"If no symbol is selected, automatic detection determines the level in the "
|
||||||
"diagram."
|
"diagram."
|
||||||
msgstr "Ist kein Symbol gewählt, bestimmt die Automatik die Ebene im Diagramm."
|
msgstr ""
|
||||||
|
"Ist kein Symbol gewählt, bestimmt die Automatik die Ebene im Diagramm."
|
||||||
|
|
||||||
#: templates/netbox_customer_export/symbol_list.html:7
|
#: templates/netbox_customer_export/symbol_list.html:7
|
||||||
msgid "Add assignment"
|
msgid "Add assignment"
|
||||||
@@ -1329,7 +1360,10 @@ msgid ""
|
|||||||
"<strong>Automatic</strong> based on role, model and manufacturer, e.g. "
|
"<strong>Automatic</strong> based on role, model and manufacturer, e.g. "
|
||||||
"“Switch”, “Firewall”, “Sophos”, “Access Point”. Patch panels, power strips, "
|
"“Switch”, “Firewall”, “Sophos”, “Access Point”. Patch panels, power strips, "
|
||||||
"PDUs and UPSs are hidden automatically."
|
"PDUs and UPSs are hidden automatically."
|
||||||
msgstr "<strong>Automatisch</strong> anhand von Rolle, Modell und Hersteller, z.B. „Switch“, „Firewall“, „Sophos“, „Access Point“. Patchpanels, Steckdosenleisten, PDUs und USVs werden automatisch ausgeblendet."
|
msgstr ""
|
||||||
|
"<strong>Automatisch</strong> anhand von Rolle, Modell und Hersteller, z.B. "
|
||||||
|
"„Switch“, „Firewall“, „Sophos“, „Access Point“. Patchpanels, "
|
||||||
|
"Steckdosenleisten, PDUs und USVs werden automatisch ausgeblendet."
|
||||||
|
|
||||||
#: templates/netbox_customer_export/symbol_list.html:44
|
#: templates/netbox_customer_export/symbol_list.html:44
|
||||||
msgid "Built-in symbols"
|
msgid "Built-in symbols"
|
||||||
@@ -1339,3 +1373,184 @@ msgstr "Eingebaute Symbole"
|
|||||||
#, python-format
|
#, python-format
|
||||||
msgid "Rack %(name)s (%(where)s)"
|
msgid "Rack %(name)s (%(where)s)"
|
||||||
msgstr "Rack %(name)s (%(where)s)"
|
msgstr "Rack %(name)s (%(where)s)"
|
||||||
|
|
||||||
|
msgid "%(cores)s cores / %(threads)s threads"
|
||||||
|
msgstr "%(cores)s Kerne / %(threads)s Threads"
|
||||||
|
|
||||||
|
msgid "Appendix rack photos – rack %(name)s"
|
||||||
|
msgstr "Anhang Rack-Fotos – Rack %(name)s"
|
||||||
|
|
||||||
|
msgid "Appendix: rack photos"
|
||||||
|
msgstr "Anhang: Rack-Fotos"
|
||||||
|
|
||||||
|
msgid "Back to rack elevation"
|
||||||
|
msgstr "Zurück zur Rack-Ansicht"
|
||||||
|
|
||||||
|
msgid "CPU"
|
||||||
|
msgstr "CPU"
|
||||||
|
|
||||||
|
msgid "Cable"
|
||||||
|
msgstr "Kabel"
|
||||||
|
|
||||||
|
msgid "Cluster %(name)s"
|
||||||
|
msgstr "Cluster %(name)s"
|
||||||
|
|
||||||
|
msgid "Cores / threads (hosts)"
|
||||||
|
msgstr "Kerne / Threads (Hosts)"
|
||||||
|
|
||||||
|
msgid "Disk"
|
||||||
|
msgstr "Datenträger"
|
||||||
|
|
||||||
|
msgid "Floor plan could not be generated: %(error)s"
|
||||||
|
msgstr "Raumplan konnte nicht erzeugt werden: %(error)s"
|
||||||
|
|
||||||
|
msgid "Floor plans"
|
||||||
|
msgstr "Raumpläne"
|
||||||
|
|
||||||
|
msgid "From NetBox-FloorPlan (if installed)"
|
||||||
|
msgstr "Aus NetBox-FloorPlan (falls installiert)"
|
||||||
|
|
||||||
|
msgid "Host"
|
||||||
|
msgstr "Host"
|
||||||
|
|
||||||
|
msgid "Hosts"
|
||||||
|
msgstr "Hosts"
|
||||||
|
|
||||||
|
msgid "Hosts and resources per cluster"
|
||||||
|
msgstr "Hosts und Ressourcen je Cluster"
|
||||||
|
|
||||||
|
msgid "Label in plan"
|
||||||
|
msgstr "Beschriftung im Plan"
|
||||||
|
|
||||||
|
msgid "Location / distribution"
|
||||||
|
msgstr "Lokation / Verteiler"
|
||||||
|
|
||||||
|
msgid "Location overview"
|
||||||
|
msgstr "Lokationsübersicht"
|
||||||
|
|
||||||
|
msgid "Location overview (connections between locations)"
|
||||||
|
msgstr "Lokationsübersicht (Verbindungen zwischen Lokationen)"
|
||||||
|
|
||||||
|
msgid "No disks recorded."
|
||||||
|
msgstr "Keine Datenträger erfasst."
|
||||||
|
|
||||||
|
msgid "No floor plans recorded."
|
||||||
|
msgstr "Keine Raumpläne erfasst."
|
||||||
|
|
||||||
|
msgid ""
|
||||||
|
"No image attachments found on racks in this scope. Photos can be uploaded on"
|
||||||
|
" the rack via <em>Attach an image</em>."
|
||||||
|
msgstr ""
|
||||||
|
"Keine Bildanhänge an Racks in diesem Scope gefunden. Fotos lassen sich am "
|
||||||
|
"Rack über <em>Bild anhängen</em> hochladen."
|
||||||
|
|
||||||
|
msgid "Patch panel / distribution frame"
|
||||||
|
msgstr "Patchfeld / Rangierverteiler"
|
||||||
|
|
||||||
|
msgid "RAM"
|
||||||
|
msgstr "RAM"
|
||||||
|
|
||||||
|
msgid "RAM (hosts)"
|
||||||
|
msgstr "RAM (Hosts)"
|
||||||
|
|
||||||
|
msgid "RAM (total of VMs)"
|
||||||
|
msgstr "RAM (Summe VMs)"
|
||||||
|
|
||||||
|
msgid "RAM of VMs"
|
||||||
|
msgstr "RAM VMs"
|
||||||
|
|
||||||
|
msgid "RAM of VMs / hosts"
|
||||||
|
msgstr "RAM VMs / Hosts"
|
||||||
|
|
||||||
|
msgid "Rack photos"
|
||||||
|
msgstr "Rack-Fotos"
|
||||||
|
|
||||||
|
msgid "Room size"
|
||||||
|
msgstr "Raumgröße"
|
||||||
|
|
||||||
|
msgid ""
|
||||||
|
"Selected photos appear in the appendix at the end of the document; a link to"
|
||||||
|
" them is placed below the rack elevation."
|
||||||
|
msgstr ""
|
||||||
|
"Ausgewählte Fotos erscheinen im Anhang am Dokumentende, unter der jeweiligen"
|
||||||
|
" Rack-Ansicht steht ein Verweis darauf."
|
||||||
|
|
||||||
|
msgid "Storage"
|
||||||
|
msgstr "Speicher"
|
||||||
|
|
||||||
|
msgid "Storage (total)"
|
||||||
|
msgstr "Speicher (Summe)"
|
||||||
|
|
||||||
|
msgid "VMs"
|
||||||
|
msgstr "VMs"
|
||||||
|
|
||||||
|
msgid "VMs active / total"
|
||||||
|
msgstr "VMs aktiv / gesamt"
|
||||||
|
|
||||||
|
msgid "VMs without a fixed host are only included in the cluster totals."
|
||||||
|
msgstr "VMs ohne festen Host sind nur in den Cluster-Summen enthalten."
|
||||||
|
|
||||||
|
msgid "Virtualization clusters"
|
||||||
|
msgstr "Virtualisierungs-Cluster"
|
||||||
|
|
||||||
|
msgid "vCPU"
|
||||||
|
msgstr "vCPU"
|
||||||
|
|
||||||
|
msgid "vCPU (total of VMs)"
|
||||||
|
msgstr "vCPU (Summe VMs)"
|
||||||
|
|
||||||
|
msgid "vCPU / cores"
|
||||||
|
msgstr "vCPU / Kerne"
|
||||||
|
|
||||||
|
msgid "vCPU per core"
|
||||||
|
msgstr "vCPU je Kern"
|
||||||
|
|
||||||
|
msgid ""
|
||||||
|
"“Location overview” shows all locations of a site and the cables between "
|
||||||
|
"them, from the server room to the last sub-distribution. “Cross-site” "
|
||||||
|
"combines all sites in one diagram to show how buildings and their locations "
|
||||||
|
"are connected. “Per rack” shows each rack separately. Connected devices "
|
||||||
|
"outside appear dashed."
|
||||||
|
msgstr ""
|
||||||
|
"„Lokationsübersicht“ zeigt alle Lokationen eines Standorts und die Kabel "
|
||||||
|
"zwischen ihnen, vom Serverraum bis zur letzten Unterverteilung. "
|
||||||
|
"„Standortübergreifend“ fasst alle Standorte in einem Diagramm zusammen, um "
|
||||||
|
"zu sehen, wie Gebäude und ihre Lokationen verbunden sind. „Je Rack“ zeigt "
|
||||||
|
"jedes Rack einzeln. Verbundene Geräte außerhalb erscheinen gestrichelt."
|
||||||
|
|
||||||
|
msgid "%(n)d device"
|
||||||
|
msgid_plural "%(n)d devices"
|
||||||
|
msgstr[0] "%(n)d Gerät"
|
||||||
|
msgstr[1] "%(n)d Geräte"
|
||||||
|
|
||||||
|
msgid "%(n)d photo, see "
|
||||||
|
msgid_plural "%(n)d photos, see "
|
||||||
|
msgstr[0] "%(n)d Foto, siehe "
|
||||||
|
msgstr[1] "%(n)d Fotos, siehe "
|
||||||
|
|
||||||
|
msgid "%(n)d rack"
|
||||||
|
msgid_plural "%(n)d racks"
|
||||||
|
msgstr[0] "%(n)d Rack"
|
||||||
|
msgstr[1] "%(n)d Racks"
|
||||||
|
|
||||||
|
msgid "Cross-site location overview (all locations in one diagram)"
|
||||||
|
msgstr ""
|
||||||
|
"Lokationsübersicht standortübergreifend (alle Lokationen in einem Diagramm)"
|
||||||
|
|
||||||
|
msgid "Cross-site location overview"
|
||||||
|
msgstr "Standortübergreifende Lokationsübersicht"
|
||||||
|
|
||||||
|
msgid "All sites"
|
||||||
|
msgstr "Alle Standorte"
|
||||||
|
|
||||||
|
msgid "Wireless"
|
||||||
|
msgstr "Funk"
|
||||||
|
|
||||||
|
msgid "Export"
|
||||||
|
msgstr "Export"
|
||||||
|
|
||||||
|
msgid "Settings"
|
||||||
|
msgstr "Einstellungen"
|
||||||
|
|
||||||
|
msgid "without location"
|
||||||
|
msgstr "ohne Lokation"
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from netbox.plugins import PluginMenuButton, PluginMenuItem
|
from netbox.plugins import PluginMenu, PluginMenuButton, PluginMenuItem
|
||||||
|
|
||||||
menu_items = (
|
_items = (
|
||||||
PluginMenuItem(
|
PluginMenuItem(
|
||||||
link="plugins:netbox_customer_export:select",
|
link="plugins:netbox_customer_export:select",
|
||||||
link_text=_("Customer Documentation"),
|
link_text=_("Customer Documentation"),
|
||||||
@@ -34,3 +34,13 @@ menu_items = (
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Eigener Eintrag im obersten Navigationsmenü statt unter „Plugins“
|
||||||
|
menu = PluginMenu(
|
||||||
|
label=_("Customer Export"),
|
||||||
|
groups=(
|
||||||
|
(_("Export"), _items[:1]),
|
||||||
|
(_("Settings"), _items[1:]),
|
||||||
|
),
|
||||||
|
icon_class="mdi mdi-file-document-multiple-outline",
|
||||||
|
)
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"""Bildanhänge (extras.ImageAttachment) von Racks: Auswahl im Formular und Anhang am Dokumentende."""
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from dcim.models import Rack
|
||||||
|
from django.contrib.contenttypes.models import ContentType
|
||||||
|
from extras.models import ImageAttachment
|
||||||
|
|
||||||
|
MAX_EDGE = 1600 # px – Handyfotos verkleinern, damit PDF/Word handlich bleiben
|
||||||
|
|
||||||
|
|
||||||
|
def attachments(scope):
|
||||||
|
"""Bildanhänge aller Racks im Scope, die der Benutzer sehen darf – sortiert nach Rack."""
|
||||||
|
racks = {r.pk: r for r in scope.racks().select_related("site", "location")}
|
||||||
|
if not racks:
|
||||||
|
return []
|
||||||
|
qs = (
|
||||||
|
ImageAttachment.objects.restrict(scope.user, "view")
|
||||||
|
.filter(object_type=ContentType.objects.get_for_model(Rack), object_id__in=racks)
|
||||||
|
.order_by("name", "pk")
|
||||||
|
)
|
||||||
|
items = [(racks[a.object_id], a) for a in qs]
|
||||||
|
items.sort(key=lambda x: (str(x[0].site), str(x[0].location or ""), x[0].name))
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def grouped(scope):
|
||||||
|
"""[(rack, [attachment, …]), …] für die Vorschau im Formular."""
|
||||||
|
out = []
|
||||||
|
for rack, att in attachments(scope):
|
||||||
|
if out and out[-1][0] == rack:
|
||||||
|
out[-1][1].append(att)
|
||||||
|
else:
|
||||||
|
out.append((rack, [att]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def caption(att):
|
||||||
|
name = att.name or att.image.name.rsplit("/", 1)[-1]
|
||||||
|
desc = getattr(att, "description", "")
|
||||||
|
return f"{name} – {desc}" if desc else name
|
||||||
|
|
||||||
|
|
||||||
|
def load_jpeg(att):
|
||||||
|
"""Bild drehen (EXIF), verkleinern und als JPEG zurückgeben. None, wenn nicht lesbar."""
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
try:
|
||||||
|
with att.image.open("rb") as f:
|
||||||
|
img = Image.open(BytesIO(f.read()))
|
||||||
|
img = ImageOps.exif_transpose(img)
|
||||||
|
img.thumbnail((MAX_EDGE, MAX_EDGE))
|
||||||
|
if img.mode != "RGB":
|
||||||
|
img = img.convert("RGB")
|
||||||
|
out = BytesIO()
|
||||||
|
img.save(out, "JPEG", quality=85)
|
||||||
|
return out.getvalue()
|
||||||
|
except Exception: # noqa: BLE001 – fehlende/defekte Datei überspringen
|
||||||
|
return None
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import re
|
||||||
import zipfile
|
import zipfile
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
@@ -20,6 +21,11 @@ def _svg_to_png(svg):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _bookmark_name(anchor):
|
||||||
|
"""Word-Textmarken: max. 40 Zeichen, Buchstabe vorne, nur Buchstaben/Ziffern/_."""
|
||||||
|
return ("_ce_" + re.sub(r"\W", "_", anchor))[:40]
|
||||||
|
|
||||||
|
|
||||||
def _load_template(path):
|
def _load_template(path):
|
||||||
"""Öffnet eine .docx/.dotx-Vorlage und leert deren Textkörper (Formatvorlagen, Kopf-/Fußzeile bleiben)."""
|
"""Öffnet eine .docx/.dotx-Vorlage und leert deren Textkörper (Formatvorlagen, Kopf-/Fußzeile bleiben)."""
|
||||||
from docx import Document as Docx
|
from docx import Document as Docx
|
||||||
@@ -140,6 +146,38 @@ def render_docx(doc):
|
|||||||
s.header_distance, s.footer_distance) = portrait_margins
|
s.header_distance, s.footer_distance) = portrait_margins
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
targets = {blk.anchor for blk in doc.blocks if blk.kind == "ref"}
|
||||||
|
bookmark_id = [0]
|
||||||
|
|
||||||
|
def add_bookmark(paragraph, anchor):
|
||||||
|
bookmark_id[0] += 1
|
||||||
|
start = OxmlElement("w:bookmarkStart")
|
||||||
|
start.set(qn("w:id"), str(bookmark_id[0]))
|
||||||
|
start.set(qn("w:name"), _bookmark_name(anchor))
|
||||||
|
end = OxmlElement("w:bookmarkEnd")
|
||||||
|
end.set(qn("w:id"), str(bookmark_id[0]))
|
||||||
|
paragraph._p.insert(1 if paragraph._p.pPr is not None else 0, start)
|
||||||
|
paragraph._p.append(end)
|
||||||
|
|
||||||
|
def add_link(paragraph, text, anchor):
|
||||||
|
link = OxmlElement("w:hyperlink")
|
||||||
|
link.set(qn("w:anchor"), _bookmark_name(anchor))
|
||||||
|
run = OxmlElement("w:r")
|
||||||
|
rpr = OxmlElement("w:rPr")
|
||||||
|
color = OxmlElement("w:color")
|
||||||
|
color.set(qn("w:val"), b["primary_color"])
|
||||||
|
underline = OxmlElement("w:u")
|
||||||
|
underline.set(qn("w:val"), "single")
|
||||||
|
rpr.append(color)
|
||||||
|
rpr.append(underline)
|
||||||
|
run.append(rpr)
|
||||||
|
t = OxmlElement("w:t")
|
||||||
|
t.text = text
|
||||||
|
t.set(qn("xml:space"), "preserve")
|
||||||
|
run.append(t)
|
||||||
|
link.append(run)
|
||||||
|
paragraph._p.append(link)
|
||||||
|
|
||||||
for blk in doc.blocks:
|
for blk in doc.blocks:
|
||||||
if landscape_open and blk.kind != "landscape":
|
if landscape_open and blk.kind != "landscape":
|
||||||
# erst beim nächsten Inhalt zurück ins Hochformat – vermeidet leere Seiten
|
# erst beim nächsten Inhalt zurück ins Hochformat – vermeidet leere Seiten
|
||||||
@@ -169,9 +207,18 @@ def render_docx(doc):
|
|||||||
else:
|
else:
|
||||||
para.add_run().add_picture(BytesIO(png), height=avail_h)
|
para.add_run().add_picture(BytesIO(png), height=avail_h)
|
||||||
elif blk.kind == "heading":
|
elif blk.kind == "heading":
|
||||||
d.add_heading(blk.text, level=min(blk.level, 4))
|
heading = d.add_heading(blk.text, level=min(blk.level, 4))
|
||||||
|
if blk.anchor in targets:
|
||||||
|
add_bookmark(heading, blk.anchor)
|
||||||
elif blk.kind == "paragraph":
|
elif blk.kind == "paragraph":
|
||||||
d.add_paragraph(blk.text)
|
d.add_paragraph(blk.text)
|
||||||
|
elif blk.kind == "ref":
|
||||||
|
para = d.add_paragraph()
|
||||||
|
if blk.rows and blk.rows[0]:
|
||||||
|
para.add_run(blk.rows[0])
|
||||||
|
add_link(para, blk.text, blk.anchor)
|
||||||
|
for r in para.runs:
|
||||||
|
r.font.size = Pt(max(b["font_size"] - 1, 7))
|
||||||
elif blk.kind == "pagebreak":
|
elif blk.kind == "pagebreak":
|
||||||
d.add_page_break()
|
d.add_page_break()
|
||||||
elif blk.kind in ("table", "kv"):
|
elif blk.kind in ("table", "kv"):
|
||||||
@@ -211,8 +258,14 @@ def render_docx(doc):
|
|||||||
cell = t.cell(0, i).paragraphs[0]
|
cell = t.cell(0, i).paragraphs[0]
|
||||||
cell.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
cell.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
if png:
|
if png:
|
||||||
# Topologie: volle Breite; Racks: 7 cm (Höhe skaliert mit der Rackgröße)
|
# Topologie: volle Breite; Fotos: halbe Breite; Racks: 7 cm (Höhe skaliert mit der Rackgröße)
|
||||||
cell.add_run().add_picture(BytesIO(png), width=Cm(16.5 if blk.level == 1 else 7))
|
width = {1: 16.5, 2: 8}.get(blk.level, 7)
|
||||||
|
if blk.level == 2:
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
px_w, px_h = Image.open(BytesIO(png)).size
|
||||||
|
width = min(width, 9 * px_w / px_h) # Hochformat-Fotos auf max. 9 cm Höhe begrenzen
|
||||||
|
cell.add_run().add_picture(BytesIO(png), width=Cm(width))
|
||||||
else:
|
else:
|
||||||
cell.add_run(_("(rack graphic not available)"))
|
cell.add_run(_("(rack graphic not available)"))
|
||||||
cap = t.cell(1, i).paragraphs[0]
|
cap = t.cell(1, i).paragraphs[0]
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from circuits.models import Circuit
|
|||||||
from dcim.models import Device, Location, PowerFeed, Rack, Site
|
from dcim.models import Device, Location, PowerFeed, Rack, Site
|
||||||
from ipam.models import VLAN, VRF, IPAddress, Prefix
|
from ipam.models import VLAN, VRF, IPAddress, Prefix
|
||||||
from tenancy.models import Tenant, TenantGroup
|
from tenancy.models import Tenant, TenantGroup
|
||||||
from virtualization.models import VirtualMachine
|
from virtualization.models import Cluster, VirtualMachine
|
||||||
from wireless.models import WirelessLAN
|
from wireless.models import WirelessLAN
|
||||||
|
|
||||||
SCOPE_MODELS = {
|
SCOPE_MODELS = {
|
||||||
@@ -82,6 +82,12 @@ class Scope:
|
|||||||
def devices(self):
|
def devices(self):
|
||||||
return self._qs(Device, site=("site",), location=("location",))
|
return self._qs(Device, site=("site",), location=("location",))
|
||||||
|
|
||||||
|
def clusters(self):
|
||||||
|
"""Cluster am Scope selbst oder mit Hosts/VMs im Scope."""
|
||||||
|
own = Cluster.objects.filter(self._q(site=("_site",), location=("_location",), tenant=("tenant",)))
|
||||||
|
q = Q(pk__in=own.values("pk")) | Q(pk__in=self.devices().values("cluster")) | Q(pk__in=self.virtual_machines().values("cluster"))
|
||||||
|
return self.restrict(Cluster.objects.filter(q).distinct())
|
||||||
|
|
||||||
def virtual_machines(self):
|
def virtual_machines(self):
|
||||||
return self._qs(
|
return self._qs(
|
||||||
VirtualMachine,
|
VirtualMachine,
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ from itertools import groupby
|
|||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.contrib.contenttypes.models import ContentType
|
from django.contrib.contenttypes.models import ContentType
|
||||||
from django.utils.translation import gettext as _
|
from django.utils.translation import gettext as _
|
||||||
from django.utils.translation import gettext_lazy
|
from django.utils.translation import gettext_lazy, ngettext
|
||||||
from netbox.plugins import get_plugin_config
|
from netbox.plugins import get_plugin_config
|
||||||
|
|
||||||
from .blocks import EMPTY, H, IMAGES, KV, LANDSCAPE, P, PAGEBREAK, T, get
|
from .blocks import EMPTY, H, IMAGES, KV, LANDSCAPE, P, PAGEBREAK, REF, T, get
|
||||||
|
from . import hardware_utilities
|
||||||
from .rack_png import render_rack_png
|
from .rack_png import render_rack_png
|
||||||
from .rack_svg import render_rack_svg
|
from .rack_svg import render_rack_svg
|
||||||
|
|
||||||
@@ -54,10 +55,20 @@ def primary_ips(obj, opts, sep=", "):
|
|||||||
return ip_text([obj.primary_ip4, obj.primary_ip6], opts, sep)
|
return ip_text([obj.primary_ip4, obj.primary_ip6], opts, sep)
|
||||||
|
|
||||||
|
|
||||||
|
def num(value):
|
||||||
|
"""Decimal/float ohne überflüssige Nachkommastellen, deutsches Komma: 245, 2,5."""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = f"{value:f}"
|
||||||
|
if "." in text:
|
||||||
|
text = text.rstrip("0").rstrip(".")
|
||||||
|
return text.replace(".", ",")
|
||||||
|
|
||||||
|
|
||||||
def _rack_pos(d, o=None):
|
def _rack_pos(d, o=None):
|
||||||
if not d.rack:
|
if not d.rack:
|
||||||
return None
|
return None
|
||||||
pos = " / " + _("U %(u)s") % {"u": f"{d.position:g}"} if d.position else ""
|
pos = " / " + _("U %(u)s") % {"u": num(d.position)} if d.position else ""
|
||||||
return f"{d.rack}{pos}"
|
return f"{d.rack}{pos}"
|
||||||
|
|
||||||
|
|
||||||
@@ -73,6 +84,8 @@ DEVICE_COLUMNS = OrderedDict(
|
|||||||
("primary_ip", (gettext_lazy("Management IP"), lambda d, o: primary_ips(d, o))),
|
("primary_ip", (gettext_lazy("Management IP"), lambda d, o: primary_ips(d, o))),
|
||||||
("oob_ip", (gettext_lazy("OOB IP"), lambda d, o: ip_text([d.oob_ip], o))),
|
("oob_ip", (gettext_lazy("OOB IP"), lambda d, o: ip_text([d.oob_ip], o))),
|
||||||
("serial", (gettext_lazy("Serial number"), lambda d, o: d.serial)),
|
("serial", (gettext_lazy("Serial number"), lambda d, o: d.serial)),
|
||||||
|
("cpu", (gettext_lazy("CPU"), lambda d, o: hardware_utilities.cpu_text(d))),
|
||||||
|
("ram", (gettext_lazy("RAM"), lambda d, o: hardware_utilities.ram_text(d))),
|
||||||
("asset_tag", (gettext_lazy("Asset tag"), lambda d, o: d.asset_tag)),
|
("asset_tag", (gettext_lazy("Asset tag"), lambda d, o: d.asset_tag)),
|
||||||
("tenant", (gettext_lazy("Tenant"), lambda d, o: d.tenant)),
|
("tenant", (gettext_lazy("Tenant"), lambda d, o: d.tenant)),
|
||||||
("description", (gettext_lazy("Description"), lambda d, o: d.description)),
|
("description", (gettext_lazy("Description"), lambda d, o: d.description)),
|
||||||
@@ -173,12 +186,14 @@ def racks(scope, opts):
|
|||||||
blocks = [H(1, _("Racks"))]
|
blocks = [H(1, _("Racks"))]
|
||||||
if not qs.exists():
|
if not qs.exists():
|
||||||
return _empty(opts, blocks)
|
return _empty(opts, blocks)
|
||||||
|
photos = _rack_photos(scope, opts)
|
||||||
for site, site_racks in groupby(qs, key=lambda r: r.site):
|
for site, site_racks in groupby(qs, key=lambda r: r.site):
|
||||||
blocks.append(H(2, _("Site %(name)s") % {"name": site}))
|
blocks.append(H(2, _("Site %(name)s") % {"name": site}))
|
||||||
for location, loc_racks in groupby(site_racks, key=lambda r: r.location):
|
for location, loc_racks in groupby(site_racks, key=lambda r: r.location):
|
||||||
blocks.append(H(3, _("Location %(name)s") % {"name": location} if location else _("No location")))
|
blocks.append(H(3, _("Location %(name)s") % {"name": location} if location else _("No location")))
|
||||||
for rack in loc_racks:
|
for rack in loc_racks:
|
||||||
blocks.append(H(4, _("Rack %(name)s") % {"name": rack.name}))
|
rack_heading = H(4, _("Rack %(name)s") % {"name": rack.name})
|
||||||
|
blocks.append(rack_heading)
|
||||||
blocks.append(
|
blocks.append(
|
||||||
KV(
|
KV(
|
||||||
[
|
[
|
||||||
@@ -222,16 +237,56 @@ def racks(scope, opts):
|
|||||||
T(
|
T(
|
||||||
[_("U"), _("Device"), _("Manufacturer / model"), _("Face")],
|
[_("U"), _("Device"), _("Manufacturer / model"), _("Face")],
|
||||||
[
|
[
|
||||||
[f"{d.position:g}" if d.position else EMPTY, d.name, f"{d.device_type.manufacturer} {d.device_type.model}", d.get_face_display() if d.face else EMPTY]
|
[num(d.position) if d.position else EMPTY, d.name, f"{d.device_type.manufacturer} {d.device_type.model}", d.get_face_display() if d.face else EMPTY]
|
||||||
for d in devs
|
for d in devs
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
if rack.pk in photos:
|
||||||
|
blocks += _photo_appendix(opts, rack, rack_heading, photos[rack.pk])
|
||||||
if opts.get("rack_pagebreak"):
|
if opts.get("rack_pagebreak"):
|
||||||
blocks.append(PAGEBREAK())
|
blocks.append(PAGEBREAK())
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
|
def _rack_photos(scope, opts):
|
||||||
|
"""Ausgewählte Bildanhänge je Rack-ID."""
|
||||||
|
selected = set(opts.get("rack_photos") or [])
|
||||||
|
if not selected:
|
||||||
|
return {}
|
||||||
|
from . import rack_photos
|
||||||
|
|
||||||
|
out = {}
|
||||||
|
for rack, att in rack_photos.attachments(scope):
|
||||||
|
if str(att.pk) in selected:
|
||||||
|
out.setdefault(rack.pk, []).append(att)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _photo_appendix(opts, rack, rack_heading, atts):
|
||||||
|
"""Legt die Fotos im Anhang ab (opts["_appendix"]) und liefert den Verweis unter der Rack-Ansicht."""
|
||||||
|
from . import rack_photos
|
||||||
|
|
||||||
|
images = [(None, rack_photos.caption(a), data) for a in atts if (data := rack_photos.load_jpeg(a))]
|
||||||
|
if not images:
|
||||||
|
return []
|
||||||
|
appendix = opts.setdefault("_appendix", [])
|
||||||
|
if not appendix:
|
||||||
|
appendix.append(H(1, _("Appendix: rack photos")))
|
||||||
|
where = " / ".join(str(x) for x in (rack.site, rack.location) if x)
|
||||||
|
heading = H(2, _("Rack %(name)s") % {"name": rack.name} + (f" ({where})" if where else ""))
|
||||||
|
appendix.append(heading)
|
||||||
|
for i in range(0, len(images), 2): # zwei Fotos je Zeile
|
||||||
|
appendix.append(IMAGES(images[i:i + 2], photos=True))
|
||||||
|
appendix.append(REF(_("Back to rack elevation"), rack_heading.anchor, prefix="↑ "))
|
||||||
|
n = len(images)
|
||||||
|
return [REF(
|
||||||
|
_("Appendix rack photos – rack %(name)s") % {"name": rack.name},
|
||||||
|
heading.anchor,
|
||||||
|
prefix=ngettext("%(n)d photo, see ", "%(n)d photos, see ", n) % {"n": n},
|
||||||
|
)]
|
||||||
|
|
||||||
|
|
||||||
@section("devices", gettext_lazy("Devices"), gettext_lazy("Infrastructure"), hint=gettext_lazy("Tables per device role"))
|
@section("devices", gettext_lazy("Devices"), gettext_lazy("Infrastructure"), hint=gettext_lazy("Tables per device role"))
|
||||||
def devices(scope, opts):
|
def devices(scope, opts):
|
||||||
blocks = [H(1, _("Devices"))]
|
blocks = [H(1, _("Devices"))]
|
||||||
@@ -261,11 +316,22 @@ def disks(scope, opts):
|
|||||||
|
|
||||||
blocks = [H(1, _("Disks & RAID"))]
|
blocks = [H(1, _("Disks & RAID"))]
|
||||||
if not disks_utilities.is_installed():
|
if not disks_utilities.is_installed():
|
||||||
return _empty(opts, blocks, _("Netbox-Utilities with disk management is not installed – see README."))
|
return _empty(opts, blocks, _("No disks recorded."))
|
||||||
blocks += disks_utilities.disk_blocks(scope, opts)
|
blocks += disks_utilities.disk_blocks(scope, opts)
|
||||||
return blocks if len(blocks) > 1 else _empty(opts, blocks)
|
return blocks if len(blocks) > 1 else _empty(opts, blocks)
|
||||||
|
|
||||||
|
|
||||||
|
@section("floorplans", gettext_lazy("Floor plans"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("From NetBox-FloorPlan (if installed)"))
|
||||||
|
def floorplans(scope, opts):
|
||||||
|
from . import floorplan
|
||||||
|
|
||||||
|
blocks = [H(1, _("Floor plans"))]
|
||||||
|
if not floorplan.is_installed():
|
||||||
|
return _empty(opts, blocks, _("No floor plans recorded."))
|
||||||
|
blocks += floorplan.floorplan_blocks(scope, opts)
|
||||||
|
return blocks if len(blocks) > 1 else _empty(opts, blocks, _("No floor plans recorded."))
|
||||||
|
|
||||||
|
|
||||||
@section("power", gettext_lazy("Power"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Power panels & feeds"))
|
@section("power", gettext_lazy("Power"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Power panels & feeds"))
|
||||||
def power(scope, opts):
|
def power(scope, opts):
|
||||||
qs = scope.power_feeds().select_related("power_panel", "rack").order_by("power_panel__name", "name")
|
qs = scope.power_feeds().select_related("power_panel", "rack").order_by("power_panel__name", "name")
|
||||||
@@ -281,6 +347,100 @@ def power(scope, opts):
|
|||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
|
def _mb(value):
|
||||||
|
"""MB als lesbare Größe (VM-RAM/-Disk sind in NetBox in MB gespeichert)."""
|
||||||
|
if not value:
|
||||||
|
return EMPTY
|
||||||
|
for unit, size in (("TB", 1024 ** 2), ("GB", 1024)):
|
||||||
|
if value >= size:
|
||||||
|
return f"{value / size:.1f} {unit}".replace(".0 ", " ").replace(".", ",")
|
||||||
|
return f"{value} MB"
|
||||||
|
|
||||||
|
|
||||||
|
def _host_resources(hosts):
|
||||||
|
"""Summe der physischen Kerne, Threads und RAM (GB) aller Hosts mit gepflegter Hardware."""
|
||||||
|
cores = threads = ram = 0
|
||||||
|
for host in hosts:
|
||||||
|
hw = hardware_utilities.hardware(host)
|
||||||
|
c, t = hardware_utilities.cores_threads(hw)
|
||||||
|
cores, threads = cores + (c or 0), threads + (t or 0)
|
||||||
|
ram += (hw.memory_gb or 0) if hw else 0
|
||||||
|
return cores, threads, ram
|
||||||
|
|
||||||
|
|
||||||
|
def _vm_totals(vms):
|
||||||
|
return (
|
||||||
|
sum(vm.vcpus or 0 for vm in vms),
|
||||||
|
sum(vm.memory or 0 for vm in vms),
|
||||||
|
sum(vm.disk or 0 for vm in vms),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@section("clusters", gettext_lazy("Virtualization clusters"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Hosts and resources per cluster"))
|
||||||
|
def clusters(scope, opts):
|
||||||
|
qs = scope.clusters().select_related("type", "group", "tenant").order_by("group__name", "name")
|
||||||
|
blocks = [H(1, _("Virtualization clusters"))]
|
||||||
|
if not qs.exists():
|
||||||
|
return _empty(opts, blocks)
|
||||||
|
vms_by_cluster = {}
|
||||||
|
for vm in scope.virtual_machines().select_related("device"):
|
||||||
|
vms_by_cluster.setdefault(vm.cluster_id, []).append(vm)
|
||||||
|
|
||||||
|
summary, details = [], []
|
||||||
|
for cluster in qs:
|
||||||
|
vms = vms_by_cluster.get(cluster.pk, [])
|
||||||
|
hosts = list(scope.restrict(cluster.devices.all()).select_related("device_type__manufacturer").order_by("name"))
|
||||||
|
vcpu, ram, disk = _vm_totals(vms)
|
||||||
|
active = sum(1 for vm in vms if vm.status == "active")
|
||||||
|
p_cores, p_threads, p_ram = _host_resources(hosts)
|
||||||
|
ram_pct = f" ({round(ram / (p_ram * 1024) * 100)} %)" if ram and p_ram else ""
|
||||||
|
summary.append([
|
||||||
|
cluster.name, cluster.type, len(hosts), f"{active} / {len(vms)}",
|
||||||
|
f"{num(vcpu)} / {p_cores}" if vcpu and p_cores else num(vcpu) if vcpu else EMPTY,
|
||||||
|
f"{_mb(ram)} / {hardware_utilities.format_memory(p_ram)}" if ram and p_ram else _mb(ram),
|
||||||
|
_mb(disk),
|
||||||
|
])
|
||||||
|
|
||||||
|
details.append(H(2, _("Cluster %(name)s") % {"name": cluster.name}))
|
||||||
|
details.append(KV([
|
||||||
|
(_("Type"), cluster.type),
|
||||||
|
(_("Group"), cluster.group),
|
||||||
|
(_("Status"), get(cluster, "status")),
|
||||||
|
(_("Scope"), getattr(cluster, "scope", None)),
|
||||||
|
(_("Tenant"), cluster.tenant),
|
||||||
|
(_("Hosts"), len(hosts)),
|
||||||
|
(_("VMs active / total"), f"{active} / {len(vms)}"),
|
||||||
|
(_("Cores / threads (hosts)"), f"{p_cores} / {p_threads}" if p_cores else None),
|
||||||
|
(_("RAM (hosts)"), hardware_utilities.format_memory(p_ram) if p_ram else None),
|
||||||
|
(_("vCPU (total of VMs)"), num(vcpu) if vcpu else None),
|
||||||
|
(_("vCPU per core"), f"{num(round(float(vcpu) / p_cores, 1))} : 1" if vcpu and p_cores else None),
|
||||||
|
(_("RAM (total of VMs)"), (_mb(ram) + ram_pct) if ram else None),
|
||||||
|
(_("Storage (total)"), _mb(disk) if disk else None),
|
||||||
|
(_("Description"), cluster.description),
|
||||||
|
]))
|
||||||
|
if hosts:
|
||||||
|
rows = []
|
||||||
|
for host in hosts:
|
||||||
|
host_vms = [vm for vm in vms if vm.device_id == host.pk]
|
||||||
|
h_vcpu, h_ram, _h_disk = _vm_totals(host_vms)
|
||||||
|
h_cores, _t, h_pram = _host_resources([host])
|
||||||
|
rows.append([
|
||||||
|
host.name,
|
||||||
|
f"{host.device_type.manufacturer} {host.device_type.model}",
|
||||||
|
hardware_utilities.cpu_text(host),
|
||||||
|
hardware_utilities.format_memory(h_pram) if h_pram else None,
|
||||||
|
len(host_vms) if host_vms else EMPTY,
|
||||||
|
(f"{num(h_vcpu)} ({num(round(float(h_vcpu) / h_cores, 1))} : 1)" if h_cores else num(h_vcpu)) if h_vcpu else EMPTY,
|
||||||
|
(_mb(h_ram) + (f" ({round(h_ram / (h_pram * 1024) * 100)} %)" if h_pram else "")) if h_ram else EMPTY,
|
||||||
|
])
|
||||||
|
details.append(T([_("Host"), _("Manufacturer / model"), _("CPU"), _("RAM"), _("VMs"), _("vCPU"), _("RAM of VMs")], rows))
|
||||||
|
if any(vm.device_id is None for vm in vms):
|
||||||
|
details.append(P(_("VMs without a fixed host are only included in the cluster totals.")))
|
||||||
|
|
||||||
|
blocks.append(T([_("Cluster"), _("Type"), _("Hosts"), _("VMs active / total"), _("vCPU / cores"), _("RAM of VMs / hosts"), _("Storage")], summary))
|
||||||
|
return blocks + details
|
||||||
|
|
||||||
|
|
||||||
@section("vms", gettext_lazy("Virtual machines"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Cluster, resources, IP"))
|
@section("vms", gettext_lazy("Virtual machines"), gettext_lazy("Infrastructure"), default=False, hint=gettext_lazy("Cluster, resources, IP"))
|
||||||
def vms(scope, opts):
|
def vms(scope, opts):
|
||||||
qs = scope.virtual_machines().select_related("cluster", "role", "platform", "primary_ip4", "primary_ip6").order_by("cluster__name", "name")
|
qs = scope.virtual_machines().select_related("cluster", "role", "platform", "primary_ip4", "primary_ip6").order_by("cluster__name", "name")
|
||||||
@@ -447,7 +607,7 @@ def licenses(scope, opts):
|
|||||||
|
|
||||||
@section("topology", gettext_lazy("Network topology"), gettext_lazy("Network"), default=False, hint=gettext_lazy("Diagram with symbols, like Packet Tracer"))
|
@section("topology", gettext_lazy("Network topology"), gettext_lazy("Network"), default=False, hint=gettext_lazy("Diagram with symbols, like Packet Tracer"))
|
||||||
def topology(scope, opts):
|
def topology(scope, opts):
|
||||||
from .topology import build_graphs, render_png
|
from .topology import build_graphs, build_location_graphs, render_png
|
||||||
|
|
||||||
title = H(1, _("Network topology"))
|
title = H(1, _("Network topology"))
|
||||||
scopes = opts.get("topo_scope") or ["site"]
|
scopes = opts.get("topo_scope") or ["site"]
|
||||||
@@ -455,6 +615,11 @@ def topology(scope, opts):
|
|||||||
pages = [] # (Überschriften, Graph) – je eine Querformat-Seite
|
pages = [] # (Überschriften, Graph) – je eine Querformat-Seite
|
||||||
if "site" in scopes:
|
if "site" in scopes:
|
||||||
pages += [([H(2, g.title)], g) for g in build_graphs(scope, opts, per="site")]
|
pages += [([H(2, g.title)], g) for g in build_graphs(scope, opts, per="site")]
|
||||||
|
if "locations" in scopes:
|
||||||
|
locs = build_location_graphs(scope, opts)
|
||||||
|
pages += [(([H(2, _("Location overview"))] if i == 0 else []) + [H(3, g.title)], g) for i, g in enumerate(locs)]
|
||||||
|
if "locations_all" in scopes:
|
||||||
|
pages += [([H(2, _("Cross-site location overview"))], g) for g in build_location_graphs(scope, opts, combined=True)]
|
||||||
if "rack" in scopes:
|
if "rack" in scopes:
|
||||||
racks = build_graphs(scope, opts, per="rack")
|
racks = build_graphs(scope, opts, per="rack")
|
||||||
# Rack-Seiten unter einer gemeinsamen Zwischenüberschrift, Racks selbst eine Ebene tiefer (kürzeres Inhaltsverzeichnis)
|
# Rack-Seiten unter einer gemeinsamen Zwischenüberschrift, Racks selbst eine Ebene tiefer (kürzeres Inhaltsverzeichnis)
|
||||||
|
|||||||
@@ -10,12 +10,14 @@ from django.utils.translation import gettext_lazy as _
|
|||||||
KINDS = OrderedDict(
|
KINDS = OrderedDict(
|
||||||
[
|
[
|
||||||
("cloud", (_("Internet / provider"), 0)),
|
("cloud", (_("Internet / provider"), 0)),
|
||||||
|
("location", (_("Location / distribution"), 3)),
|
||||||
("modem", (_("Modem / NTU / media converter"), 1)),
|
("modem", (_("Modem / NTU / media converter"), 1)),
|
||||||
("firewall", (_("Firewall"), 1)),
|
("firewall", (_("Firewall"), 1)),
|
||||||
("router", (_("Router"), 1)),
|
("router", (_("Router"), 1)),
|
||||||
("l3switch", (_("Layer 3 switch / core"), 2)),
|
("l3switch", (_("Layer 3 switch / core"), 2)),
|
||||||
("switch", (_("Switch"), 3)),
|
("switch", (_("Switch"), 3)),
|
||||||
("radio", (_("Radio link / microwave"), 3)),
|
("radio", (_("Radio link / microwave"), 3)),
|
||||||
|
("patchpanel", (_("Patch panel / distribution frame"), 3)),
|
||||||
("wlc", (_("Wireless controller"), 3)),
|
("wlc", (_("Wireless controller"), 3)),
|
||||||
("poe", (_("PoE injector"), 4)),
|
("poe", (_("PoE injector"), 4)),
|
||||||
("ap", (_("Access point"), 4)),
|
("ap", (_("Access point"), 4)),
|
||||||
@@ -33,7 +35,7 @@ KINDS = OrderedDict(
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
HIDDEN = "hidden"
|
HIDDEN = "hidden"
|
||||||
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k != "cloud"] + [(HIDDEN, _("Hide in topology"))]
|
KIND_CHOICES = [(k, v[0]) for k, v in KINDS.items() if k not in ("cloud", "location")] + [(HIDDEN, _("Hide in topology"))]
|
||||||
|
|
||||||
# Reihenfolge wichtig: erster Treffer gewinnt. None = passiv, nicht zeichnen.
|
# Reihenfolge wichtig: erster Treffer gewinnt. None = passiv, nicht zeichnen.
|
||||||
# Tippvarianten („Acces Point“, „Controler“, „Libary“) sind absichtlich mit abgedeckt.
|
# Tippvarianten („Acces Point“, „Controler“, „Libary“) sind absichtlich mit abgedeckt.
|
||||||
@@ -288,6 +290,23 @@ def _draw_ups(d):
|
|||||||
d.polygon([(62, 70), (50, 88), (58, 88), (54, 102), (70, 82), (62, 82), (68, 70)], fill=(250, 200, 40))
|
d.polygon([(62, 70), (50, 88), (58, 88), (54, 102), (70, 82), (62, 82), (68, 70)], fill=(250, 200, 40))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_patchpanel(d):
|
||||||
|
# flaches 19"-Feld mit zwei Portreihen, bewusst nüchtern (passives Element)
|
||||||
|
_iso_box(d, 8, 58, 104, 92, 14, (96, 104, 114), (150, 158, 168), (74, 82, 92))
|
||||||
|
for row in (64, 78):
|
||||||
|
for i in range(12):
|
||||||
|
d.rectangle([14 + i * 7.5, row, 19 + i * 7.5, row + 7], fill=(40, 46, 54))
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_location(d):
|
||||||
|
# Verteilerschrank mit Glastür und Höheneinheiten – steht in der Übersicht für eine ganze Lokation
|
||||||
|
_iso_box(d, 26, 20, 92, 116, 12, (58, 74, 92), (118, 136, 156), (42, 56, 72))
|
||||||
|
d.rectangle([33, 27, 85, 109], fill=(170, 196, 220), outline=OUTLINE, width=2)
|
||||||
|
for i, y in enumerate(range(33, 101, 11)):
|
||||||
|
d.rectangle([38, y, 80, y + 7], fill=(40, 52, 66))
|
||||||
|
d.ellipse([74, y + 2, 77, y + 5], fill=(60, 200, 90) if i % 2 == 0 else (86, 149, 206))
|
||||||
|
|
||||||
|
|
||||||
def _draw_pbx(d):
|
def _draw_pbx(d):
|
||||||
# Anlage (Box) mit Hörer-Symbol
|
# Anlage (Box) mit Hörer-Symbol
|
||||||
_iso_box(d, 12, 50, 104, 104, 12, (62, 70, 80), (126, 136, 148), (44, 52, 60))
|
_iso_box(d, 12, 50, 104, 104, 12, (62, 70, 80), (126, 136, 148), (44, 52, 60))
|
||||||
@@ -321,6 +340,8 @@ _DRAWERS = {
|
|||||||
"tape": _draw_tape,
|
"tape": _draw_tape,
|
||||||
"ups": _draw_ups,
|
"ups": _draw_ups,
|
||||||
"pbx": _draw_pbx,
|
"pbx": _draw_pbx,
|
||||||
|
"patchpanel": _draw_patchpanel,
|
||||||
|
"location": _draw_location,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -368,6 +389,11 @@ class SymbolResolver:
|
|||||||
pass
|
pass
|
||||||
self._icons = {}
|
self._icons = {}
|
||||||
|
|
||||||
|
def is_hidden(self, device):
|
||||||
|
"""Per Symbolzuordnung ausdrücklich ausgeblendet?"""
|
||||||
|
sym = self.by_type.get(device.device_type_id) or self.by_role.get(device.role_id)
|
||||||
|
return bool(sym and sym.kind == HIDDEN)
|
||||||
|
|
||||||
def resolve(self, device):
|
def resolve(self, device):
|
||||||
"""(kind, icon_png_bytes) oder (None, None), wenn das Gerät nicht gezeichnet wird."""
|
"""(kind, icon_png_bytes) oder (None, None), wenn das Gerät nicht gezeichnet wird."""
|
||||||
sym = self.by_type.get(device.device_type_id) or self.by_role.get(device.role_id)
|
sym = self.by_type.get(device.device_type_id) or self.by_role.get(device.role_id)
|
||||||
|
|||||||
@@ -29,6 +29,7 @@
|
|||||||
table { width: 100%; border-collapse: collapse; margin: 4pt 0 10pt; font-size: 8.5pt; }
|
table { width: 100%; border-collapse: collapse; margin: 4pt 0 10pt; font-size: 8.5pt; }
|
||||||
thead { display: table-header-group; }
|
thead { display: table-header-group; }
|
||||||
th { background: var(--primary); color: var(--head-text); text-align: left; padding: 3pt 5pt; }
|
th { background: var(--primary); color: var(--head-text); text-align: left; padding: 3pt 5pt; }
|
||||||
|
th, td { overflow-wrap: anywhere; }
|
||||||
td { border-bottom: 1px solid #ddd; padding: 3pt 5pt; vertical-align: top; }
|
td { border-bottom: 1px solid #ddd; padding: 3pt 5pt; vertical-align: top; }
|
||||||
tr { page-break-inside: avoid; }
|
tr { page-break-inside: avoid; }
|
||||||
tbody tr:nth-child(even) td { background: var(--stripe); }
|
tbody tr:nth-child(even) td { background: var(--stripe); }
|
||||||
@@ -39,6 +40,11 @@
|
|||||||
.images img { max-height: 190mm; max-width: 80mm; }
|
.images img { max-height: 190mm; max-width: 80mm; }
|
||||||
.images.wide figure { width: 100%; min-width: 0; }
|
.images.wide figure { width: 100%; min-width: 0; }
|
||||||
.images.wide img { width: 100%; height: auto; max-height: 240mm; object-fit: contain; }
|
.images.wide img { width: 100%; height: auto; max-height: 240mm; object-fit: contain; }
|
||||||
|
.images.photos { display: flex; gap: 6mm; justify-content: flex-start; page-break-inside: avoid; }
|
||||||
|
.images.photos figure { width: calc(50% - 3mm); margin: 0 0 6mm; }
|
||||||
|
.images.photos img { width: 100%; height: auto; max-width: none; max-height: 95mm; object-fit: contain; border: 1px solid #ddd; }
|
||||||
|
.ref { font-size: 8.5pt; color: #555; margin: 2pt 0 8pt; }
|
||||||
|
.ref a { color: var(--primary); text-decoration: none; border-bottom: 1px solid currentColor; }
|
||||||
figcaption { font-style: italic; color: #555; }
|
figcaption { font-style: italic; color: #555; }
|
||||||
.footer { position: running(footer); font-size: 7pt; color: #777; }
|
.footer { position: running(footer); font-size: 7pt; color: #777; }
|
||||||
@media screen { .footer { display: none; } }
|
@media screen { .footer { display: none; } }
|
||||||
@@ -73,13 +79,14 @@
|
|||||||
{% if b.kind == 'heading' %}
|
{% if b.kind == 'heading' %}
|
||||||
{% if b.level == 1 %}<h1 id="{{ b.anchor }}">{{ b.text }}</h1>{% elif b.level == 2 %}<h2 id="{{ b.anchor }}">{{ b.text }}</h2>{% elif b.level == 3 %}<h3 id="{{ b.anchor }}">{{ b.text }}</h3>{% else %}<h4 id="{{ b.anchor }}">{{ b.text }}</h4>{% endif %}
|
{% if b.level == 1 %}<h1 id="{{ b.anchor }}">{{ b.text }}</h1>{% elif b.level == 2 %}<h2 id="{{ b.anchor }}">{{ b.text }}</h2>{% elif b.level == 3 %}<h3 id="{{ b.anchor }}">{{ b.text }}</h3>{% else %}<h4 id="{{ b.anchor }}">{{ b.text }}</h4>{% endif %}
|
||||||
{% elif b.kind == 'paragraph' %}<p>{{ b.text|linebreaksbr }}</p>
|
{% elif b.kind == 'paragraph' %}<p>{{ b.text|linebreaksbr }}</p>
|
||||||
|
{% elif b.kind == 'ref' %}<p class="ref">{{ b.rows.0 }}<a href="#{{ b.anchor }}">{{ b.text }}</a></p>
|
||||||
{% elif b.kind == 'table' %}
|
{% elif b.kind == 'table' %}
|
||||||
<table><thead><tr>{% for h in b.headers %}<th>{{ h }}</th>{% endfor %}</tr></thead>
|
<table><thead><tr>{% for h in b.headers %}<th>{{ h }}</th>{% endfor %}</tr></thead>
|
||||||
<tbody>{% for row in b.rows %}<tr>{% for c in row %}<td>{{ c|linebreaksbr }}</td>{% endfor %}</tr>{% endfor %}</tbody></table>
|
<tbody>{% for row in b.rows %}<tr>{% for c in row %}<td>{{ c|linebreaksbr }}</td>{% endfor %}</tr>{% endfor %}</tbody></table>
|
||||||
{% elif b.kind == 'kv' %}
|
{% elif b.kind == 'kv' %}
|
||||||
<table class="kv"><tbody>{% for row in b.rows %}<tr><td>{{ row.0 }}</td><td>{{ row.1|linebreaksbr }}</td></tr>{% endfor %}</tbody></table>
|
<table class="kv"><tbody>{% for row in b.rows %}<tr><td>{{ row.0 }}</td><td>{{ row.1|linebreaksbr }}</td></tr>{% endfor %}</tbody></table>
|
||||||
{% elif b.kind == 'images' %}
|
{% elif b.kind == 'images' %}
|
||||||
<div class="images{% if b.level == 1 %} wide{% endif %}">{% for img in b.images %}<figure><img src="{{ img.data_uri }}" alt="{{ img.caption }}">{% if img.caption %}<figcaption>{{ img.caption }}</figcaption>{% endif %}</figure>{% endfor %}</div>
|
<div class="images{% if b.level == 1 %} wide{% elif b.level == 2 %} photos{% endif %}">{% for img in b.images %}<figure><img src="{{ img.data_uri }}" alt="{{ img.caption }}">{% if img.caption %}<figcaption>{{ img.caption }}</figcaption>{% endif %}</figure>{% endfor %}</div>
|
||||||
{% elif b.kind == 'pagebreak' %}<div class="pagebreak"></div>
|
{% elif b.kind == 'pagebreak' %}<div class="pagebreak"></div>
|
||||||
{% elif b.kind == 'landscape' %}
|
{% elif b.kind == 'landscape' %}
|
||||||
<section class="landscape">
|
<section class="landscape">
|
||||||
|
|||||||
@@ -26,6 +26,13 @@
|
|||||||
.ce-card { transition: opacity .15s; }
|
.ce-card { transition: opacity .15s; }
|
||||||
.ce-actions { position: sticky; bottom: 0; z-index: 10; background: var(--tblr-bg-surface); border-top: 1px solid var(--tblr-border-color); padding: .75rem 1rem; display: flex; justify-content: flex-end; gap: .5rem; }
|
.ce-actions { position: sticky; bottom: 0; z-index: 10; background: var(--tblr-bg-surface); border-top: 1px solid var(--tblr-border-color); padding: .75rem 1rem; display: flex; justify-content: flex-end; gap: .5rem; }
|
||||||
.ce-format .btn { flex: 1; padding-left: .25rem; padding-right: .25rem; }
|
.ce-format .btn { flex: 1; padding-left: .25rem; padding-right: .25rem; }
|
||||||
|
.ce-photos { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: .5rem; }
|
||||||
|
.ce-photo { position: relative; margin: 0; border: 1px solid var(--tblr-border-color); border-radius: .375rem; overflow: hidden; cursor: pointer; background: var(--tblr-bg-surface-secondary); }
|
||||||
|
.ce-photo:has(input:checked) { border-color: var(--tblr-primary); box-shadow: 0 0 0 1px var(--tblr-primary); }
|
||||||
|
.ce-photo img { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; }
|
||||||
|
.ce-photo .form-check-input { position: absolute; top: .4rem; left: .4rem; margin: 0; }
|
||||||
|
.ce-photo span { display: block; padding: .25rem .4rem; font-size: .75rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.ce-photo-rack + .ce-photo-rack { margin-top: .9rem; }
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<form method="post" class="mt-3" id="ce-export-form">
|
<form method="post" class="mt-3" id="ce-export-form">
|
||||||
@@ -132,6 +139,33 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card ce-card mt-3" data-ce-depends="racks">
|
||||||
|
<h2 class="card-header"><i class="mdi mdi-image-multiple-outline"></i> {% trans "Rack photos" %}</h2>
|
||||||
|
<div class="card-body">
|
||||||
|
{% if not rack_photos %}
|
||||||
|
<div class="text-secondary">{% trans "No image attachments found on racks in this scope. Photos can be uploaded on the rack via <em>Attach an image</em>." %}</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="form-text mt-0 mb-3">{% trans "Selected photos appear in the appendix at the end of the document; a link to them is placed below the rack elevation." %}</div>
|
||||||
|
{% for rack, atts in rack_photos %}
|
||||||
|
<div class="ce-photo-rack" data-ce-group>
|
||||||
|
<div class="ce-group-head">
|
||||||
|
<h5>{{ rack.name }} <span class="fw-normal" style="text-transform: none">· {{ rack.site }}{% if rack.location %} / {{ rack.location }}{% endif %}</span></h5>
|
||||||
|
<span><a data-ce-all>{% trans "All" %}</a> · <a data-ce-none>{% trans "None" %}</a></span>
|
||||||
|
</div>
|
||||||
|
<div class="ce-photos">
|
||||||
|
{% for a in atts %}
|
||||||
|
<label class="ce-photo" title="{{ a.name|default:a.image.name }}">
|
||||||
|
<input type="checkbox" class="form-check-input" name="rack_photos" value="{{ a.pk }}"{% if a.pk|stringformat:"s" in form.rack_photos.value %} checked{% endif %}>
|
||||||
|
<img src="{{ a.image.url }}" alt="" loading="lazy">
|
||||||
|
<span>{{ a.name|default:a.image.name }}</span>
|
||||||
|
</label>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="card ce-card mt-3" data-ce-depends="topology">
|
<div class="card ce-card mt-3" data-ce-depends="topology">
|
||||||
<h2 class="card-header d-flex justify-content-between align-items-center">
|
<h2 class="card-header d-flex justify-content-between align-items-center">
|
||||||
<span><i class="mdi mdi-sitemap"></i> {% trans "Topology" %}</span>
|
<span><i class="mdi mdi-sitemap"></i> {% trans "Topology" %}</span>
|
||||||
@@ -142,7 +176,7 @@
|
|||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="ce-label mt-0">{{ form.topo_scope.label }}</div>
|
<div class="ce-label mt-0">{{ form.topo_scope.label }}</div>
|
||||||
{% include 'netbox_customer_export/_pills.html' with field=form.topo_scope %}
|
{% include 'netbox_customer_export/_pills.html' with field=form.topo_scope %}
|
||||||
<div class="form-text mb-2">{% trans "“Per rack” additionally shows each rack separately; connected devices outside appear dashed." %}</div>
|
<div class="form-text mb-2">{% trans "“Location overview” shows all locations of a site and the cables between them, from the server room to the last sub-distribution. “Cross-site” combines all sites in one diagram to show how buildings and their locations are connected. “Per rack” shows each rack separately. Connected devices outside appear dashed." %}</div>
|
||||||
<div class="ce-label">{{ form.topo_details.label }}</div>
|
<div class="ce-label">{{ form.topo_details.label }}</div>
|
||||||
{% include 'netbox_customer_export/_pills.html' with field=form.topo_details %}
|
{% include 'netbox_customer_export/_pills.html' with field=form.topo_details %}
|
||||||
<div class="ce-label">{% trans "More" %}</div>
|
<div class="ce-label">{% trans "More" %}</div>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from dataclasses import dataclass, field
|
|||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
from django.utils.translation import gettext as _
|
from django.utils.translation import gettext as _
|
||||||
|
from django.utils.translation import ngettext
|
||||||
|
|
||||||
from .symbols import KINDS, SymbolResolver, builtin_icon
|
from .symbols import KINDS, SymbolResolver, builtin_icon
|
||||||
|
|
||||||
@@ -19,6 +20,7 @@ class Node:
|
|||||||
icon: bytes
|
icon: bytes
|
||||||
sub: list = field(default_factory=list)
|
sub: list = field(default_factory=list)
|
||||||
external: bool = False # Gerät eines anderen Standorts / Provider
|
external: bool = False # Gerät eines anderen Standorts / Provider
|
||||||
|
tier: int = None # Ebene überschreiben (sonst aus dem Symbol)
|
||||||
row: int = 0 # Zeile im Diagramm (nach Umbruch)
|
row: int = 0 # Zeile im Diagramm (nach Umbruch)
|
||||||
x: float = 0 # Mitte, in Layout-Pixeln
|
x: float = 0 # Mitte, in Layout-Pixeln
|
||||||
y: float = 0 # Oberkante des Symbols, wird beim Zeichnen gesetzt
|
y: float = 0 # Oberkante des Symbols, wird beim Zeichnen gesetzt
|
||||||
@@ -29,6 +31,8 @@ class Edge:
|
|||||||
a: str
|
a: str
|
||||||
b: str
|
b: str
|
||||||
labels: list = field(default_factory=list)
|
labels: list = field(default_factory=list)
|
||||||
|
summary: str = "" # feste Beschriftung statt Port-Namen (z.B. Lokationsübersicht)
|
||||||
|
wireless: bool = False # nur Funkstrecken (WirelessLink) – blau gepunktet
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -87,7 +91,7 @@ def build_graphs(scope, opts, per="site"):
|
|||||||
cache = getattr(scope, "_topology_cache", None)
|
cache = getattr(scope, "_topology_cache", None)
|
||||||
if cache is None:
|
if cache is None:
|
||||||
cache = scope._topology_cache = _collect(scope, opts)
|
cache = scope._topology_cache = _collect(scope, opts)
|
||||||
by_pk, drawn, links, external = cache
|
by_pk, drawn, links, external, wireless = cache
|
||||||
|
|
||||||
groups = OrderedDict()
|
groups = OrderedDict()
|
||||||
for pk in drawn:
|
for pk in drawn:
|
||||||
@@ -127,7 +131,7 @@ def build_graphs(scope, opts, per="site"):
|
|||||||
kind, icon = drawn[d.pk]
|
kind, icon = drawn[d.pk]
|
||||||
other = Node(nid, d.name or str(d), kind, icon, context(d), external=True)
|
other = Node(nid, d.name or str(d), kind, icon, context(d), external=True)
|
||||||
nodes[nid] = Node(**{**other.__dict__})
|
nodes[nid] = Node(**{**other.__dict__})
|
||||||
edges.append(Edge(a, b, labels))
|
edges.append(Edge(a, b, labels, wireless=(a, b) in wireless))
|
||||||
if not opts.get("topo_isolated"):
|
if not opts.get("topo_isolated"):
|
||||||
linked = {n for e in edges for n in (e.a, e.b)}
|
linked = {n for e in edges for n in (e.a, e.b)}
|
||||||
nodes = OrderedDict((k, v) for k, v in nodes.items() if k in linked)
|
nodes = OrderedDict((k, v) for k, v in nodes.items() if k in linked)
|
||||||
@@ -145,6 +149,7 @@ def build_graphs(scope, opts, per="site"):
|
|||||||
def _collect(scope, opts):
|
def _collect(scope, opts):
|
||||||
"""Geräte, Symbole und Verbindungen (Kabelpfade) des Scopes einmalig einlesen."""
|
"""Geräte, Symbole und Verbindungen (Kabelpfade) des Scopes einmalig einlesen."""
|
||||||
from dcim.models import Interface
|
from dcim.models import Interface
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
resolver = SymbolResolver()
|
resolver = SymbolResolver()
|
||||||
devices = list(
|
devices = list(
|
||||||
@@ -159,11 +164,12 @@ def _collect(scope, opts):
|
|||||||
drawn[d.pk] = (kind, icon)
|
drawn[d.pk] = (kind, icon)
|
||||||
by_pk = {d.pk: d for d in devices}
|
by_pk = {d.pk: d for d in devices}
|
||||||
|
|
||||||
# Verbindungen: vollständige Kabelpfade (auch über Patchpanels) zwischen Interfaces
|
# Verbindungen: vollständige Kabelpfade (auch über Patchpanels) und Funkstrecken zwischen Interfaces
|
||||||
links = defaultdict(list) # (a, b) -> ["Gi1/0/1 – eth0", …]
|
links = defaultdict(list) # (a, b) -> ["Gi1/0/1 – eth0", …]
|
||||||
|
kinds = defaultdict(set) # (a, b) -> {"cable", "wireless"}
|
||||||
external = {} # node_id -> Node-Vorlage
|
external = {} # node_id -> Node-Vorlage
|
||||||
ifaces = scope.restrict(
|
ifaces = scope.restrict(
|
||||||
Interface.objects.filter(device_id__in=list(drawn), cable__isnull=False)
|
Interface.objects.filter(Q(cable__isnull=False) | Q(wireless_link__isnull=False), device_id__in=list(drawn))
|
||||||
).select_related("device")
|
).select_related("device")
|
||||||
for iface in ifaces:
|
for iface in ifaces:
|
||||||
try:
|
try:
|
||||||
@@ -204,8 +210,159 @@ def _collect(scope, opts):
|
|||||||
label = " – ".join(reversed(label.split(" – ")))
|
label = " – ".join(reversed(label.split(" – ")))
|
||||||
if label not in links[key]:
|
if label not in links[key]:
|
||||||
links[key].append(label)
|
links[key].append(label)
|
||||||
|
kinds[key].add("cable" if iface.cable_id else "wireless")
|
||||||
|
|
||||||
return by_pk, drawn, links, external
|
wireless = {k for k, v in kinds.items() if v == {"wireless"}}
|
||||||
|
return by_pk, drawn, links, external, wireless
|
||||||
|
|
||||||
|
|
||||||
|
def build_location_graphs(scope, opts, combined=False):
|
||||||
|
"""Lokationsübersicht: ein Graph je Standort, Knoten = Lokationen, Linien = Kabel zwischen Lokationen.
|
||||||
|
|
||||||
|
Mit `combined=True` entsteht ein einziger standortübergreifender Graph über alle Lokationen im Scope, an
|
||||||
|
jedem Knoten steht der Standort – so sieht man, wie Gebäude und ihre Lokationen untereinander verbunden sind.
|
||||||
|
|
||||||
|
Gezählt werden physische Kabel (Interfaces, Front- und Rear-Ports), deren Enden in verschiedenen Lokationen
|
||||||
|
liegen – typischerweise LWL-/Kupfer-Trunks vom Serverraum zu den Unterverteilungen. Lokationen mit
|
||||||
|
Firewall/Router/Core stehen oben, die Ebenen darunter folgen der Verkabelung.
|
||||||
|
"""
|
||||||
|
from dcim.models import FrontPort, Interface, RearPort
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
|
resolver = SymbolResolver()
|
||||||
|
devices = list(
|
||||||
|
scope.devices()
|
||||||
|
.select_related("role", "device_type__manufacturer", "site", "location__parent", "rack")
|
||||||
|
.order_by("site__name", "location__name")
|
||||||
|
)
|
||||||
|
if not devices:
|
||||||
|
return []
|
||||||
|
by_pk = {d.pk: d for d in devices}
|
||||||
|
|
||||||
|
def node_of(d):
|
||||||
|
"""Lokation des Geräts – Geräte ohne Lokation (z.B. Richtfunk-APs am Dach) hängen am Standort selbst."""
|
||||||
|
return f"l{d.location_id}" if d.location_id else f"s{d.site_id}"
|
||||||
|
|
||||||
|
nid_of = {d.pk: node_of(d) for d in devices}
|
||||||
|
|
||||||
|
# Ebene je Lokation = „höchstes“ Gerät darin (Firewall/Core oben, reine Verteiler darunter)
|
||||||
|
tier, racks, count = {}, defaultdict(set), defaultdict(int)
|
||||||
|
for d in devices:
|
||||||
|
kind, _icon = resolver.resolve(d)
|
||||||
|
t = KINDS.get(kind, ("", 3))[1] if kind else 3
|
||||||
|
nid = nid_of[d.pk]
|
||||||
|
tier[nid] = min(tier.get(nid, 9), t)
|
||||||
|
count[nid] += 1
|
||||||
|
if d.rack_id:
|
||||||
|
racks[nid].add(d.rack_id)
|
||||||
|
|
||||||
|
cables = {} # ("c"|"w", pk) -> (Knoten a, Knoten b, Kabel oder WirelessLink)
|
||||||
|
outside = {} # node_id -> Node (andere Standorte / Provider)
|
||||||
|
for model in (Interface, FrontPort, RearPort):
|
||||||
|
cond = Q(cable__isnull=False)
|
||||||
|
if model is Interface:
|
||||||
|
cond |= Q(wireless_link__isnull=False)
|
||||||
|
ports = scope.restrict(model.objects.filter(cond, device_id__in=list(by_pk))).select_related("cable")
|
||||||
|
for port in ports:
|
||||||
|
link = port.cable if port.cable_id else port.wireless_link
|
||||||
|
link_key = ("c", port.cable_id) if port.cable_id else ("w", port.wireless_link_id)
|
||||||
|
if link_key in cables:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
peers = port.link_peers or []
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
continue
|
||||||
|
a = nid_of[port.device_id]
|
||||||
|
for peer in peers:
|
||||||
|
peer_dev = getattr(peer, "device", None)
|
||||||
|
if peer_dev is not None:
|
||||||
|
if peer_dev.pk in by_pk:
|
||||||
|
b = nid_of[peer_dev.pk]
|
||||||
|
elif not opts.get("topo_external"):
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
loc = getattr(peer_dev, "location", None)
|
||||||
|
b = f"l{loc.pk}" if loc else f"s{peer_dev.site_id}"
|
||||||
|
outside[b] = Node(
|
||||||
|
b, str(loc or peer_dev.site), "location", builtin_icon("location"),
|
||||||
|
[str(peer_dev.site)], external=True,
|
||||||
|
)
|
||||||
|
elif peer._meta.model_name == "circuittermination" and opts.get("topo_external"):
|
||||||
|
circuit = peer.circuit
|
||||||
|
b = f"c{circuit.pk}"
|
||||||
|
outside[b] = Node(b, str(circuit.provider), "cloud", builtin_icon("cloud"), [str(circuit.cid)], external=True)
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
if a != b:
|
||||||
|
cables[link_key] = (a, b, link)
|
||||||
|
break
|
||||||
|
|
||||||
|
links = defaultdict(list)
|
||||||
|
for a, b, cable in cables.values():
|
||||||
|
links[tuple(sorted((a, b)))].append(cable)
|
||||||
|
|
||||||
|
sites = OrderedDict()
|
||||||
|
all_locs = {} # node_id -> (Name, Standort)
|
||||||
|
for d in devices:
|
||||||
|
nid = nid_of[d.pk]
|
||||||
|
sites.setdefault(None if combined else d.site, OrderedDict())[nid] = d
|
||||||
|
all_locs[nid] = (d.location.name if d.location_id else str(d.site), d.site)
|
||||||
|
|
||||||
|
graphs = []
|
||||||
|
for site, locations in sites.items():
|
||||||
|
nodes = OrderedDict()
|
||||||
|
for nid, d in locations.items():
|
||||||
|
loc = d.location
|
||||||
|
if loc is not None:
|
||||||
|
name = loc.name
|
||||||
|
where = [str(loc.site)] if combined else []
|
||||||
|
if loc.parent_id:
|
||||||
|
where.append(str(loc.parent))
|
||||||
|
else:
|
||||||
|
name = str(d.site)
|
||||||
|
where = [_("without location")]
|
||||||
|
sub = [" / ".join(where)] if where else []
|
||||||
|
n_racks, n_dev = len(racks[nid]), count[nid]
|
||||||
|
parts = [ngettext("%(n)d rack", "%(n)d racks", n_racks) % {"n": n_racks}] if n_racks else []
|
||||||
|
parts.append(ngettext("%(n)d device", "%(n)d devices", n_dev) % {"n": n_dev})
|
||||||
|
sub.append(" · ".join(parts))
|
||||||
|
nodes[nid] = Node(nid, name, "location", builtin_icon("location"), sub, tier=tier[nid])
|
||||||
|
members = set(nodes)
|
||||||
|
edges = []
|
||||||
|
for (a, b), lst in links.items():
|
||||||
|
if not (a in members or b in members):
|
||||||
|
continue
|
||||||
|
for nid in (a, b):
|
||||||
|
if nid in members:
|
||||||
|
continue
|
||||||
|
tpl = outside.get(nid)
|
||||||
|
if tpl is None: # Lokation im Scope, aber an einem anderen Standort
|
||||||
|
name, loc_site = all_locs[nid]
|
||||||
|
tpl = Node(nid, name, "location", builtin_icon("location"), [str(loc_site)], external=True)
|
||||||
|
nodes[nid] = Node(**{**tpl.__dict__})
|
||||||
|
edges.append(Edge(
|
||||||
|
a, b, [str(c) for c in lst], summary=_cable_summary(lst),
|
||||||
|
wireless=all(c._meta.model_name == "wirelesslink" for c in lst),
|
||||||
|
))
|
||||||
|
if not opts.get("topo_isolated"):
|
||||||
|
linked = {n for e in edges for n in (e.a, e.b)}
|
||||||
|
nodes = OrderedDict((k, v) for k, v in nodes.items() if k in linked)
|
||||||
|
if nodes:
|
||||||
|
_layout(nodes, edges)
|
||||||
|
title = _("All sites") if combined else _("Site %(name)s") % {"name": site}
|
||||||
|
graphs.append(Graph(title, nodes, edges))
|
||||||
|
return graphs
|
||||||
|
|
||||||
|
|
||||||
|
def _cable_summary(cables):
|
||||||
|
"""„2× SMF, 4× CAT6a, 1× Funk“ – Kabel ohne Typ zählen als „Kabel“, Funkstrecken als „Funk“."""
|
||||||
|
types = defaultdict(int)
|
||||||
|
for c in cables:
|
||||||
|
if c._meta.model_name == "wirelesslink":
|
||||||
|
types[_("Wireless")] += 1
|
||||||
|
else:
|
||||||
|
types[c.get_type_display() if c.type else _("Cable")] += 1
|
||||||
|
return ", ".join(f"{n}× {t}" for t, n in sorted(types.items(), key=lambda x: -x[1]))
|
||||||
|
|
||||||
|
|
||||||
# --- Layout -------------------------------------------------------------------
|
# --- Layout -------------------------------------------------------------------
|
||||||
@@ -234,7 +391,7 @@ def _layout(nodes, edges):
|
|||||||
for e in edges:
|
for e in edges:
|
||||||
adj[e.a].add(e.b)
|
adj[e.a].add(e.b)
|
||||||
adj[e.b].add(e.a)
|
adj[e.b].add(e.a)
|
||||||
tier = {nid: KINDS.get(n.kind, ("", 4))[1] for nid, n in nodes.items()}
|
tier = {nid: n.tier if n.tier is not None else KINDS.get(n.kind, ("", 4))[1] for nid, n in nodes.items()}
|
||||||
|
|
||||||
layer = {n: None for n in nodes if not adj[n]} # isolierte Knoten: unterste Zeile
|
layer = {n: None for n in nodes if not adj[n]} # isolierte Knoten: unterste Zeile
|
||||||
remaining = set(nodes) - set(layer)
|
remaining = set(nodes) - set(layer)
|
||||||
@@ -303,10 +460,16 @@ def _oriented(graph, e):
|
|||||||
|
|
||||||
|
|
||||||
def _edge_text(graph, e, show_ports):
|
def _edge_text(graph, e, show_ports):
|
||||||
|
if e.summary:
|
||||||
|
return e.summary
|
||||||
if show_ports:
|
if show_ports:
|
||||||
labels = _oriented(graph, e)
|
labels = _oriented(graph, e)
|
||||||
return labels[0] + (f" (+{len(labels) - 1})" if len(labels) > 1 else "")
|
text = labels[0] + (f" (+{len(labels) - 1})" if len(labels) > 1 else "")
|
||||||
return f"{len(e.labels)}×" if len(e.labels) > 1 else None
|
return f"{_('Wireless')}: {text}" if e.wireless else text
|
||||||
|
count = f"{len(e.labels)}×" if len(e.labels) > 1 else ""
|
||||||
|
if e.wireless:
|
||||||
|
return f"{count} {_('Wireless')}".strip()
|
||||||
|
return count or None
|
||||||
|
|
||||||
|
|
||||||
# --- PNG ----------------------------------------------------------------------
|
# --- PNG ----------------------------------------------------------------------
|
||||||
@@ -316,6 +479,7 @@ PALETTE = [
|
|||||||
(23, 150, 170), (140, 86, 75), (188, 150, 20), (200, 80, 160), (90, 90, 90),
|
(23, 150, 170), (140, 86, 75), (188, 150, 20), (200, 80, 160), (90, 90, 90),
|
||||||
]
|
]
|
||||||
EXTERNAL = (160, 160, 160)
|
EXTERNAL = (160, 160, 160)
|
||||||
|
WIRELESS = (30, 136, 229) # Funkstrecken: blau, gepunktet
|
||||||
|
|
||||||
|
|
||||||
def _font(size, bold=False):
|
def _font(size, bold=False):
|
||||||
@@ -458,7 +622,8 @@ def render_png(graph, show_ports=False, scale=2):
|
|||||||
line([(min(xs), ly), (max(xs), ly)], col, dashed=u.external)
|
line([(min(xs), ly), (max(xs), ly)], col, dashed=u.external)
|
||||||
for c, e, ex, stack_pos in entries:
|
for c, e, ex, stack_pos in entries:
|
||||||
dashed = u.external or c.external
|
dashed = u.external or c.external
|
||||||
line([(ex, ly), (ex, c.y - 2)], EXTERNAL if dashed else col, w=3 if len(e.labels) > 1 else 2, dashed=dashed)
|
drop_col = WIRELESS if e.wireless else EXTERNAL if dashed else col
|
||||||
|
line([(ex, ly), (ex, c.y - 2)], drop_col, w=3 if len(e.labels) > 1 else 2, dashed=dashed or e.wireless)
|
||||||
if min(xs) < ex < max(xs): # Abzweig auf der Schiene markieren
|
if min(xs) < ex < max(xs): # Abzweig auf der Schiene markieren
|
||||||
d.ellipse([(ex - 2.5) * S, (ly - 2.5) * S, (ex + 2.5) * S, (ly + 2.5) * S], fill=col)
|
d.ellipse([(ex - 2.5) * S, (ly - 2.5) * S, (ex + 2.5) * S, (ly + 2.5) * S], fill=col)
|
||||||
text = _edge_text(graph, e, show_ports)
|
text = _edge_text(graph, e, show_ports)
|
||||||
@@ -471,7 +636,8 @@ def render_png(graph, show_ports=False, scale=2):
|
|||||||
a, b = nodes[e.a], nodes[e.b]
|
a, b = nodes[e.a], nodes[e.b]
|
||||||
ly = gap["top"] + gap["lane_of"][("s", i)] * LANE
|
ly = gap["top"] + gap["lane_of"][("s", i)] * LANE
|
||||||
dashed = a.external or b.external
|
dashed = a.external or b.external
|
||||||
line([(a.x, a.y - 2), (a.x, ly), (b.x, ly), (b.x, b.y - 2)], EXTERNAL if dashed else (70, 70, 70), dashed=dashed)
|
col = WIRELESS if e.wireless else EXTERNAL if dashed else (70, 70, 70)
|
||||||
|
line([(a.x, a.y - 2), (a.x, ly), (b.x, ly), (b.x, b.y - 2)], col, dashed=dashed or e.wireless)
|
||||||
text = _edge_text(graph, e, show_ports)
|
text = _edge_text(graph, e, show_ports)
|
||||||
if text:
|
if text:
|
||||||
labels.append((text, (a.x + b.x) / 2, ly, "mm"))
|
labels.append((text, (a.x + b.x) / 2, ly, "mm"))
|
||||||
@@ -483,7 +649,8 @@ def render_png(graph, show_ports=False, scale=2):
|
|||||||
left, right = (a, b) if a.x < b.x else (b, a)
|
left, right = (a, b) if a.x < b.x else (b, a)
|
||||||
line(
|
line(
|
||||||
[(left.x + ICON / 2 + 4, cy), (right.x - ICON / 2 - 4, cy)],
|
[(left.x + ICON / 2 + 4, cy), (right.x - ICON / 2 - 4, cy)],
|
||||||
EXTERNAL if dashed else (70, 70, 70), w=3 if len(e.labels) > 1 else 2, dashed=dashed,
|
WIRELESS if e.wireless else EXTERNAL if dashed else (70, 70, 70),
|
||||||
|
w=3 if len(e.labels) > 1 else 2, dashed=dashed or e.wireless,
|
||||||
)
|
)
|
||||||
text = _edge_text(graph, e, show_ports)
|
text = _edge_text(graph, e, show_ports)
|
||||||
if text:
|
if text:
|
||||||
|
|||||||
@@ -42,7 +42,9 @@ class ExportView(LoginRequiredMixin, View):
|
|||||||
grouped = {}
|
grouped = {}
|
||||||
for s in SECTIONS.values():
|
for s in SECTIONS.values():
|
||||||
grouped.setdefault(s.group, []).append(s)
|
grouped.setdefault(s.group, []).append(s)
|
||||||
return render(request, self.template_name, {"object": scope.obj, "scope": scope, "form": form, "section_groups": grouped})
|
return render(request, self.template_name, {
|
||||||
|
"object": scope.obj, "scope": scope, "form": form, "section_groups": grouped, "rack_photos": form.photo_groups,
|
||||||
|
})
|
||||||
|
|
||||||
def get(self, request, kind, pk):
|
def get(self, request, kind, pk):
|
||||||
scope = self._scope(request, kind, pk)
|
scope = self._scope(request, kind, pk)
|
||||||
@@ -58,6 +60,7 @@ class ExportView(LoginRequiredMixin, View):
|
|||||||
blocks = []
|
blocks = []
|
||||||
for key in opts["sections"]:
|
for key in opts["sections"]:
|
||||||
blocks += SECTIONS[key].func(scope, opts)
|
blocks += SECTIONS[key].func(scope, opts)
|
||||||
|
blocks += opts.pop("_appendix", []) # z.B. Rack-Fotos, immer am Dokumentende
|
||||||
|
|
||||||
doc = Document(
|
doc = Document(
|
||||||
title=opts["title"],
|
title=opts["title"],
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "netbox-customer-export"
|
name = "netbox-customer-export"
|
||||||
version = "0.11.0"
|
version = "0.19.1"
|
||||||
description = "NetBox plugin: customer documentation (PDF/Word) for sites, locations, tenants and tenant groups"
|
description = "NetBox plugin: customer documentation (PDF/Word) for sites, locations, tenants and tenant groups"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
|
|||||||
Reference in new issue
Block a user