feat: import the disk CSV export of an HPE MSA
A three-step wizard reads the MSA disk export, maps each enclosure (shelf) to a device and previews new, updated, replaced, skipped and conflicting disks. Devices without slot areas get one created during the import, pre-filled from the device type template or the export. Disk groups can become RAID groups and the install date can be estimated from the power on hours. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
d45afa5e54
commit
a7801ec297
9 files changed
+896
-3
No files matched your search
@@ -28,7 +28,7 @@ uploads and more.
|
|||||||
- Cables and wireless links can be assigned to one or more VLANs.
|
- Cables and wireless links can be assigned to one or more VLANs.
|
||||||
- The B-side device selection of a cable can be pre-filtered by tenant group, tenant and site.
|
- The B-side device selection of a cable can be pre-filtered by tenant group, tenant and site.
|
||||||
- A **Prefix** column (first word of the site name) for device and rack lists, including sorting and filtering.
|
- A **Prefix** column (first word of the site name) for device and rack lists, including sorting and filtering.
|
||||||
- A **Disks** tab for servers, NAS, SAN and MSA devices: slot layout, disks, RAID groups, warranty and age warnings, replacement history, CSV import, REST API and GraphQL.
|
- A **Disks** tab for servers, NAS, SAN and MSA devices: slot layout, disks, RAID groups, warranty and age warnings, replacement history, CSV import, HPE MSA disk export import, REST API and GraphQL.
|
||||||
|
|
||||||
Navigation settings are stored per user. The active tenant or tenant-group
|
Navigation settings are stored per user. The active tenant or tenant-group
|
||||||
selection is stored in the browser session.
|
selection is stored in the browser session.
|
||||||
@@ -333,6 +333,20 @@ srv-01,Front,1,spare,ssd,sas,Samsung,PM1643a,1.92 TB,S4XXNA0R123457,2029-05-31
|
|||||||
srv-01,PCIe,0,active,nvme,nvme,Samsung,PM9A3,3.84 TB,S64XNA0T654321,2030-01-31
|
srv-01,PCIe,0,active,nvme,nvme,Samsung,PM9A3,3.84 TB,S64XNA0T654321,2030-01-31
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**HPE MSA import.** The *HPE MSA export* button next to **Disks > Disks** (also
|
||||||
|
*MSA import* in a device's **Disks** tab) reads the CSV disk export of an HPE MSA
|
||||||
|
(*Pools → Disks*, export to CSV). The `Location` column (`1.4` = enclosure 1,
|
||||||
|
slot 4) defines the enclosures; in the next step each enclosure (shelf) is
|
||||||
|
assigned to a NetBox device. The preview shows per disk whether it is new,
|
||||||
|
updated (same serial in the same slot), replacing another disk, skipped or in
|
||||||
|
conflict (slot outside the area, serial already installed elsewhere). If a
|
||||||
|
device has no slot area yet, the area is created during the import, pre-filled
|
||||||
|
from the device type template or from the export (12 or 24 bays). `Type`,
|
||||||
|
`Size` (GiB are converted), `Disk Group`, `Revision` and `Health` are mapped;
|
||||||
|
`GLOBAL SP`/`DEDICATED SP` become hot spares, `Fault` becomes failed. Optionally
|
||||||
|
missing RAID groups are created from `Disk Group` (level *Other*) and the install
|
||||||
|
date is estimated from `Power On Hours`.
|
||||||
|
|
||||||
**REST API and GraphQL.**
|
**REST API and GraphQL.**
|
||||||
|
|
||||||
| Endpoint | Content |
|
| Endpoint | Content |
|
||||||
@@ -352,6 +366,9 @@ and `netbox_utilities_disk_bay_template(_list)`.
|
|||||||
layout and filling slots requires `netbox_utilities.add_disk`, replacing
|
layout and filling slots requires `netbox_utilities.add_disk`, replacing
|
||||||
requires `netbox_utilities.change_disk`, and RAID groups use the
|
requires `netbox_utilities.change_disk`, and RAID groups use the
|
||||||
`netbox_utilities.*_raidgroup` permissions.
|
`netbox_utilities.*_raidgroup` permissions.
|
||||||
|
The HPE MSA import requires `netbox_utilities.add_disk`; updating or replacing
|
||||||
|
existing disks additionally requires `netbox_utilities.change_disk`, and creating
|
||||||
|
RAID groups `netbox_utilities.add_raidgroup` (otherwise they are skipped).
|
||||||
|
|
||||||
### Pre-filter for the B-side of a cable
|
### Pre-filter for the B-side of a cable
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from utilities.forms.fields import (
|
|||||||
from utilities.forms.rendering import FieldSet
|
from utilities.forms.rendering import FieldSet
|
||||||
from utilities.forms.widgets import DatePicker
|
from utilities.forms.widgets import DatePicker
|
||||||
|
|
||||||
from . import disks
|
from . import disks, msa_import
|
||||||
from .models import (
|
from .models import (
|
||||||
BAY_LAYOUT_FIELDS,
|
BAY_LAYOUT_FIELDS,
|
||||||
Disk,
|
Disk,
|
||||||
@@ -487,3 +487,90 @@ class DiskBulkEditForm(NetBoxModelBulkEditForm):
|
|||||||
"description",
|
"description",
|
||||||
"comments",
|
"comments",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MSAUploadForm(forms.Form):
|
||||||
|
"""Step 1 of the HPE MSA import: the CSV export from Pools → Disks."""
|
||||||
|
|
||||||
|
export_file = forms.FileField(
|
||||||
|
label="CSV-Datei",
|
||||||
|
required=False,
|
||||||
|
widget=forms.ClearableFileInput(attrs={"class": "form-control", "accept": ".csv,text/csv"}),
|
||||||
|
)
|
||||||
|
export_text = forms.CharField(
|
||||||
|
label="… oder Inhalt einfügen",
|
||||||
|
required=False,
|
||||||
|
widget=forms.Textarea(attrs={"class": "form-control font-monospace", "rows": 8}),
|
||||||
|
)
|
||||||
|
|
||||||
|
def clean(self):
|
||||||
|
cleaned_data = super().clean()
|
||||||
|
upload = cleaned_data.get("export_file")
|
||||||
|
data = upload.read() if upload else cleaned_data.get("export_text", "")
|
||||||
|
if not data or not str(data).strip():
|
||||||
|
raise ValidationError("Bitte eine CSV-Datei hochladen oder den Inhalt einfügen.")
|
||||||
|
export = msa_import.parse_export(data)
|
||||||
|
if not export.disks:
|
||||||
|
raise ValidationError(export.errors)
|
||||||
|
cleaned_data["export"] = export
|
||||||
|
cleaned_data["raw"] = data if isinstance(data, str) else msa_import._decode(data)
|
||||||
|
return cleaned_data
|
||||||
|
|
||||||
|
|
||||||
|
class MSAAssignForm(forms.Form):
|
||||||
|
"""Step 2: which NetBox device is which MSA enclosure (shelf)."""
|
||||||
|
|
||||||
|
create_raid_groups = forms.BooleanField(
|
||||||
|
label="RAID-Gruppen aus „Disk Group“ anlegen",
|
||||||
|
required=False,
|
||||||
|
initial=True,
|
||||||
|
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
|
||||||
|
help_text="Fehlende Gruppen werden mit RAID-Level „Sonstiges“ angelegt; das Level bitte danach prüfen.",
|
||||||
|
)
|
||||||
|
replace_existing = forms.BooleanField(
|
||||||
|
label="Belegte Steckplätze ersetzen",
|
||||||
|
required=False,
|
||||||
|
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
|
||||||
|
help_text="Steckt in NetBox ein anderer Datenträger im Steckplatz, wird er als ausgebaut markiert.",
|
||||||
|
)
|
||||||
|
estimate_install_date = forms.BooleanField(
|
||||||
|
label="Einbaudatum aus Betriebsstunden schätzen",
|
||||||
|
required=False,
|
||||||
|
initial=True,
|
||||||
|
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
|
||||||
|
help_text="Nur für neue Datenträger; damit greift die Alterswarnung.",
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, *args, enclosures=(), **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.enclosures = list(enclosures)
|
||||||
|
for enclosure in self.enclosures:
|
||||||
|
self.fields[f"device_{enclosure}"] = DynamicModelChoiceField(
|
||||||
|
label=f"Shelf {enclosure}",
|
||||||
|
queryset=Device.objects.all(),
|
||||||
|
required=False,
|
||||||
|
selector=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
def device_fields(self):
|
||||||
|
return [(enclosure, self[f"device_{enclosure}"]) for enclosure in self.enclosures]
|
||||||
|
|
||||||
|
def option_fields(self):
|
||||||
|
return [self[name] for name in ("create_raid_groups", "replace_existing", "estimate_install_date")]
|
||||||
|
|
||||||
|
def clean(self):
|
||||||
|
cleaned_data = super().clean()
|
||||||
|
assigned = {
|
||||||
|
enclosure: cleaned_data.get(f"device_{enclosure}")
|
||||||
|
for enclosure in self.enclosures
|
||||||
|
if cleaned_data.get(f"device_{enclosure}")
|
||||||
|
}
|
||||||
|
if not assigned:
|
||||||
|
raise ValidationError("Bitte mindestens einem Shelf ein Gerät zuweisen.")
|
||||||
|
seen = {}
|
||||||
|
for enclosure, device in assigned.items():
|
||||||
|
if device.pk in seen:
|
||||||
|
self.add_error(f"device_{enclosure}", f"{device} ist bereits Shelf {seen[device.pk]} zugewiesen.")
|
||||||
|
seen[device.pk] = enclosure
|
||||||
|
cleaned_data["assigned"] = assigned
|
||||||
|
return cleaned_data
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import base64
|
||||||
|
from datetime import timedelta
|
||||||
from itertools import groupby
|
from itertools import groupby
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
@@ -9,12 +11,13 @@ from django.db import transaction
|
|||||||
from django.http import JsonResponse
|
from django.http import JsonResponse
|
||||||
from django.shortcuts import get_object_or_404, redirect, render
|
from django.shortcuts import get_object_or_404, redirect, render
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
from django.views import View
|
from django.views import View
|
||||||
from netbox.plugins import get_plugin_config
|
from netbox.plugins import get_plugin_config
|
||||||
from netbox.views import generic
|
from netbox.views import generic
|
||||||
from utilities.views import ContentTypePermissionRequiredMixin, ViewTab, register_model_view
|
from utilities.views import ContentTypePermissionRequiredMixin, ViewTab, register_model_view
|
||||||
|
|
||||||
from . import disk_filtersets, disk_forms, disk_tables, disks
|
from . import disk_filtersets, disk_forms, disk_tables, disks, msa_import
|
||||||
from .models import DEFAULT_BAY_NAME, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
|
from .models import DEFAULT_BAY_NAME, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
|
||||||
|
|
||||||
BAY_NAME_SUGGESTIONS = ("Front", "Rückseite", "Intern", "BOSS-Karte (M.2)", "PCIe", "M.2")
|
BAY_NAME_SUGGESTIONS = ("Front", "Rückseite", "Intern", "BOSS-Karte (M.2)", "PCIe", "M.2")
|
||||||
@@ -572,3 +575,311 @@ class DiskBayTemplateBulkDeleteView(generic.BulkDeleteView):
|
|||||||
queryset = DiskBayTemplate.objects.all()
|
queryset = DiskBayTemplate.objects.all()
|
||||||
filterset = disk_filtersets.DiskBayTemplateFilterSet
|
filterset = disk_filtersets.DiskBayTemplateFilterSet
|
||||||
table = disk_tables.DiskBayTemplateTable
|
table = disk_tables.DiskBayTemplateTable
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# HPE MSA import
|
||||||
|
#
|
||||||
|
|
||||||
|
IMPORTING_ACTIONS = (msa_import.ACTION_NEW, msa_import.ACTION_UPDATE, msa_import.ACTION_REPLACE)
|
||||||
|
|
||||||
|
|
||||||
|
class MSADiskImportView(ContentTypePermissionRequiredMixin, View):
|
||||||
|
"""Import the disk CSV export of an HPE MSA: map each enclosure (shelf) to a device, preview, create.
|
||||||
|
|
||||||
|
The wizard keeps no server-side state; the export travels base64-encoded in a hidden field.
|
||||||
|
"""
|
||||||
|
|
||||||
|
template_name = "netbox_utilities/disk_msa_import.html"
|
||||||
|
|
||||||
|
def get_required_permission(self):
|
||||||
|
return "netbox_utilities.add_disk"
|
||||||
|
|
||||||
|
def get(self, request):
|
||||||
|
return self._render(request, "upload", upload_form=disk_forms.MSAUploadForm())
|
||||||
|
|
||||||
|
def post(self, request):
|
||||||
|
step = request.POST.get("step", "upload")
|
||||||
|
if step == "upload" or not request.POST.get("export_data"):
|
||||||
|
upload_form = disk_forms.MSAUploadForm(request.POST, request.FILES)
|
||||||
|
if not upload_form.is_valid():
|
||||||
|
return self._render(request, "upload", upload_form=upload_form)
|
||||||
|
raw = upload_form.cleaned_data["raw"]
|
||||||
|
export = upload_form.cleaned_data["export"]
|
||||||
|
return self._render_assign(request, raw, export, self._assign_form(request, export))
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw = base64.b64decode(request.POST["export_data"]).decode("utf-8")
|
||||||
|
except (ValueError, UnicodeDecodeError):
|
||||||
|
messages.error(request, "Die Importdaten waren beschädigt. Bitte die Datei erneut hochladen.")
|
||||||
|
return redirect("plugins:netbox_utilities:disk_msa_import")
|
||||||
|
export = msa_import.parse_export(raw)
|
||||||
|
assign_form = self._assign_form(request, export, data=request.POST)
|
||||||
|
if step == "back" or not assign_form.is_valid():
|
||||||
|
return self._render_assign(request, raw, export, assign_form)
|
||||||
|
|
||||||
|
bound = step == "plan"
|
||||||
|
plans = [
|
||||||
|
self._plan_enclosure(request, enclosure, device, export.enclosures[enclosure], assign_form, bound)
|
||||||
|
for enclosure, device in assign_form.cleaned_data["assigned"].items()
|
||||||
|
]
|
||||||
|
if bound and "do_import" in request.POST:
|
||||||
|
error = self._import_blocker(request, plans)
|
||||||
|
if error:
|
||||||
|
messages.error(request, error)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
summary = self._execute(request, plans, assign_form.cleaned_data)
|
||||||
|
except ValidationError as exc:
|
||||||
|
for message in exc.messages:
|
||||||
|
messages.error(request, message)
|
||||||
|
else:
|
||||||
|
messages.success(request, summary)
|
||||||
|
devices = [plan["device"] for plan in plans]
|
||||||
|
if len(devices) == 1:
|
||||||
|
return redirect("dcim:device_disks", pk=devices[0].pk)
|
||||||
|
return redirect(
|
||||||
|
f"{reverse('plugins:netbox_utilities:disk_by_device')}?"
|
||||||
|
+ urlencode([("device_id", device.pk) for device in devices])
|
||||||
|
)
|
||||||
|
return self._render(
|
||||||
|
request,
|
||||||
|
"plan",
|
||||||
|
export_data=self._encode(raw),
|
||||||
|
assign_form=assign_form,
|
||||||
|
plans=plans,
|
||||||
|
parse_errors=export.errors,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _encode(raw):
|
||||||
|
return base64.b64encode(raw.encode("utf-8")).decode("ascii")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _assign_form(request, export, data=None):
|
||||||
|
form = disk_forms.MSAAssignForm(data, enclosures=list(export.enclosures))
|
||||||
|
devices = Device.objects.restrict(request.user, "view")
|
||||||
|
for enclosure in form.enclosures:
|
||||||
|
form.fields[f"device_{enclosure}"].queryset = devices
|
||||||
|
return form
|
||||||
|
|
||||||
|
def _render_assign(self, request, raw, export, assign_form):
|
||||||
|
enclosures = [
|
||||||
|
{
|
||||||
|
"id": enclosure,
|
||||||
|
"field": assign_form[f"device_{enclosure}"],
|
||||||
|
"count": len(items),
|
||||||
|
"first": items[0].slot,
|
||||||
|
"last": items[-1].slot,
|
||||||
|
"models": sorted({item.model for item in items if item.model}),
|
||||||
|
}
|
||||||
|
for enclosure, items in export.enclosures.items()
|
||||||
|
]
|
||||||
|
return self._render(
|
||||||
|
request,
|
||||||
|
"assign",
|
||||||
|
export_data=self._encode(raw),
|
||||||
|
assign_form=assign_form,
|
||||||
|
enclosures=enclosures,
|
||||||
|
parse_errors=export.errors,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _bay_defaults(device, items):
|
||||||
|
"""Initial values for a new slot area: the device type template, else a guess from the export."""
|
||||||
|
templates = DiskBayTemplate.objects.filter(device_type_id=device.device_type_id).order_by("weight", "name")
|
||||||
|
template = templates.first()
|
||||||
|
if template is not None:
|
||||||
|
values = template.layout_values()
|
||||||
|
else:
|
||||||
|
first = 0 if min(item.slot for item in items) == 0 else 1
|
||||||
|
count = msa_import.suggest_slot_count(max(item.slot for item in items) - first + 1)
|
||||||
|
values = {
|
||||||
|
"name": DEFAULT_BAY_NAME,
|
||||||
|
"weight": 100,
|
||||||
|
"slot_count": count,
|
||||||
|
"rows": 1,
|
||||||
|
"first_slot": first,
|
||||||
|
"numbering": disks.NUMBERING_HORIZONTAL,
|
||||||
|
"form_factor": msa_import.suggest_form_factor(count),
|
||||||
|
}
|
||||||
|
values["save_as_template"] = template is None
|
||||||
|
return values
|
||||||
|
|
||||||
|
def _plan_enclosure(self, request, enclosure, device, items, assign_form, bound):
|
||||||
|
bays = list(DiskBayLayout.objects.filter(device=device).order_by("weight", "name", "pk"))
|
||||||
|
bay = bay_form = None
|
||||||
|
if bays:
|
||||||
|
requested = request.POST.get(f"bay_{enclosure}") if bound else None
|
||||||
|
bay = next((item for item in bays if str(item.pk) == requested), None)
|
||||||
|
if bay is None:
|
||||||
|
highest = max(item.slot for item in items)
|
||||||
|
bay = next((item for item in bays if item.first_slot <= highest <= item.last_slot), bays[0])
|
||||||
|
first_slot, last_slot = bay.first_slot, bay.last_slot
|
||||||
|
else:
|
||||||
|
# The device has no slots yet: ask for the area right here, pre-filled from the export.
|
||||||
|
defaults = self._bay_defaults(device, items)
|
||||||
|
bay_form = disk_forms.DiskBayLayoutForm(
|
||||||
|
request.POST if bound else None,
|
||||||
|
prefix=f"bay{enclosure}",
|
||||||
|
instance=DiskBayLayout(device=device),
|
||||||
|
initial=defaults,
|
||||||
|
)
|
||||||
|
bay_form.fields["slot_count"].widget.attrs.pop("autofocus", None)
|
||||||
|
if bound and bay_form.is_valid():
|
||||||
|
first_slot = bay_form.cleaned_data["first_slot"]
|
||||||
|
slot_count = bay_form.cleaned_data["slot_count"]
|
||||||
|
else:
|
||||||
|
first_slot, slot_count = defaults["first_slot"], defaults["slot_count"]
|
||||||
|
last_slot = first_slot + slot_count - 1
|
||||||
|
|
||||||
|
# Disks in the chosen area, or without area while the device has none yet.
|
||||||
|
installed = Disk.objects.filter(device=device, status__in=disks.SLOT_OCCUPYING_STATUSES)
|
||||||
|
installed = installed.filter(bay=bay) if bay is not None else installed.filter(bay__isnull=True)
|
||||||
|
occupants = {disk.slot: disk for disk in installed}
|
||||||
|
holders = {}
|
||||||
|
serials = [item.serial for item in items if item.serial]
|
||||||
|
for disk in Disk.objects.filter(serial__in=serials, status__in=disks.SLOT_OCCUPYING_STATUSES).select_related(
|
||||||
|
"device", "bay"
|
||||||
|
):
|
||||||
|
holders.setdefault(disk.serial.casefold(), []).append(disk)
|
||||||
|
|
||||||
|
replace = assign_form.cleaned_data["replace_existing"]
|
||||||
|
rows = []
|
||||||
|
for item in items:
|
||||||
|
occupant = occupants.get(item.slot)
|
||||||
|
elsewhere = next(
|
||||||
|
(
|
||||||
|
f"{disk.device} – {disk.slot_label}"
|
||||||
|
for disk in holders.get(item.serial.casefold(), [])
|
||||||
|
if occupant is None or disk.pk != occupant.pk
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
action, reason = msa_import.classify(
|
||||||
|
item,
|
||||||
|
first_slot,
|
||||||
|
last_slot,
|
||||||
|
occupant_serial=None if occupant is None else occupant.serial,
|
||||||
|
serial_elsewhere=elsewhere,
|
||||||
|
replace=replace,
|
||||||
|
)
|
||||||
|
label, color = msa_import.ACTION_LABELS[action]
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"item": item,
|
||||||
|
"occupant": occupant,
|
||||||
|
"action": action,
|
||||||
|
"label": label,
|
||||||
|
"color": color,
|
||||||
|
"reason": reason,
|
||||||
|
"capacity": disks.format_capacity(item.capacity_gb),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"enclosure": enclosure,
|
||||||
|
"device": device,
|
||||||
|
"bays": bays,
|
||||||
|
"bay": bay,
|
||||||
|
"bay_form": bay_form,
|
||||||
|
"rows": rows,
|
||||||
|
"importing": sum(1 for row in rows if row["action"] in IMPORTING_ACTIONS),
|
||||||
|
"groups": sorted({item.disk_group for item in items if item.disk_group}),
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _import_blocker(request, plans):
|
||||||
|
if any(plan["bay_form"] is not None and not plan["bay_form"].is_valid() for plan in plans):
|
||||||
|
return "Bitte die Angaben zu den neuen Steckplatz-Bereichen korrigieren."
|
||||||
|
actions = [row["action"] for plan in plans for row in plan["rows"]]
|
||||||
|
if not any(action in IMPORTING_ACTIONS for action in actions):
|
||||||
|
return "Es gibt nichts zu importieren."
|
||||||
|
changes = any(action in (msa_import.ACTION_UPDATE, msa_import.ACTION_REPLACE) for action in actions)
|
||||||
|
if changes and not request.user.has_perm("netbox_utilities.change_disk"):
|
||||||
|
return "Zum Aktualisieren oder Ersetzen vorhandener Datenträger fehlt die Berechtigung."
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _execute(request, plans, options):
|
||||||
|
today = timezone.localdate()
|
||||||
|
may_add_groups = request.user.has_perm("netbox_utilities.add_raidgroup")
|
||||||
|
totals = dict.fromkeys((*IMPORTING_ACTIONS, "bays", "groups"), 0)
|
||||||
|
|
||||||
|
with transaction.atomic():
|
||||||
|
for plan in plans:
|
||||||
|
device, bay, bay_form = plan["device"], plan["bay"], plan["bay_form"]
|
||||||
|
if bay_form is not None:
|
||||||
|
bay = bay_form.save()
|
||||||
|
totals["bays"] += 1
|
||||||
|
# Disks recorded before the device had any area belong to its first one.
|
||||||
|
for disk in Disk.objects.filter(device=device, bay__isnull=True):
|
||||||
|
disk.snapshot()
|
||||||
|
disk.bay = bay
|
||||||
|
disk.save()
|
||||||
|
if bay_form.cleaned_data.get("save_as_template"):
|
||||||
|
values = bay.layout_values()
|
||||||
|
DiskBayTemplate.objects.update_or_create(
|
||||||
|
device_type_id=device.device_type_id, name=values.pop("name"), defaults=values
|
||||||
|
)
|
||||||
|
|
||||||
|
groups = {group.name.casefold(): group for group in RAIDGroup.objects.filter(device=device)}
|
||||||
|
if options["create_raid_groups"] and may_add_groups:
|
||||||
|
for name in plan["groups"]:
|
||||||
|
if name.casefold() not in groups:
|
||||||
|
group = RAIDGroup(
|
||||||
|
device=device, name=name, level="other", description="Aus HPE MSA importiert"
|
||||||
|
)
|
||||||
|
group.full_clean()
|
||||||
|
group.save()
|
||||||
|
groups[name.casefold()] = group
|
||||||
|
totals["groups"] += 1
|
||||||
|
|
||||||
|
for row in plan["rows"]:
|
||||||
|
item, action = row["item"], row["action"]
|
||||||
|
if action not in IMPORTING_ACTIONS:
|
||||||
|
continue
|
||||||
|
values = {
|
||||||
|
"status": item.status,
|
||||||
|
"disk_type": item.disk_type,
|
||||||
|
"interface": item.interface,
|
||||||
|
"manufacturer": item.manufacturer,
|
||||||
|
"model": item.model,
|
||||||
|
"capacity_gb": item.capacity_gb,
|
||||||
|
"firmware": item.firmware,
|
||||||
|
"raid_group": groups.get(item.disk_group.casefold()) if item.disk_group else None,
|
||||||
|
}
|
||||||
|
if action == msa_import.ACTION_UPDATE:
|
||||||
|
disk = Disk.objects.get(pk=row["occupant"].pk)
|
||||||
|
disk.snapshot()
|
||||||
|
disk.bay = bay
|
||||||
|
for name, value in values.items():
|
||||||
|
if value not in (None, "") or name == "raid_group":
|
||||||
|
setattr(disk, name, value)
|
||||||
|
else:
|
||||||
|
if action == msa_import.ACTION_REPLACE:
|
||||||
|
old = Disk.objects.get(pk=row["occupant"].pk)
|
||||||
|
old.snapshot()
|
||||||
|
old.status = disks.STATUS_REPLACED
|
||||||
|
old.save()
|
||||||
|
disk = Disk(device=device, bay=bay, slot=item.slot, serial=item.serial, **values)
|
||||||
|
disk.form_factor = bay.form_factor
|
||||||
|
if options["estimate_install_date"] and item.power_on_hours:
|
||||||
|
disk.install_date = today - timedelta(hours=item.power_on_hours)
|
||||||
|
else:
|
||||||
|
disk.install_date = today
|
||||||
|
disk.full_clean()
|
||||||
|
disk.save()
|
||||||
|
totals[action] += 1
|
||||||
|
|
||||||
|
parts = [f"{totals[msa_import.ACTION_NEW]} neu", f"{totals[msa_import.ACTION_UPDATE]} aktualisiert"]
|
||||||
|
if totals[msa_import.ACTION_REPLACE]:
|
||||||
|
parts.append(f"{totals[msa_import.ACTION_REPLACE]} ersetzt")
|
||||||
|
text = "MSA-Import abgeschlossen: " + ", ".join(parts) + "."
|
||||||
|
if totals["bays"]:
|
||||||
|
text += f" {totals['bays']} Steckplatz-Bereich(e) angelegt."
|
||||||
|
if totals["groups"]:
|
||||||
|
text += f" {totals['groups']} RAID-Gruppe(n) angelegt – bitte das RAID-Level prüfen."
|
||||||
|
return text
|
||||||
|
|
||||||
|
def _render(self, request, step, **context):
|
||||||
|
return render(request, self.template_name, {"step": step, **context})
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"""Pure helpers for importing the disk export of an HPE MSA (Pools → Disks → "Export to CSV")."""
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from . import disks
|
||||||
|
|
||||||
|
# Header names of the MSA export, casefolded.
|
||||||
|
COLUMN_LOCATION = "location"
|
||||||
|
REQUIRED_COLUMNS = (COLUMN_LOCATION,)
|
||||||
|
|
||||||
|
# Usage values of hot spares; "dedicated" spares belong to one disk group.
|
||||||
|
SPARE_USAGES = ("global sp", "dedicated sp", "spare")
|
||||||
|
# Health values which mean the disk has failed.
|
||||||
|
FAILED_HEALTH = ("fault", "failed")
|
||||||
|
# Disk group values without a real group.
|
||||||
|
NO_GROUP = ("", "-", "n/a")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MSADisk:
|
||||||
|
enclosure: str
|
||||||
|
slot: int
|
||||||
|
status: str
|
||||||
|
disk_type: str = ""
|
||||||
|
interface: str = ""
|
||||||
|
capacity_gb: int | None = None
|
||||||
|
disk_group: str = ""
|
||||||
|
serial: str = ""
|
||||||
|
manufacturer: str = ""
|
||||||
|
model: str = ""
|
||||||
|
firmware: str = ""
|
||||||
|
power_on_hours: int | None = None
|
||||||
|
usage: str = ""
|
||||||
|
health: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MSAExport:
|
||||||
|
disks: list = field(default_factory=list)
|
||||||
|
errors: list = field(default_factory=list)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def enclosures(self):
|
||||||
|
"""Enclosure IDs in natural order with their disks."""
|
||||||
|
result = {}
|
||||||
|
for disk in sorted(self.disks, key=lambda item: (_natural(item.enclosure), item.slot)):
|
||||||
|
result.setdefault(disk.enclosure, []).append(disk)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _natural(value):
|
||||||
|
return (0, int(value), "") if str(value).isdigit() else (1, 0, str(value))
|
||||||
|
|
||||||
|
|
||||||
|
def _decode(data):
|
||||||
|
if isinstance(data, bytes):
|
||||||
|
for encoding in ("utf-8-sig", "cp1252"):
|
||||||
|
try:
|
||||||
|
return data.decode(encoding)
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
continue
|
||||||
|
return str(data or "").lstrip("")
|
||||||
|
|
||||||
|
|
||||||
|
def _int(value):
|
||||||
|
try:
|
||||||
|
return int(str(value).strip().replace(".", "").replace(",", ""))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def map_type(value, rpm=""):
|
||||||
|
"""Translate the MSA "Type" column, e.g. "SSD SAS", "SAS", "SAS MDL" or "SATA", into (type, interface)."""
|
||||||
|
text = (value or "").upper()
|
||||||
|
interface = "sata" if "SATA" in text else "sas" if "SAS" in text else "nvme" if "NVME" in text else ""
|
||||||
|
if "SSD" in text or "NVME" in text:
|
||||||
|
disk_type = "ssd" if interface != "nvme" else "nvme"
|
||||||
|
elif text or (rpm and rpm.strip().lower() not in ("0k", "0")):
|
||||||
|
disk_type = "hdd"
|
||||||
|
else:
|
||||||
|
disk_type = ""
|
||||||
|
return disk_type, interface
|
||||||
|
|
||||||
|
|
||||||
|
def map_status(usage, health):
|
||||||
|
if (health or "").strip().casefold() in FAILED_HEALTH:
|
||||||
|
return disks.STATUS_FAILED
|
||||||
|
if (usage or "").strip().casefold() in SPARE_USAGES:
|
||||||
|
return disks.STATUS_SPARE
|
||||||
|
return disks.STATUS_ACTIVE
|
||||||
|
|
||||||
|
|
||||||
|
def parse_export(data):
|
||||||
|
"""Parse the CSV export into an MSAExport; rows that cannot be read end up in errors."""
|
||||||
|
text = _decode(data).strip()
|
||||||
|
export = MSAExport()
|
||||||
|
if not text:
|
||||||
|
export.errors.append("Die Datei ist leer.")
|
||||||
|
return export
|
||||||
|
try:
|
||||||
|
dialect = csv.Sniffer().sniff(text.splitlines()[0], delimiters=",;\t")
|
||||||
|
except csv.Error:
|
||||||
|
dialect = csv.excel
|
||||||
|
reader = csv.DictReader(io.StringIO(text), dialect=dialect)
|
||||||
|
headers = {name.strip().casefold(): name for name in (reader.fieldnames or [])}
|
||||||
|
missing = [name for name in REQUIRED_COLUMNS if name not in headers]
|
||||||
|
if missing:
|
||||||
|
export.errors.append("Das ist kein HPE-MSA-Datenträger-Export: die Spalte „Location“ fehlt.")
|
||||||
|
return export
|
||||||
|
|
||||||
|
def column(row, name):
|
||||||
|
key = headers.get(name)
|
||||||
|
return (row.get(key) or "").strip() if key else ""
|
||||||
|
|
||||||
|
seen = set()
|
||||||
|
for line, row in enumerate(reader, start=2):
|
||||||
|
location = column(row, COLUMN_LOCATION)
|
||||||
|
if not location:
|
||||||
|
continue
|
||||||
|
enclosure, _, slot_text = location.partition(".")
|
||||||
|
slot = _int(slot_text)
|
||||||
|
if not enclosure or slot is None:
|
||||||
|
export.errors.append(f"Zeile {line}: ungültige Position {location!r} (erwartet z. B. 1.4).")
|
||||||
|
continue
|
||||||
|
if (enclosure, slot) in seen:
|
||||||
|
export.errors.append(f"Zeile {line}: Position {location} kommt mehrfach vor.")
|
||||||
|
continue
|
||||||
|
seen.add((enclosure, slot))
|
||||||
|
|
||||||
|
try:
|
||||||
|
capacity = disks.parse_capacity(column(row, "size")) if column(row, "size") else None
|
||||||
|
except ValueError:
|
||||||
|
capacity = None
|
||||||
|
disk_type, interface = map_type(column(row, "type"), column(row, "r/min"))
|
||||||
|
group = column(row, "disk group")
|
||||||
|
usage, health = column(row, "usage"), column(row, "health")
|
||||||
|
export.disks.append(
|
||||||
|
MSADisk(
|
||||||
|
enclosure=enclosure,
|
||||||
|
slot=slot,
|
||||||
|
status=map_status(usage, health),
|
||||||
|
disk_type=disk_type,
|
||||||
|
interface=interface,
|
||||||
|
capacity_gb=capacity,
|
||||||
|
disk_group="" if group.casefold() in NO_GROUP else group,
|
||||||
|
serial=column(row, "serial number"),
|
||||||
|
manufacturer=column(row, "manufacturer"),
|
||||||
|
model=column(row, "model"),
|
||||||
|
firmware=column(row, "revision"),
|
||||||
|
power_on_hours=_int(column(row, "power on hours")) if column(row, "power on hours") else None,
|
||||||
|
usage=usage,
|
||||||
|
health=health,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if not export.disks and not export.errors:
|
||||||
|
export.errors.append("Die Datei enthält keine Datenträger.")
|
||||||
|
return export
|
||||||
|
|
||||||
|
|
||||||
|
def suggest_slot_count(highest_slot):
|
||||||
|
"""Common MSA enclosure sizes: 12 LFF or 24 SFF bays; anything bigger is taken as is."""
|
||||||
|
for size in (12, 24):
|
||||||
|
if highest_slot <= size:
|
||||||
|
return size
|
||||||
|
return highest_slot
|
||||||
|
|
||||||
|
|
||||||
|
def suggest_form_factor(slot_count):
|
||||||
|
return "3.5" if slot_count == 12 else "2.5" if slot_count == 24 else ""
|
||||||
|
|
||||||
|
|
||||||
|
ACTION_NEW = "new"
|
||||||
|
ACTION_UPDATE = "update"
|
||||||
|
ACTION_REPLACE = "replace"
|
||||||
|
ACTION_SKIP = "skip"
|
||||||
|
ACTION_CONFLICT = "conflict"
|
||||||
|
|
||||||
|
ACTION_LABELS = {
|
||||||
|
ACTION_NEW: ("Neu", "success"),
|
||||||
|
ACTION_UPDATE: ("Aktualisieren", "info"),
|
||||||
|
ACTION_REPLACE: ("Ersetzt vorhandenen", "warning"),
|
||||||
|
ACTION_SKIP: ("Übersprungen", "secondary"),
|
||||||
|
ACTION_CONFLICT: ("Konflikt", "danger"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def classify(disk, first_slot, last_slot, occupant_serial=None, serial_elsewhere=None, replace=False):
|
||||||
|
"""Decide what happens to one exported disk; returns (action, reason).
|
||||||
|
|
||||||
|
occupant_serial: serial of the disk currently in the target slot ("" if it has none,
|
||||||
|
None if the slot is free). serial_elsewhere: label of another slot that already
|
||||||
|
holds this serial, if any.
|
||||||
|
"""
|
||||||
|
if not first_slot <= disk.slot <= last_slot:
|
||||||
|
return ACTION_CONFLICT, f"Steckplatz {disk.slot} liegt außerhalb des Bereichs ({first_slot}–{last_slot})."
|
||||||
|
if disk.serial and serial_elsewhere:
|
||||||
|
return ACTION_CONFLICT, f"Seriennummer steckt laut NetBox bereits in {serial_elsewhere}."
|
||||||
|
if occupant_serial is None:
|
||||||
|
return ACTION_NEW, ""
|
||||||
|
if disk.serial and occupant_serial.casefold() == disk.serial.casefold():
|
||||||
|
return ACTION_UPDATE, ""
|
||||||
|
if replace:
|
||||||
|
return (
|
||||||
|
ACTION_REPLACE,
|
||||||
|
f"Bisheriger Datenträger {occupant_serial or '(ohne Seriennummer)'} wird als ausgebaut markiert.",
|
||||||
|
)
|
||||||
|
return ACTION_SKIP, f"Steckplatz ist mit {occupant_serial or 'einem Datenträger ohne Seriennummer'} belegt."
|
||||||
@@ -38,6 +38,12 @@ menu = PluginMenu(
|
|||||||
icon_class="mdi mdi-upload",
|
icon_class="mdi mdi-upload",
|
||||||
permissions=("netbox_utilities.add_disk",),
|
permissions=("netbox_utilities.add_disk",),
|
||||||
),
|
),
|
||||||
|
PluginMenuButton(
|
||||||
|
link="plugins:netbox_utilities:disk_msa_import",
|
||||||
|
title="HPE-MSA-Export importieren",
|
||||||
|
icon_class="mdi mdi-database-import",
|
||||||
|
permissions=("netbox_utilities.add_disk",),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
PluginMenuItem(
|
PluginMenuItem(
|
||||||
|
|||||||
@@ -116,6 +116,11 @@
|
|||||||
<a href="{% url 'plugins:netbox_utilities:disk_list' %}?device_id={{ object.pk }}" class="btn btn-sm btn-outline-secondary">
|
<a href="{% url 'plugins:netbox_utilities:disk_list' %}?device_id={{ object.pk }}" class="btn btn-sm btn-outline-secondary">
|
||||||
<i class="mdi mdi-table" aria-hidden="true"></i> Liste & Export
|
<i class="mdi mdi-table" aria-hidden="true"></i> Liste & Export
|
||||||
</a>
|
</a>
|
||||||
|
{% if perms.netbox_utilities.add_disk %}
|
||||||
|
<a href="{% url 'plugins:netbox_utilities:disk_msa_import' %}" class="btn btn-sm btn-outline-secondary" title="Datenträger-Export einer HPE MSA importieren">
|
||||||
|
<i class="mdi mdi-database-import" aria-hidden="true"></i> MSA-Import
|
||||||
|
</a>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="nbu-disk-bays"
|
<div id="nbu-disk-bays"
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
{% extends 'base/layout.html' %}
|
||||||
|
|
||||||
|
{% block title %}HPE-MSA-Export importieren{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="row mb-3">
|
||||||
|
<div class="col col-xl-10 offset-xl-1">
|
||||||
|
|
||||||
|
<ol class="nbu-msa-steps list-inline small text-muted mb-3">
|
||||||
|
<li class="list-inline-item{% if step == 'upload' %} fw-bold text-body{% endif %}">1. Export hochladen</li>
|
||||||
|
<li class="list-inline-item">›</li>
|
||||||
|
<li class="list-inline-item{% if step == 'assign' %} fw-bold text-body{% endif %}">2. Shelfs zuordnen</li>
|
||||||
|
<li class="list-inline-item">›</li>
|
||||||
|
<li class="list-inline-item{% if step == 'plan' %} fw-bold text-body{% endif %}">3. Prüfen & importieren</li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
{% if parse_errors %}
|
||||||
|
<div class="alert alert-warning">
|
||||||
|
<strong>Einige Zeilen wurden ignoriert:</strong>
|
||||||
|
<ul class="mb-0">{% for error in parse_errors %}<li>{{ error }}</li>{% endfor %}</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if step == 'upload' %}
|
||||||
|
<form method="post" enctype="multipart/form-data" class="card">
|
||||||
|
{% csrf_token %}
|
||||||
|
<input type="hidden" name="step" value="upload">
|
||||||
|
<h2 class="card-header"><i class="mdi mdi-database-import me-1" aria-hidden="true"></i>HPE-MSA-Export importieren</h2>
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="text-muted">
|
||||||
|
In der MSA-Oberfläche unter <em>Pools → Disks</em> (bzw. <em>System → Disks</em>) die Liste als CSV exportieren.
|
||||||
|
Die Spalte <em>Location</em> (z. B. <code>1.4</code>) enthält Shelf und Steckplatz.
|
||||||
|
</p>
|
||||||
|
{% if upload_form.non_field_errors %}<div class="alert alert-danger">{{ upload_form.non_field_errors }}</div>{% endif %}
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="{{ upload_form.export_file.id_for_label }}">{{ upload_form.export_file.label }}</label>
|
||||||
|
{{ upload_form.export_file }}
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="{{ upload_form.export_text.id_for_label }}">{{ upload_form.export_text.label }}</label>
|
||||||
|
{{ upload_form.export_text }}
|
||||||
|
</div>
|
||||||
|
<div class="text-end">
|
||||||
|
<button type="submit" class="btn btn-primary">Weiter</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{% else %}
|
||||||
|
<form method="post">
|
||||||
|
{% csrf_token %}
|
||||||
|
<input type="hidden" name="export_data" value="{{ export_data }}">
|
||||||
|
|
||||||
|
{% if step == 'assign' %}
|
||||||
|
<input type="hidden" name="step" value="assign">
|
||||||
|
{% if assign_form.non_field_errors %}<div class="alert alert-danger">{{ assign_form.non_field_errors }}</div>{% endif %}
|
||||||
|
<div class="card mb-3">
|
||||||
|
<h2 class="card-header"><i class="mdi mdi-server me-1" aria-hidden="true"></i>Welches Gerät ist welches Shelf?</h2>
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="text-muted">Shelf 1 ist in der Regel der Controller-Einschub, weitere Nummern sind Erweiterungs-Shelfs. Shelfs ohne Gerät werden übersprungen.</p>
|
||||||
|
<table class="table table-hover align-middle">
|
||||||
|
<thead><tr><th>Shelf</th><th>Datenträger</th><th>Modelle</th><th style="min-width: 20rem">Gerät in NetBox</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for enclosure in enclosures %}
|
||||||
|
<tr>
|
||||||
|
<td class="fw-bold">{{ enclosure.id }}</td>
|
||||||
|
<td>{{ enclosure.count }} <span class="text-muted small">(Steckplatz {{ enclosure.first }}–{{ enclosure.last }})</span></td>
|
||||||
|
<td class="small">{{ enclosure.models|join:", " }}</td>
|
||||||
|
<td>
|
||||||
|
{{ enclosure.field }}
|
||||||
|
{% for error in enclosure.field.errors %}<div class="text-danger small">{{ error }}</div>{% endfor %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<h2 class="card-header">Optionen</h2>
|
||||||
|
<div class="card-body">
|
||||||
|
{% for field in assign_form.option_fields %}
|
||||||
|
<div class="form-check form-switch mb-2">
|
||||||
|
{{ field }}
|
||||||
|
<label class="form-check-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
|
||||||
|
<div class="form-text">{{ field.help_text }}</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="text-end">
|
||||||
|
<a href="{% url 'plugins:netbox_utilities:disk_msa_import' %}" class="btn btn-outline-secondary">Andere Datei</a>
|
||||||
|
<button type="submit" class="btn btn-primary">Weiter zur Vorschau</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% else %}
|
||||||
|
<input type="hidden" name="step" value="plan">
|
||||||
|
{# Carry the assignment of step 2 along. #}
|
||||||
|
{% for enclosure, field in assign_form.device_fields %}
|
||||||
|
{% if field.value %}<input type="hidden" name="{{ field.html_name }}" value="{{ field.value }}">{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
{% for field in assign_form.option_fields %}
|
||||||
|
{% if field.value %}<input type="hidden" name="{{ field.html_name }}" value="on">{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
{% for plan in plans %}
|
||||||
|
<div class="card mb-3">
|
||||||
|
<h2 class="card-header">
|
||||||
|
<i class="mdi mdi-server me-1" aria-hidden="true"></i>
|
||||||
|
Shelf {{ plan.enclosure }} → <a href="{% url 'dcim:device_disks' pk=plan.device.pk %}" target="_blank">{{ plan.device }}</a>
|
||||||
|
<span class="badge text-bg-secondary ms-2">{{ plan.importing }} von {{ plan.rows|length }} werden importiert</span>
|
||||||
|
</h2>
|
||||||
|
<div class="card-body">
|
||||||
|
{% if plan.bay_form %}
|
||||||
|
<div class="alert alert-warning">
|
||||||
|
<i class="mdi mdi-alert" aria-hidden="true"></i>
|
||||||
|
<strong>{{ plan.device }} hat noch keine Datenträger-Steckplätze.</strong>
|
||||||
|
Der folgende Bereich wird beim Import angelegt – bitte prüfen und bei Bedarf anpassen, dann „Vorschau aktualisieren“.
|
||||||
|
</div>
|
||||||
|
{% include 'netbox_utilities/inc/disk_layout_fields.html' with form=plan.bay_form %}
|
||||||
|
{% elif plan.bays|length > 1 %}
|
||||||
|
<div class="mb-3" style="max-width: 24rem">
|
||||||
|
<label class="form-label" for="bay_{{ plan.enclosure }}">Bereich</label>
|
||||||
|
<select name="bay_{{ plan.enclosure }}" id="bay_{{ plan.enclosure }}" class="form-select">
|
||||||
|
{% for bay in plan.bays %}
|
||||||
|
<option value="{{ bay.pk }}"{% if bay.pk == plan.bay.pk %} selected{% endif %}>{{ bay.name }} ({{ bay.first_slot }}–{{ bay.last_slot }})</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<input type="hidden" name="bay_{{ plan.enclosure }}" value="{{ plan.bay.pk }}">
|
||||||
|
<p class="text-muted">Bereich: <strong>{{ plan.bay.name }}</strong> (Steckplatz {{ plan.bay.first_slot }}–{{ plan.bay.last_slot }})</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if plan.groups and assign_form.cleaned_data.create_raid_groups %}
|
||||||
|
<p class="small text-muted mb-2">Disk Groups: {{ plan.groups|join:", " }}</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-sm table-hover align-middle mb-0">
|
||||||
|
<thead>
|
||||||
|
<tr><th>Slot</th><th>Aktion</th><th>Status</th><th>Typ</th><th>Größe</th><th>Modell</th><th>Seriennummer</th><th>Disk Group</th><th>Firmware</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in plan.rows %}
|
||||||
|
<tr{% if row.action == 'conflict' or row.action == 'skip' %} class="text-muted"{% endif %}>
|
||||||
|
<td>{{ row.item.slot }}</td>
|
||||||
|
<td>
|
||||||
|
<span class="badge text-bg-{{ row.color }}">{{ row.label }}</span>
|
||||||
|
{% if row.reason %}<div class="small">{{ row.reason }}</div>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td>{{ row.item.usage }}{% if row.item.health and row.item.health != 'OK' %} <span class="badge text-bg-danger">{{ row.item.health }}</span>{% endif %}</td>
|
||||||
|
<td>{{ row.item.disk_type|upper }} {{ row.item.interface|upper }}</td>
|
||||||
|
<td>{{ row.capacity }}</td>
|
||||||
|
<td>{{ row.item.manufacturer }} {{ row.item.model }}</td>
|
||||||
|
<td class="font-monospace">{{ row.item.serial }}</td>
|
||||||
|
<td>{{ row.item.disk_group|default:"—" }}</td>
|
||||||
|
<td>{{ row.item.firmware }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
<div class="d-flex flex-wrap gap-2">
|
||||||
|
<button type="submit" name="step" value="back" class="btn btn-outline-secondary me-auto">Zurück</button>
|
||||||
|
<button type="submit" class="btn btn-outline-primary">Vorschau aktualisieren</button>
|
||||||
|
<button type="submit" name="do_import" value="1" class="btn btn-primary">
|
||||||
|
<i class="mdi mdi-check" aria-hidden="true"></i> Importieren
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock content %}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from django.test import SimpleTestCase
|
||||||
|
|
||||||
|
from netbox_utilities import disks, msa_import
|
||||||
|
|
||||||
|
EXPORT = """Location,Health,Type,Size,Usage,Disk Group,Status,Serial Number,r/min,Manufacturer,Model,Revision,Power On Hours,FDE State,FDE Lock Key,Sector Format
|
||||||
|
1.1,OK,SSD SAS,745.2GiB,VIRTUAL POOL,rcA1,Up,Z8713PT50000822150Z3,0k,SEAGATE,ST800FM0403,0007,70425,Not FDE Capable,00000000,512e
|
||||||
|
1.11,OK,SAS,558.9GiB,GLOBAL SP,-,Up,X4T0A00LFJVL,10k,HPE,EG000600JWJNH,HPD5,1803,Not FDE Capable,00000000,512n
|
||||||
|
1.3,Fault,SAS,558.9GiB,VIRTUAL POOL,dgA01,Up,WFJ0KKMY,10k,HP,EG000600JWJNP,HPD1,70425,Not FDE Capable,00000000,512n
|
||||||
|
2.1,OK,SAS,558.9GiB,VIRTUAL POOL,dgB01,Up,WFJ0KGPR,10k,HP,EG000600JWJNP,HPD1,70425,Not FDE Capable,00000000,512n
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class ParseExportTest(SimpleTestCase):
|
||||||
|
def test_parses_enclosures_slots_and_fields(self):
|
||||||
|
export = msa_import.parse_export(EXPORT.encode("utf-8"))
|
||||||
|
self.assertEqual(export.errors, [])
|
||||||
|
enclosures = export.enclosures
|
||||||
|
self.assertEqual(list(enclosures), ["1", "2"])
|
||||||
|
self.assertEqual([disk.slot for disk in enclosures["1"]], [1, 3, 11])
|
||||||
|
|
||||||
|
ssd = enclosures["1"][0]
|
||||||
|
self.assertEqual((ssd.disk_type, ssd.interface), ("ssd", "sas"))
|
||||||
|
self.assertEqual(ssd.capacity_gb, 800)
|
||||||
|
self.assertEqual(ssd.disk_group, "rcA1")
|
||||||
|
self.assertEqual(ssd.firmware, "0007")
|
||||||
|
self.assertEqual(ssd.power_on_hours, 70425)
|
||||||
|
self.assertEqual(ssd.status, disks.STATUS_ACTIVE)
|
||||||
|
|
||||||
|
def test_maps_spares_failed_disks_and_missing_groups(self):
|
||||||
|
by_slot = {disk.slot: disk for disk in msa_import.parse_export(EXPORT).enclosures["1"]}
|
||||||
|
self.assertEqual(by_slot[11].status, disks.STATUS_SPARE)
|
||||||
|
self.assertEqual(by_slot[11].disk_group, "")
|
||||||
|
self.assertEqual(by_slot[3].status, disks.STATUS_FAILED)
|
||||||
|
self.assertEqual((by_slot[3].disk_type, by_slot[3].capacity_gb), ("hdd", 600))
|
||||||
|
|
||||||
|
def test_semicolon_csv_from_excel(self):
|
||||||
|
text = "Location;Type;Serial Number\n1.4;SATA;ABC\n"
|
||||||
|
disk = msa_import.parse_export(text).disks[0]
|
||||||
|
self.assertEqual((disk.enclosure, disk.slot, disk.serial, disk.interface), ("1", 4, "ABC", "sata"))
|
||||||
|
|
||||||
|
def test_rejects_other_files_and_bad_rows(self):
|
||||||
|
self.assertTrue(msa_import.parse_export("Name,Serial\nfoo,bar\n").errors)
|
||||||
|
export = msa_import.parse_export("Location\n1.x\n1.2\n1.2\n")
|
||||||
|
self.assertEqual(len(export.disks), 1)
|
||||||
|
self.assertEqual(len(export.errors), 2)
|
||||||
|
|
||||||
|
|
||||||
|
class SuggestionTest(SimpleTestCase):
|
||||||
|
def test_slot_count_rounds_up_to_enclosure_sizes(self):
|
||||||
|
self.assertEqual(msa_import.suggest_slot_count(11), 12)
|
||||||
|
self.assertEqual(msa_import.suggest_slot_count(21), 24)
|
||||||
|
self.assertEqual(msa_import.suggest_slot_count(30), 30)
|
||||||
|
self.assertEqual(msa_import.suggest_form_factor(24), "2.5")
|
||||||
|
|
||||||
|
|
||||||
|
class ClassifyTest(SimpleTestCase):
|
||||||
|
disk = SimpleNamespace(slot=4, serial="ABC")
|
||||||
|
|
||||||
|
def test_free_slot_is_new(self):
|
||||||
|
self.assertEqual(msa_import.classify(self.disk, 1, 24)[0], msa_import.ACTION_NEW)
|
||||||
|
|
||||||
|
def test_same_serial_updates(self):
|
||||||
|
self.assertEqual(msa_import.classify(self.disk, 1, 24, occupant_serial="abc")[0], msa_import.ACTION_UPDATE)
|
||||||
|
|
||||||
|
def test_other_disk_is_skipped_or_replaced(self):
|
||||||
|
self.assertEqual(msa_import.classify(self.disk, 1, 24, occupant_serial="XYZ")[0], msa_import.ACTION_SKIP)
|
||||||
|
self.assertEqual(
|
||||||
|
msa_import.classify(self.disk, 1, 24, occupant_serial="XYZ", replace=True)[0], msa_import.ACTION_REPLACE
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_conflicts(self):
|
||||||
|
self.assertEqual(msa_import.classify(self.disk, 1, 3)[0], msa_import.ACTION_CONFLICT)
|
||||||
|
self.assertEqual(
|
||||||
|
msa_import.classify(self.disk, 1, 24, serial_elsewhere="MSA2 – Front 7")[0], msa_import.ACTION_CONFLICT
|
||||||
|
)
|
||||||
@@ -18,6 +18,7 @@ urlpatterns = [
|
|||||||
path("settings/", views.UtilitiesSettingsView.as_view(), name="settings"),
|
path("settings/", views.UtilitiesSettingsView.as_view(), name="settings"),
|
||||||
path("tenant/select/", views.SelectTenantView.as_view(), name="select_tenant"),
|
path("tenant/select/", views.SelectTenantView.as_view(), name="select_tenant"),
|
||||||
# Datenträger
|
# Datenträger
|
||||||
|
path("disks/import-msa/", disk_views.MSADiskImportView.as_view(), name="disk_msa_import"),
|
||||||
path("disks/by-device/", disk_views.DiskByDeviceView.as_view(), name="disk_by_device"),
|
path("disks/by-device/", disk_views.DiskByDeviceView.as_view(), name="disk_by_device"),
|
||||||
path("disks/", include(get_model_urls("netbox_utilities", "disk", detail=False))),
|
path("disks/", include(get_model_urls("netbox_utilities", "disk", detail=False))),
|
||||||
path("disks/<int:pk>/", include(get_model_urls("netbox_utilities", "disk"))),
|
path("disks/<int:pk>/", include(get_model_urls("netbox_utilities", "disk"))),
|
||||||
|
|||||||
Reference in new issue
Block a user