Ejemplo n.º 1
0
    def setUp(self):
        user = create_test_user(permissions=['dcim.view_inventoryitem'])
        self.client = Client()
        self.client.force_login(user)

        site = Site(name='Site 1', slug='site-1')
        site.save()

        manufacturer = Manufacturer(name='Manufacturer 1',
                                    slug='manufacturer-1')
        manufacturer.save()

        devicetype = DeviceType(model='Device Type 1',
                                manufacturer=manufacturer)
        devicetype.save()

        devicerole = DeviceRole(name='Device Role 1', slug='device-role-1')
        devicerole.save()

        device = Device(name='Device 1',
                        site=site,
                        device_type=devicetype,
                        device_role=devicerole)
        device.save()

        InventoryItem.objects.bulk_create([
            InventoryItem(device=device, name='Inventory Item 1'),
            InventoryItem(device=device, name='Inventory Item 2'),
            InventoryItem(device=device, name='Inventory Item 3'),
        ])
Ejemplo n.º 2
0
    def setUp(self):

        self.client = Client()

        site = Site(name='Site 1', slug='site-1')
        site.save()

        manufacturer = Manufacturer(name='Manufacturer 1',
                                    slug='manufacturer-1')
        manufacturer.save()

        devicetype = DeviceType(model='Device Type 1',
                                manufacturer=manufacturer)
        devicetype.save()

        devicerole = DeviceRole(name='Device Role 1', slug='device-role-1')
        devicerole.save()

        device = Device(name='Device 1',
                        site=site,
                        device_type=devicetype,
                        device_role=devicerole)
        device.save()

        InventoryItem.objects.bulk_create([
            InventoryItem(device=device, name='Inventory Item 1'),
            InventoryItem(device=device, name='Inventory Item 2'),
            InventoryItem(device=device, name='Inventory Item 3'),
        ])
Ejemplo n.º 3
0
 def create_inventory_items(inventory_items, parent=None):
     for item in inventory_items:
         i = InventoryItem(device=device,
                           parent=parent,
                           name=item['name'],
                           part_id=item['part_id'],
                           serial=item['serial'],
                           discovered=True)
         i.save()
         create_inventory_items(item.get('items', []), parent=i)
Ejemplo n.º 4
0
def sync_inventory(device, conn, parser):
    ''' Get list of parsed inventory commands
        And add it into netbox device inventory
    '''
    command = {'Command': 'sh inventory'}
    output = conn.cli([command['Command']])
    output = output[command['Command']]

    # print("Output is {}".format(output))
    if output:
        parser.ParseCmd(output, command)
        result = [list(row) for row in parser]

        if result:
            for item in result:
                name = item[0]
                descr = item[1]
                pid = item[2]
                serial = item[4]

                # Check, if this item exists (by device, name and serial)
                item = InventoryItem.objects.filter(device=device,
                                                    name=name,
                                                    serial=serial)

                if item:
                    print("Device {} alredy have a item {}".format(
                        device.name, name))
                    continue
                else:
                    print("Tries to add a item {} on device {}".format(
                        device.name, name))
                    item = InventoryItem()
                    item.manufacturer = device.device_type.manufacturer
                    item.name = name.strip('"')
                    item.part_id = pid
                    item.serial = serial
                    item.description = descr.strip('"')
                    item.device = device
                    item.save()
        else:
            print("Cannot parse output of command")
    else:
        print("Cannot do a command {} on device".format(command))
Ejemplo n.º 5
0
def server_bmc_get(device_id):
    """To group all `get_` calls.

    It turned out that BMC only allows **1** SSH session
    at a time. The consequetive SSH call will return an error

    ```
    X11 forwarding request failed on channel 0
    Connection to 10.240.41.254 closed.
    ```

    Args:
      device_id: host server id. This device should have a property `bmc_access`
        which has BMC (ip, secret). We are **ASSUMING** that a device has ONE BMC.
    """
    server = Device.objects.get(id=device_id)
    the_bmc = server.bmc_controllers[0]

    ip, secret = server.bmc_access
    print "reading server %s BMC name" % ip

    cli = BmcByCli(ip, secret.name, secret.password)

    if not cli.connect():
        print "Access to BMC %s has failed. abort." % ip
        the_bmc.status = DEVICE_STATUS_OFFLINE
        server.save()
        the_bmc.save()
        return
    else:
        the_bmc.status = DEVICE_STATUS_ACTIVE

    # server name
    # Example output:
    #
    # ```
    # SystemName: brain4-3
    # ContactPerson:
    # Location:
    # FullPostalAddress:
    # RoomID:
    # RackID:
    # LowestU: 0
    # HeightU: 2
    # ```
    #
    # This is the name by BMC, not FQDN or hostname that OS represents.
    name = filter(lambda x: "SystemName" in x, cli.get_name().split("\n"))
    name = re.search("SystemName:(?P<name>.+)", name[0]).group("name").strip()
    if not server.name:
        server.name = name

    the_bmc.name = "%s BMC" % name

    # eth0 mac
    # Example output:
    #
    # ```
    # -b      :  08:94:ef:48:13:3d
    # ```
    mac = cli.get_eth0_mac()
    mac = re.search("b\s+:(?P<mac>.*)", mac).group("mac").strip().upper()
    existings = Interface.objects.filter(mac_address=mac)
    if existings:
        i = existings[0]
    else:
        i = Interface(device=server)

    i.device = the_bmc
    i.name = "eth0"
    i.type = INTERFACE_TYPE_MANAGEMENT
    i.mgmt_only = True
    i.mac_address = mac
    i.save()

    # link Interface to its primary IP
    the_bmc.primary_ip4.interface = i
    the_bmc.primary_ip4.save()

    # vpd sys
    # To get serial number, uuid of this device.
    #
    # Example output:
    # ```
    # Machine Type-Model             Serial Number                  UUID
    # --------------                 ---------                      ----
    # 8871AC1                        J11PGTT                        60CD7A22827E11E79D09089    # ```
    tmp = re.split("-+", cli.get_vpd_sys())
    sys_info = re.split("\s+", tmp[-1].strip())[:3]

    the_bmc.serial = ""
    the_bmc.asset_tag = ""
    the_bmc.save()

    server.serial = sys_info[1]
    if server.asset_tag != sys_info[2]:
        if Device.objects.filter(asset_tag=sys_info[2]):
            # wow we have someone who already owned this tag!
            # Create a random uuid one.
            server.asset_tag = "Generated %s" % str(uuid.uuid4())
        else:
            server.asset_tag = sys_info[2]
    server.save()

    server.device_type.part_number = sys_info[0]
    server.device_type.save()

    # get server's power state
    power = filter(lambda x: "power" in x, cli.get_name().split("\n"))
    for p in power:
        state = re.search("power\s(?P<state>.+)", power).group("state").strip()
        if state == "off":
            server.status = DEVICE_STATUS_POWERED_OFF
        elif state == "on":
            # Note: server BMC indicates `power on`, but OS may still
            # be in off state.
            pass
    server.save()

    # dump raid controllers inside server
    for c in cli.get_storage_controllers():
        # manufacturer
        m, whatever = Manufacturer.objects.get_or_create(
            name=c["manufacturer"].strip(),
            slug=c["manufacturer"].lower().strip())

        # device type
        model = c["model"]
        existing = DeviceType.objects.filter(slug=slugify(model))
        if existing:
            dt = existing[0]
        else:
            dt, whatever = DeviceType.objects.get_or_create(
                manufacturer=m,
                model=model,
                slug=slugify(model),
                part_number=c["part_id"].strip(),
                u_height=0,  # TODO: hardcoded special value!
                is_network_device=False,
                subdevice_role=SUBDEVICE_ROLE_CHILD)

        # items
        asset_tag = c["asset_tag"].strip()
        serial = c["serial"].strip()
        if not asset_tag:
            existing = InventoryItem.objects.filter(asset_tag=asset_tag)
        else:
            existing = InventoryItem.objects.filter(serial=serial)

        if existing:
            item = existing[0]
        else:  # inventory item
            item = InventoryItem(
                device=server,
                manufacturer=m,
                discovered=True,
                asset_tag=c["asset_tag"].strip(),
            )

        item.device_type = dt
        item.name = c["target"]
        item.part_id = c["part_id"].strip()
        item.serial = c["serial"].strip()
        item.description = convert_to_html_table(c["description"], ":")
        item.save()

    # dump disks inside server
    for c in cli.get_storage_drives():
        # manufacturer
        m, whatever = Manufacturer.objects.get_or_create(
            name=c["manufacturer"].strip(),
            slug=c["manufacturer"].lower().strip())

        # device type
        model = "/".join(
            filter(lambda x: x, [c["name"], c["disk_type"], c["media_type"]]))
        existing = DeviceType.objects.filter(slug=slugify(model))
        if existing:
            dt = existing[0]
        else:
            dt, whatever = DeviceType.objects.get_or_create(
                manufacturer=m,
                model=model,
                slug=slugify(model),
                part_number=c["part_id"].strip(),
                u_height=0,  # TODO: hardcoded special value!
                is_network_device=False,
                subdevice_role=SUBDEVICE_ROLE_CHILD)

        # inventory item
        item, whatever = InventoryItem.objects.get_or_create(
            device=server,
            manufacturer=m,
            device_type=dt,
            discovered=True,
            name=c["target"],
            part_id=c["part_id"].strip(),
            serial=c["serial"].strip(),
        )
        item.description = convert_to_html_table(c["description"], ":")
        item.save()

    # dump fw
    tmp = cli.get_firmware_status()
    tmp = re.sub("-", "", tmp)
    item, whatever = InventoryItem.objects.get_or_create(
        device=server,
        name="firmware",
        discovered=True,
    )
    item.description = convert_to_html_table(tmp)
    item.save()
Ejemplo n.º 6
0
 def create_inventory_items(inventory_items, parent=None):
     for item in inventory_items:
         i = InventoryItem(device=device, parent=parent, name=item['name'], part_id=item['part_id'],
                           serial=item['serial'], discovered=True)
         i.save()
         create_inventory_items(item.get('items', []), parent=i)
Ejemplo n.º 7
0
        else:
            manufacturer = device.device_type.manufacturer

        # Check, if this item exists (by device, name and serial)
        item = InventoryItem.objects.filter(device=device,
                                            name=name,
                                            serial=serial,
                                            discovered=True)
        if item:
            logger.info("Device {} already have a discovered item {}".format(
                device.name, name))
            continue
        else:
            logger.info("Tries to add a item {} on device {}".format(
                name, device.name))
            item = InventoryItem()
            item.manufacturer = manufacturer
            item.name = name
            item.part_id = pid
            item.serial = serial
            item.description = descr
            item.device = device
            item.discovered = True
            try:
                item.save()
                is_changed = True
            except Exception as e:
                logger.warning(
                    "Error to save Inventory item with name {} to device {}. Error is {}"
                    .format(name, device.name, e))
    if is_changed: