コード例 #1
0
 public static function setUpBeforeClass()
 {
     // add sample locations
     self::$first_location_id = $parent_location_id = commitAddObject('unit test location 0', NULL, 1562, NULL);
     for ($i = 1; $i <= self::$num_children; $i++) {
         $child_location_id = commitAddObject("unit test location {$i}", NULL, 1562, NULL);
         commitLinkEntities('location', $parent_location_id, 'location', $child_location_id);
         $parent_location_id = $child_location_id;
     }
     self::$last_location_id = $parent_location_id;
     // add sample objects
     usePreparedInsertBlade('Dictionary', array('chapter_id' => 1, 'dict_value' => 'unit test object type'));
     self::$objtype_id = lastInsertID();
     commitSupplementOPC(self::$objtype_id, self::$objtype_id);
     self::$first_object_id = $parent_object_id = commitAddObject('unit test object 0', NULL, self::$objtype_id, NULL);
     for ($i = 1; $i <= self::$num_children; $i++) {
         $child_object_id = commitAddObject("unit test object {$i}", NULL, self::$objtype_id, NULL);
         commitLinkEntities('object', $parent_object_id, 'object', $child_object_id);
         $parent_object_id = $child_object_id;
     }
     self::$last_object_id = $parent_object_id;
     // add sample tags
     usePreparedInsertBlade('TagTree', array('tag' => 'unit test tag 0'));
     self::$first_tag_id = $parent_tag_id = lastInsertID();
     for ($i = 1; $i <= self::$num_children; $i++) {
         usePreparedInsertBlade('TagTree', array('parent_id' => $parent_tag_id, 'tag' => "unit test tag {$i}"));
         $parent_tag_id = lastInsertID();
     }
     self::$last_tag_id = $parent_tag_id;
 }
コード例 #2
0
 public static function setUpBeforeClass()
 {
     // add sample data
     usePreparedInsertBlade('Dictionary', array('chapter_id' => 1, 'dict_value' => 'unit test object type a'));
     self::$objtypea_id = lastInsertID();
     usePreparedInsertBlade('Dictionary', array('chapter_id' => 1, 'dict_value' => 'unit test object type b'));
     self::$objtypeb_id = lastInsertID();
     usePreparedInsertBlade('Dictionary', array('chapter_id' => 1, 'dict_value' => 'unit test object type c'));
     self::$objtypec_id = lastInsertID();
     usePreparedInsertBlade('Dictionary', array('chapter_id' => 1, 'dict_value' => 'unit test object type d'));
     self::$objtyped_id = lastInsertID();
     commitSupplementOPC(self::$objtypea_id, self::$objtypeb_id);
     commitSupplementOPC(self::$objtypea_id, self::$objtypec_id);
     commitSupplementOPC(self::$objtypeb_id, self::$objtypea_id);
     commitSupplementOPC(self::$objtypeb_id, self::$objtypec_id);
     commitSupplementOPC(self::$objtypec_id, self::$objtypea_id);
     commitSupplementOPC(self::$objtypec_id, self::$objtypeb_id);
     self::$objecta_id = commitAddObject('unit test object a', NULL, self::$objtypea_id, NULL);
     self::$objectb_id = commitAddObject('unit test object b', NULL, self::$objtypeb_id, NULL);
     self::$objectc_id = commitAddObject('unit test object c', NULL, self::$objtypec_id, NULL);
     self::$objectd_id = commitAddObject('unit test object d', NULL, self::$objtyped_id, NULL);
     self::$locationa_id = commitAddObject('unit test location a', NULL, 1562, NULL);
     self::$locationb_id = commitAddObject('unit test location b', NULL, 1562, NULL);
     self::$locationc_id = commitAddObject('unit test location c', NULL, 1562, NULL);
     self::$rowa_id = commitAddObject('unit test row a', NULL, 1561, NULL);
     self::$rowb_id = commitAddObject('unit test row b', NULL, 1561, NULL);
     self::$racka_id = commitAddObject('unit test rack a', NULL, 1560, NULL);
     self::$rackb_id = commitAddObject('unit test rack b', NULL, 1560, NULL);
 }
コード例 #3
0
 public function setUp()
 {
     // create a nameless shelf which contains a modem (re: ticket #1115)
     $this->shelf_id = commitAddObject(NULL, NULL, 3, NULL);
     $this->modem_id = commitAddObject('unit test modem', NULL, 13, NULL);
     commitLinkEntities('object', $this->shelf_id, 'object', $this->modem_id);
 }
コード例 #4
0
ファイル: importer.php プロジェクト: xtha/salt
/** Create a new Virtual Machine Pool
	@param		name	Pool name
	@param		tagid	Tag ID to use for this new VM
	@returns 	poolID	ID of new VMPool object
*/
function createVMPool($name, $tagid)
{
    // Get "VM Cluster" dict key
    $vmClusterTypeID = usePreparedSelectBlade("select * from Dictionary where dict_value = 'VM Cluster'")->fetch(PDO::FETCH_ASSOC);
    $vmClusterTypeID = $vmClusterTypeID['dict_key'];
    // Add the pool, with the proper type and tags
    $taglist = array($tagid);
    $poolID = commitAddObject($name, $name, $vmClusterTypeID, '', $taglist);
    // return the pool ID
    return $poolID;
}
コード例 #5
0
 public static function setUpBeforeClass()
 {
     // make sure AUTOPORTS_CONFIG is empty
     self::$autoports_config_var = getConfigVar('AUTOPORTS_CONFIG');
     if (self::$autoports_config_var != '') {
         setConfigVar('AUTOPORTS_CONFIG', '');
     }
     // find a port type that is incompatible with 1000Base-T
     $result = usePreparedSelectBlade('SELECT type1 FROM PortCompat WHERE type1 != 24 AND type2 != 24 LIMIT 1');
     self::$portc_type = $result->fetchColumn();
     // add sample data
     //   - set port a & b's type to 1000Base-T
     //   - set port c's type to the incompatible one
     self::$object_id = commitAddObject('unit test object', NULL, 4, NULL);
     self::$porta = commitAddPort(self::$object_id, 'test porta', '1-24', NULL, NULL);
     self::$portb = commitAddPort(self::$object_id, 'test portb', '1-24', NULL, NULL);
     self::$portc = commitAddPort(self::$object_id, 'test portc', self::$portc_type, NULL, NULL);
 }
コード例 #6
0
ファイル: ophandlers.php プロジェクト: xtha/salt
function autoPopulateUCS()
{
    global $ucsproductmap;
    $ucsm_id = getBypassValue();
    $oinfo = spotEntity('object', $ucsm_id);
    $chassis_id = array();
    $done = 0;
    # There are three request parameters (use_terminal_settings, ucs_login and
    # ucs_password) not processed here. These are asserted and used inside
    # queryTerminal().
    try {
        $contents = queryDevice($ucsm_id, 'getinventory');
    } catch (RTGatewayError $e) {
        showError($e->getMessage());
        return;
    }
    foreach ($contents as $item) {
        $mname = preg_replace('#^sys/(.+)$#', $oinfo['name'] . '/\\1', $item['DN']);
        if ($item['type'] == 'NetworkElement') {
            $new_object_id = commitAddObject($mname, NULL, 8, NULL);
            #    Set H/W Type for Network Switch
            if (array_key_exists($item['model'], $ucsproductmap)) {
                commitUpdateAttrValue($new_object_id, 2, $ucsproductmap[$item['model']]);
            }
            #  	 Set Serial#
            commitUpdateAttrValue($new_object_id, 1, $item['serial']);
            commitLinkEntities('object', $ucsm_id, 'object', $new_object_id);
            bindIPToObject(ip_parse($item['OOB']), $new_object_id, 'mgmt0', 'regular');
            $done++;
        } elseif ($item['type'] == 'EquipmentChassis') {
            $chassis_id[$item['DN']] = $new_object_id = commitAddObject($mname, NULL, 1502, NULL);
            #    Set H/W Type for Server Chassis
            if (array_key_exists($item['model'], $ucsproductmap)) {
                commitUpdateAttrValue($new_object_id, 2, $ucsproductmap[$item['model']]);
            }
            #  	 Set Serial#
            commitUpdateAttrValue($new_object_id, 1, $item['serial']);
            commitLinkEntities('object', $ucsm_id, 'object', $new_object_id);
            $done++;
        } elseif ($item['type'] == 'ComputeBlade') {
            if ($item['assigned'] == '') {
                $new_object_id = commitAddObject($mname, NULL, 4, NULL);
            } else {
                $spname = preg_replace('#.+/ls-(.+)#i', '${1}', $item['assigned']) . "(" . $oinfo['name'] . ")";
                $new_object_id = commitAddObject($spname, NULL, 4, NULL);
            }
            #    Set H/W Type for Blade Server
            if (array_key_exists($item['model'], $ucsproductmap)) {
                commitUpdateAttrValue($new_object_id, 2, $ucsproductmap[$item['model']]);
            }
            #  	 Set Serial#
            commitUpdateAttrValue($new_object_id, 1, $item['serial']);
            #  	 Set Slot#
            commitUpdateAttrValue($new_object_id, 28, $item['slot']);
            $parent_name = preg_replace('#^([^/]+)/([^/]+)/([^/]+)$#', '${1}/${2}', $item['DN']);
            if (array_key_exists($parent_name, $chassis_id)) {
                commitLinkEntities('object', $chassis_id[$parent_name], 'object', $new_object_id);
            }
            $done++;
        }
    }
    # endfor
    showSuccess("Auto-populated UCS Domain '{$oinfo['name']}' with {$done} items");
}
コード例 #7
0
function snmpgeneric_tabhandler($object_id)
{
    //	sg_var_dump_html($_POST);
    if (isset($_POST['asnewobject']) && $_POST['asnewobject'] == "1") {
        $newobject_name = $_POST['object_name'];
        $newobject_label = $_POST['object_label'];
        $newobject_type_id = $_POST['object_type_id'];
        $newobject_asset_no = $_POST['object_asset_no'];
        if (sg_checkObjectNameUniqueness($newobject_name, $newobject_type_id)) {
            $object_id = commitAddObject($newobject_name, $newobject_label, $newobject_type_id, $newobject_asset_no);
            $_POST['asnewobject'] = "0";
            parse_str($_SERVER['QUERY_STRING'], $query_string);
            $query_string['object_id'] = $object_id;
            $_SERVER['QUERY_STRING'] = http_build_query($query_string);
            list($path, $qs) = explode('?', $_SERVER['REQUEST_URI'], 2);
            $_SERVER['REQUEST_URI'] = $path . '?' . $_SERVER['QUERY_STRING'];
            // switch to new object
            echo '<body>';
            echo '<body onload="document.forms[\'newobject\'].submit();">';
            echo '<form method=POST id=newobject action=' . $_SERVER['REQUEST_URI'] . '>';
            foreach ($_POST as $name => $value) {
                echo "<input type=hidden name={$name} value={$value}>";
            }
            echo '<input type=submit id="submitbutton" tabindex="1" value="Show List">';
            echo '</from></body>';
            exit;
        } else {
            showError("Object with name: \"{$newobject_name}\" already exists!!!");
            $_POST['snmpconfig'] = "0";
        }
    }
    // save snmp settings
    if (isset($_POST['save']) && $_POST['save'] == "1") {
        // TODO save only on success !!
        $object = spotEntity('object', $object_id);
        $snmpvalues[0] = 'SNMP';
        $snmpnames = array('host', 'version', 'community');
        if ($_POST['version'] == "v3") {
            $snmpnames = array_merge($snmpnames, array('sec_level', 'auth_protocol', 'auth_passphrase', 'priv_protocol', 'priv_passphrase'));
        }
        foreach ($snmpnames as $key => $value) {
            if (isset($_POST[$value])) {
                switch ($value) {
                    case "auth_passphrase":
                    case "priv_passphrase":
                        $snmpvalues[$key + 1] = base64_encode($_POST[$value]);
                        break;
                    default:
                        $snmpvalues[$key + 1] = $_POST[$value];
                }
            }
        }
        //	sg_var_dump_html($snmpvalues);
        $newsnmpstr = implode($snmpvalues, ":");
        $snmpstr = strtok($object['comment'], "\n\r");
        $snmpstrarray = explode(':', $snmpstr);
        $setcomment = "set";
        if ($snmpstrarray[0] == "SNMP") {
            if ($newsnmpstr == $snmpstr) {
                $setcomment = "ok";
            } else {
                $setcomment = "update";
            }
        }
        if ($setcomment != "ok") {
            if ($setcomment == "update") {
                $comment = str_replace($snmpstr, $newsnmpstr, $object['comment']);
            } else {
                $comment = "{$newsnmpstr}\n" . $object['comment'];
            }
            //	echo "$snmpnewstr ".$object['comment']." --> $comment";
            commitUpdateObject($object_id, $object['name'], NULL, $object['has_problems'], NULL, $comment);
            showNotice("{$setcomment} SNMP Settings: {$newsnmpstr}");
        }
    }
    if (isset($_POST['snmpconfig']) && $_POST['snmpconfig'] == '1') {
        snmpgeneric_list($object_id);
    } else {
        snmpgeneric_snmpconfig($object_id);
    }
}
コード例 #8
0
ファイル: snmp.php プロジェクト: ivladdalvi/racktables
function addModules($parent_id, $object_id, $module_key = NULL)
{
    $self = __FUNCTION__;
    global $chapter_to_objtype_map, $known_modules, $iftable_processors, $snmp_data, $objectInfo;
    $count = count($snmp_data['entPhysicalContainedIn']);
    $children = array_keys($snmp_data['entPhysicalContainedIn'], $parent_id);
    foreach ($children as $id) {
        // it should be added as a port
        if (array_key_exists($id, $snmp_data['entToIfMapping'])) {
            addModulePort($id, $object_id, $module_key);
        }
        // it should be added as an object
        foreach ($known_modules as $key => $attr) {
            // the model string may be stored in entPhysicalDescr or entPhysicalModelName
            if (preg_match($attr['pattern'], $snmp_data['entPhysicalDescr'][$id]) or preg_match($attr['pattern'], $snmp_data['entPhysicalModelName'][$id])) {
                $module_key = $key;
                // sometimes ports are registered to a child object such as a motherboard
                // in such cases, we want them assigned to the origin object itself (example: Cisco 2801 ISR)
                if (isset($known_modules[$module_key]['assign_to_origin'])) {
                    addModulePort($id, $object_id, $module_key);
                    break;
                }
                showSuccess($known_modules[$module_key]['text']);
                // entPhysicalName contains the name of the slot in most cases.
                // But sometimes it contains a non-unique string, such as 'Linecard'.
                // If that is true, use the id instead, which can be assumed to be unique.
                $module_name_known = TRUE;
                $module_name = $snmp_data['entPhysicalName'][$id];
                if (count(array_keys($snmp_data['entPhysicalName'], $module_name)) > 1) {
                    $module_name_known = FALSE;
                    $module_name = "module {$id}";
                }
                // determine object type
                $dict_entry = getDictionaryEntry($attr['dict_key']);
                if (!array_key_exists($dict_entry['chapter_id'], $chapter_to_objtype_map)) {
                    showError('No dictionary entry, terminating');
                    break 2;
                }
                $objtype_id = $chapter_to_objtype_map[$dict_entry['chapter_id']];
                $child_object_id = commitAddObject("{$objectInfo['name']} - {$module_name}", NULL, $objtype_id, NULL);
                $child_objectInfo = spotEntity('object', $child_object_id);
                $child_objectInfo['attrs'] = getAttrValues($child_object_id);
                updateStickerForCell($child_objectInfo, 1, $snmp_data['entPhysicalSerialNum'][$id]);
                // OEM S/N 1
                updateStickerForCell($child_objectInfo, 2, $attr['dict_key']);
                // HW type
                updateStickerForCell($child_objectInfo, 5, $snmp_data['entPhysicalFirmwareRev'][$id]);
                // SW version
                if ($module_name_known) {
                    updateStickerForCell($child_objectInfo, 28, $module_name);
                }
                // Slot number
                commitLinkEntities('object', $object_id, 'object', $child_object_id);
                // add model-specific module details
                switch ($module_key) {
                    case 'J8726A':
                        checkPIC('1-681');
                        commitAddPort($child_object_id, 'con0', '1-681', 'console', '');
                        // DB-9 RS-232 console
                        break;
                    case 'NPE-G1':
                    case 'NPE-G2':
                        checkPIC('1-29');
                        commitAddPort($child_object_id, 'con0', '1-29', 'console', '');
                        // RJ-45 RS-232 console
                        commitAddPort($child_object_id, 'aux0', '1-29', 'auxillary', '');
                        // RJ-45 RS-232 aux port
                        checkPIC('1-19');
                        commitAddPort($child_object_id, 'mgmt', '1-19', '', '');
                        // 100Mb OOB mgmt
                        break;
                    case 'WS-SUP720-3B':
                    case 'WS-X6K-SUP2-2GE':
                    case 'WS-XSUP720-3BXL':
                        checkPIC('1-29');
                        commitAddPort($child_object_id, 'con0', '1-29', 'console', '');
                        // RJ-45 RS-232 console
                        break;
                    case 'WS-X4515':
                        checkPIC('1-29');
                        commitAddPort($child_object_id, 'con0', '1-29', 'console', '');
                        // RJ-45 RS-232 console
                        checkPIC('1-19');
                        commitAddPort($child_object_id, 'eobc', '1-19', 'mgmt', '');
                        // 100Mb OOB mgmt
                        break;
                }
                break;
            }
        }
        // if a new child object was just created, find children of that; otherwise, find children of the object passed as an argument
        $search_object_id = isset($child_object_id) ? $child_object_id : $object_id;
        $self($id, $search_object_id, $module_key);
    }
}
コード例 #9
0
function initRackTablesObject($rackDatas)
{
    // zabbix host data
    $params = array('output' => 'extend');
    $result = doPost('host.get', $params);
    $hosts = isset($result['result']) ? $result['result'] : array();
    $objectDatas = array();
    foreach ($hosts as $host) {
        $object_type_id = 4;
        $object_name = isset($host['host']) ? $host['host'] : "";
        $object_label = "";
        $object_asset_no = "";
        $taglist = array();
        $has_problems = $host['status'] == 0 ? 'no' : 'yes';
        $object_id = commitAddObject($object_name, $object_label, $object_type_id, $object_asset_no, $taglist);
        usePreparedUpdateBlade('Object', array('has_problems' => $has_problems), array('id' => $object_id));
        $objectDatas[$host['hostid']] = $object_id;
        // set hostgroup
        $params = array('output' => array('name'), 'hostids' => array($host['hostid']));
        $result = doPost('hostgroup.get', $params);
        $hostgroups = isset($result['result']) ? $result['result'] : array();
        $rack_ids = array();
        $_REQUEST = array();
        foreach ($hostgroups as $hostgroup) {
            if (isset($rackDatas[$hostgroup['name']])) {
                $rack = $rackDatas[$hostgroup['name']];
                amplifyCell($rack);
                array_push($rack_ids, $rack['id']);
                $height = $rack['height'];
                for ($i = 0; $i < 3; $i++) {
                    for ($j = $height; $j > 0; $j--) {
                        if ($rack[$j][$i]['state'] == 'F') {
                            # state == "T" : mounted
                            $_REQUEST['atom_' . $rack['id'] . "_{$j}" . "_{$i}"] = 'on';
                            break 2;
                        }
                    }
                }
            }
        }
        $_REQUEST['object_id'] = $object_id;
        $_REQUEST['rackmulti'] = $rack_ids;
        $object = spotEntity('object', $object_id);
        $changecnt = 0;
        // Get a list of rack ids which are parents of the object
        $parentRacks = reduceSubarraysToColumn(getParents($object, 'rack'), 'id');
        $workingRacksData = array();
        foreach ($_REQUEST['rackmulti'] as $cand_id) {
            if (!isset($workingRacksData[$cand_id])) {
                $rackData = spotEntity('rack', $cand_id);
                amplifyCell($rackData);
                $workingRacksData[$cand_id] = $rackData;
            } else {
                $rackData = $workingRacksData[$cand_id];
            }
            $is_ro = !rackModificationPermitted($rackData, 'updateObjectAllocation', FALSE);
            // It's zero-U mounted to this rack on the form, but not in the DB.  Mount it.
            if (isset($_REQUEST["zerou_{$cand_id}"]) && !in_array($cand_id, $parentRacks)) {
                if ($is_ro) {
                    continue;
                }
                $changecnt++;
                commitLinkEntities('rack', $cand_id, 'object', $object_id);
            }
            // It's not zero-U mounted to this rack on the form, but it is in the DB.  Unmount it.
            if (!isset($_REQUEST["zerou_{$cand_id}"]) && in_array($cand_id, $parentRacks)) {
                if ($is_ro) {
                    continue;
                }
                $changecnt++;
                commitUnlinkEntities('rack', $cand_id, 'object', $object_id);
            }
        }
        foreach ($workingRacksData as &$rd) {
            applyObjectMountMask($rd, $object_id);
        }
        $oldMolecule = getMoleculeForObject($object_id);
        foreach ($workingRacksData as $rack_id => $rackData) {
            $is_ro = !rackModificationPermitted($rackData, 'updateObjectAllocation', FALSE);
            if ($is_ro || !processGridForm($rackData, 'F', 'T', $object_id)) {
                continue;
            }
            $changecnt++;
            // Reload our working copy after form processing.
            $rackData = spotEntity('rack', $cand_id);
            amplifyCell($rackData);
            applyObjectMountMask($rackData, $object_id);
            $workingRacksData[$rack_id] = $rackData;
        }
        if ($changecnt) {
            // Log a record.
            $newMolecule = getMoleculeForObject($object_id);
            global $remote_username, $sic;
            usePreparedInsertBlade('MountOperation', array('object_id' => $object_id, 'old_molecule_id' => count($oldMolecule) ? createMolecule($oldMolecule) : NULL, 'new_molecule_id' => count($newMolecule) ? createMolecule($newMolecule) : NULL, 'user_name' => $remote_username, 'comment' => empty($sic['comment']) ? NULL : $sic['comment']));
        }
        // set IP
        $params = array('output' => 'extend', 'hostids' => $host['hostid']);
        $result = doPost('hostinterface.get', $params);
        $hostinterfaces = isset($result['result']) ? $result['result'] : array();
        foreach ($hostinterfaces as $interface) {
            if (isset($interface['ip']) && $interface['ip'] != '127.0.0.1') {
                $allocs = getObjectIPAllocations($object_id);
                $current_ips = array();
                foreach ($allocs as $alloc) {
                    $ip = $alloc["addrinfo"]["ip"];
                    $current_ips[$ip] = $ip;
                }
                $ip = $interface['ip'];
                if (!in_array($ip, array_values($current_ips))) {
                    // new IP
                    $ip_bin = ip_parse($ip);
                    if (null == getIPAddressNetworkId($ip_bin)) {
                        // if ip is not exists, adding it into RackTables IPv4Prefix.
                        $range = substr($ip, 0, strripos($ip, '.')) . '.0/24';
                        $vlan_ck = NULL;
                        $net_id = createIPv4Prefix($range, 'admim', isCheckSet('is_connected'), $taglist);
                        $net_cell = spotEntity('ipv4net', $net_id);
                        if (isset($vlan_ck)) {
                            if (considerConfiguredConstraint($net_cell, 'VLANIPV4NET_LISTSRC')) {
                                commitSupplementVLANIPv4($vlan_ck, $net_id);
                            }
                        }
                    }
                    bindIPToObject($ip_bin, $object_id, "", "");
                }
            }
        }
    }
    return $objectDatas;
}
コード例 #10
0
ファイル: api.php プロジェクト: xtha/salt
 //    UI handler: addMultipleObjects()
 case 'add_object':
     require_once 'inc/init.php';
     // only the Type ID is required at creation -- everything else can be set later
     assertUIntArg("object_type_id", TRUE);
     $object_type_id = $_REQUEST['object_type_id'];
     // virtual objects don't have labels or asset tags
     if (isset($_REQUEST['virtual_objects'])) {
         $_REQUEST["object_label"] = '';
         $_REQUEST["object_asset_no"] = '';
     }
     $object_name = isset($_REQUEST['object_name']) ? $_REQUEST['object_name'] : '';
     $object_label = isset($_REQUEST['object_label']) ? $_REQUEST['object_label'] : '';
     $object_asset_no = isset($_REQUEST['object_asset_no']) ? $_REQUEST['object_asset_no'] : '';
     $taglist = isset($_REQUEST['taglist']) ? $_REQUEST['taglist'] : array();
     $object_id = commitAddObject($object_name, $object_label, $object_type_id, $object_asset_no, $taglist);
     // redirect to the get_object URL for the new object
     redirectUser($_SERVER['SCRIPT_NAME'] . "?method=get_object&object_id={$object_id}");
     break;
     // edit an existing object
     //    UI equivalent: submitting form at /index.php?page=object&tab=edit&object_id=911
     //    UI handler: updateObject()
 // edit an existing object
 //    UI equivalent: submitting form at /index.php?page=object&tab=edit&object_id=911
 //    UI handler: updateObject()
 case 'edit_object':
     require_once 'inc/init.php';
     // check required args
     genericAssertion('object_id', 'uint0');
     genericAssertion('object_name', 'string0');
     genericAssertion('object_label', 'string0');
コード例 #11
0
function RunImport()
{
    $taglist = isset($_REQUEST['taglist']) ? $_REQUEST['taglist'] : array();
    $objectnames = $_POST['objectname'];
    global $dbxlink;
    $log = emptyLog();
    foreach ($objectnames as $objectname) {
        // FIXME: This reads the entire directory for each object. Not very efficient.
        if ($handle = opendir('./yamls/')) {
            while (false !== ($file = readdir($handle))) {
                # puppet names the files $FQDN.yaml, not PSMN
                if ($file == $objectname . ".yaml") {
                    # SPYC is not happy with the puppet header. Hence read it as string, strip the header and feed it to SPYC
                    $file_contents = file_get_contents("./yamls/{$file}");
                    $file_contents = substr($file_contents, strpos($file_contents, "\n") + 1);
                    $yaml_file_array = Spyc::YAMLLoadString($file_contents);
                    // FIXME: Is this the correct way to narrow in on an array?
                    // At this point, $yaml_file_array contains all the data from the YAML files in a indexed array.
                    $yaml_name = $yaml_file_array['name'];
                    // switch to the 2nd part of the array
                    $yaml_file_array = $yaml_file_array['parameters'];
                    // getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0|1|2)
                    $object = getSearchResultByField('RackObject', array('id'), 'name', $yaml_name, '', 2);
                    if ($object) {
                        # Object exists. Do NOT modify.
                        $id = $object[0]['id'];
                        $log = mergeLogs($log, oneLiner(202, array("{$objectname} exists. No modifications!")));
                    } else {
                        // Object does not exist. Create new.
                        // Syntax: commitAddObject ($new_name, $new_label, $new_type_id, $new_asset_no, $taglist = array())
                        // Type is 4, server, by default.
                        $new_yamlobject = commitAddObject($yaml_name, '', 4, $yaml_file_array['serialnumber'], $taglist);
                        // Hardware type (i.e. ProLiant DL380 G6a), Dict Chapter ID is '11';
                        $hw_dict_key = getdict($hw = $yaml_file_array['productname'], $chapter = 11);
                        commitUpdateAttrValue($object_id = $new_yamlobject, $attr_id = '2', $value = $hw_dict_key);
                        // Operating system string, Dict Chapter ID is '13'.
                        $osrelease = $yaml_file_array['operatingsystem'] . " " . $yaml_file_array['operatingsystemrelease'];
                        $os_dict_key = getdict($hw = $osrelease, $chapter = 13);
                        commitUpdateAttrValue($object_id = $new_yamlobject, $attr_id = '4', $value = $os_dict_key);
                        /*
                                    // FIXME: The IDs should be looked up, and not preset.
                                    // Architecture. Attribute ID is '10000'.
                                    commitUpdateAttrValue ($object_id = $new_yamlobject, $attr_id = '10000', $value = $yaml_file_array['hardwareisa']);
                                    // Memory. Attribute ID is 17.
                                    commitUpdateAttrValue ($object_id = $new_yamlobject, $attr_id = '17', $value = (int)$yaml_file_array['memorysize']);
                                    // CPU. Attribute ID is 100001
                                    $cpu = $yaml_file_array['processorcount'] . " x " . $yaml_file_array['processor0'];
                                    commitUpdateAttrValue ($object_id = $new_yamlobject, $attr_id = '10001', $value = $cpu);
                        */
                        // OEM S/N 1. Attribute ID is '1'.
                        commitUpdateAttrValue($object_id = $new_yamlobject, $attr_id = '1', $value = $yaml_file_array['serialnumber']);
                        // FQDN. Attribute ID is '3'.
                        commitUpdateAttrValue($object_id = $new_yamlobject, $attr_id = '3', $value = $yaml_file_array['fqdn']);
                        // UUID. Attribute ID is '25'.
                        commitUpdateAttrValue($object_id = $new_yamlobject, $attr_id = '25', $value = $yaml_file_array['uuid']);
                        // Hypervisor. Attribute ID is '26', Dict Chapter ID is '29'.
                        // Hypervisor key does not exist in standard Puppet yaml file, added by PSMN
                        if (isset($yaml_file_array['hypervisor'])) {
                            $hv_dict_key = getdict($hw = $yaml_file_array['hypervisor'], $chapter = 29);
                            commitUpdateAttrValue($object_id = $new_yamlobject, $attr_id = '26', $value = $hv_dict_key);
                        }
                        // NICS
                        // Warning! This part only work if default Configuration is modified
                        // Go to "MainPage -> Configuration -> User Interface"
                        // Modify "AutoPorts configuration": Change "4 = 1*33*kvm + 2*24*eth%u;15 = 1*446*kvm" to "15 = 1*446*kvm"
                        // Ref: http://www.freelists.org/post/racktables-users/Automatic-insertions-of-servers-in-the-db,7
                        $nics = explode(',', $yaml_file_array['interfaces'], 9);
                        $count = count($nics);
                        for ($i = 0; $i < $count; $i++) {
                            switch ($nics[$i]) {
                                case "sit0":
                                    break 1;
                                case "ib0":
                                    // infiniband
                                    if (isset($yaml_file_array['ipaddress_' . $nics[$i]])) {
                                        $ip = $yaml_file_array['ipaddress_' . $nics[$i]];
                                    }
                                    // do NOT import infiniband MAC for now
                                    //                if (isset($yaml_file_array['macaddress_' . $nics[$i]]))
                                    //                {
                                    //                  $mac = $yaml_file_array['macaddress_' . $nics[$i]];
                                    //                }
                                    // Add port to object. Type 40 is 10GBase-CX4, MAC can be NULL
                                    commitAddPort($object_id = $new_yamlobject, $nics[$i], 40, 'infiniband', $mac);
                                    // Add IP to object.
                                    if (isset($ip)) {
                                        bindIpToObject($ip, $new_yamlobject, $nics[$i], 'regular');
                                    }
                                    break 1;
                                default:
                                    if (preg_match("eth", $nics[$i]) === 0) {
                                        break 1;
                                    }
                                    # this one might be bad for non-linux OSes ?
                                    if (isset($yaml_file_array['ipaddress_' . $nics[$i]])) {
                                        $ip = $yaml_file_array['ipaddress_' . $nics[$i]];
                                    }
                                    if (isset($yaml_file_array['macaddress_' . $nics[$i]])) {
                                        $mac = $yaml_file_array['macaddress_' . $nics[$i]];
                                    }
                                    // Add port to object. Type 24 is 1000Base-T
                                    commitAddPort($object_id = $new_yamlobject, $nics[$i], 24, 'Ethernet port', "{$mac}");
                                    // Add IP to object.
                                    if (isset($ip)) {
                                        bindIpToObject($ip, $new_yamlobject, $nics[$i], 'regular');
                                    }
                                    break 1;
                            }
                            unset($ip);
                            unset($mac);
                        }
                        // Create a URL for the log message.
                        $url = makeHref(array('page' => 'object', 'tab' => 'default', 'object_id' => $new_yamlobject));
                        $loginstance = "<a href=\"{$url}\">" . $objectname . "</a>";
                        $log = mergeLogs($log, oneLiner(80, array("{$loginstance}")));
                    }
                }
            }
        }
    }
    return showSuccess($log);
}
コード例 #12
0
function copyLotOfObjects()
{
    global $dbxlink;
    $dbrollback = 0;
    if (!$dbxlink->beginTransaction()) {
        throw new RTDatabaseError("can not start transaction");
    }
    // do we need this ?
    $log = emptyLog();
    $taglist = isset($_REQUEST['taglist']) ? $_REQUEST['taglist'] : array();
    assertUIntArg('global_type_id', TRUE);
    assertStringArg('namelist', TRUE);
    $global_type_id = $_REQUEST['global_type_id'];
    $source_object_id = $_REQUEST['object_id'];
    $source_object = spotEntity('object', $source_object_id);
    amplifyCell($source_object);
    // only call amplifyCell_object_Backend_Port if we have function linkmgmt_linkPorts from linkmgmt.php
    if (function_exists('amplifyCell_object_Backend_Port') && function_exists('linkmgmt_linkPorts')) {
        amplifyCell_object_Backend_Port($source_object);
    }
    if ($global_type_id == 0 or !strlen($_REQUEST['namelist'])) {
        // Log something reasonable with showError Here
        // We do not have names to copy our object to !
        // Pls check what makes $global_type_id == 0  an error
        $log = mergeLogs($log, oneLiner(186));
        return;
    }
    // The name extractor below was stolen from ophandlers.php:addMultiPorts()
    $names1 = explode("\n", $_REQUEST['namelist']);
    $names2 = array();
    foreach ($names1 as $line) {
        $parts = explode('\\r', $line);
        reset($parts);
        if (!strlen($parts[0])) {
            continue;
        } else {
            $names2[] = rtrim($parts[0]);
        }
    }
    foreach ($names2 as $name_or_csv) {
        $label = '';
        $asset_no = '';
        $object_name = '';
        $regexp = '/^\\"([^\\"]*)\\","([^\\"]*)\\","([^\\"]*)\\"/';
        $object_name_or_csv = htmlspecialchars_decode($name_or_csv, ENT_QUOTES);
        // error_log( "$regexp $object_name" );
        if (preg_match($regexp, $object_name_or_csv, $matches)) {
            $object_name = $matches[1];
            $label = $matches[2];
            $asset_no = $matches[3];
        } else {
            $object_name = $name_or_csv;
        }
        try {
            $object_id = commitAddObject($object_name, $label, $global_type_id, $asset_no, $taglist);
            if (!$object_id) {
                throw new RTDatabaseError("could not create {$object_name}");
            }
            $info = spotEntity('object', $object_id);
            amplifyCell($info);
            foreach ($source_object['ports'] as $source_port) {
                $update_port = 0;
                foreach ($info['ports'] as $new_port) {
                    if ($new_port['name'] == $source_port['name']) {
                        commitUpdatePort($object_id, $new_port['id'], $new_port['name'], $new_port['oif_id'], $source_port['label'], "");
                        $update_port = 1;
                    }
                }
                if ($update_port) {
                    true;
                } else {
                    commitAddPort($object_id, $source_port['name'], sprintf("%s-%s", $source_port['iif_id'], $source_port['oif_id']), $source_port['label'], "");
                }
            }
            // Copy Backendlinks only start if we ghave function linkmgmt_linkPorts from linkmgmt.php
            if (function_exists('amplifyCell_object_Backend_Port') && function_exists('linkmgmt_linkPorts')) {
                $info = spotEntity('object', $object_id);
                amplifyCell($info);
                amplifyCell_object_Backend_Port($info);
                /*	 showError( '<div align="left"><pre>\n===== Source Object ======\n\n' .
                				 		 varDumpToString ( $source_object ) .
                						'\n\n===== New Object ======\n\n' .
                						 varDumpToString ( $info )  .  '</pre></div>' );
                			*/
                $name_by_id = array();
                foreach ($info['BackendPorts'] as $new_be_port) {
                    $name_by_id[$new_be_port['name']] = $new_be_port['id'];
                }
                $linked_ports = array();
                foreach ($source_object['BackendPorts'] as $source_be_port) {
                    if ($source_be_port['object_id'] == $source_be_port['remote_object_id']) {
                        // We have a Port that has the own object as remote object we want to copy this type of Linko
                        // We have backend Links
                        $new_be_port_a = $name_by_id[$source_be_port['name']];
                        $new_be_port_b = $name_by_id[$source_be_port['remote_name']];
                        if ($new_be_port_a && $new_be_port_b && !array_key_exists($new_be_port_a, $linked_ports) && !array_key_exists($new_be_port_b, $linked_ports)) {
                            // error_log ( sprintf ('new_be_port_a %s // new_be_port_b %s // cableid %s', $new_be_port_a  , $new_be_port_b, $source_be_port['cableid'] ));
                            $ret_val = linkmgmt_linkPorts($new_be_port_a, $new_be_port_b, 'back', $source_be_port['cableid']);
                            // error_log ( sprintf (' linkmgmt_linkPorts ret val: "%s" ', $ret_val)) ;
                            if ($ret_val) {
                                throw new RTDatabaseError("could not copy Backend Links for {$object_name} because: {$ret_val}");
                            } else {
                                $linked_ports[$new_be_port_a] = True;
                                $linked_ports[$new_be_port_b] = True;
                            }
                        }
                    }
                }
            }
            // Copy attributes
            foreach (getAttrValues($source_object_id) as $record) {
                $value = $record['value'];
                switch ($record['type']) {
                    case 'uint':
                    case 'float':
                    case 'string':
                        $value = $record['value'];
                        break;
                    case 'dict':
                        $value = $record['key'];
                        break;
                    default:
                }
                if (permitted(NULL, NULL, NULL, array(array('tag' => '$attr_' . $record['id'])))) {
                    if (empty($value)) {
                        commitUpdateAttrValue($object_id, $record['id']);
                    } else {
                        commitUpdateAttrValue($object_id, $record['id'], $value);
                    }
                } else {
                    showError('Permission denied, "' . $record['name'] . '" can not be set');
                }
            }
            //$log = mergeLogs ($log, oneLiner (5, array ('<a href="' .
            //	makeHref (array ('page' => 'object', 'tab' => 'default', 'object_id' => $object_id)) .
            //	'">' . $info['dname'] . '</a>'))
            //);
            showSuccess(sprintf("Copied Object %s ; new Object: %s", $source_object['name'], formatPortLink($object_id, $info['dname'], 1, '', '')));
        } catch (RTDatabaseError $e) {
            error_log("rolling back DB");
            $dbrollback = 1;
            $dbxlink->rollBack();
            $log = mergeLogs($log, oneLiner(147, array($object_name)));
            throw new RTDatabaseError($e->getMessage() . sprintf(' (%s)', $name_or_csv));
        }
    }
    if (!$dbrollback) {
        $dbxlink->commit();
    }
    // return buildWideRedirectURL ($log);
}
コード例 #13
0
function Update()
{
    // Read uploaded file
    $lines = file($_FILES['userfile']['tmp_name']);
    // add file contents to facter array
    foreach ($lines as $line_num => $line) {
        $tmpfacter = explode("=>", $line, 2);
        $facter[trim($tmpfacter[0])] = str_replace('"', '', trim($tmpfacter[1]));
    }
    // Fix fqdn since all fields have \n inn them
    $facter['fqdn'] = str_replace("\n", "", $facter['fqdn']);
    // Check if it's an existing machine
    // 2011-08-31 <*****@*****.**>
    // * expanded query to try to match via facter Serialnumber to be able to
    //   match unnamed HW assets. Serial is more precise and less likely to be changed.
    if (array_key_exists('serialnumber', $facter) && strlen($facter['serialnumber']) > 0 && $facter['serialnumber'] != 'Not Specified') {
        $query = "select id from RackObject where name = \"{$facter['fqdn']}\" OR asset_no = \"{$facter['serialnumber']}\" LIMIT 1";
    } else {
        $query = "select id from RackObject where name = \"{$facter['fqdn']}\" LIMIT 1";
    }
    unset($result);
    $result = usePreparedSelectBlade($query);
    $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
    if ($resultarray) {
        $id = $resultarray[0]['id'];
    }
    // If it's a new machine
    if (!isset($id)) {
        // Check to see if it's a physical machine and get the correct id for Server
        if ($facter['is_virtual'] == "false") {
            // Find server id
            $query = "select dict_key from Dictionary where dict_value='Server' LIMIT 1";
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll();
            if ($resultarray) {
                $virtual = $resultarray[0]['dict_key'];
            }
        } else {
            // Find virtual id
            $query = "select dict_key from Dictionary where dict_value='VM' LIMIT 1";
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
            if ($resultarray) {
                $virtual = $resultarray[0]['dict_key'];
            }
        }
        // Add the new machine
        $newmachine = commitAddObject($facter['fqdn'], "", $virtual, $value = "");
        $type_id = getObjectTypeID($newmachine);
    } else {
        // Just set some fields I use later down for updating
        $newmachine = $id;
        $machineupdate = 1;
        $type_id = getObjectTypeID($newmachine);
    }
    // 2011-08-31 <*****@*****.**>
    // * Update (unique) name of object.
    if (array_key_exists('serialnumber', $facter) && strlen($facter['serialnumber']) > 0 && $facter['serialnumber'] != 'Not Specified') {
        unset($result);
        $query = "select * from RackObject where asset_no = \"{$facter['serialnumber']}\" LIMIT 1";
        $result = usePreparedSelectBlade($query);
        $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
        if ($resultarray) {
            $id = $resultarray[0]['id'];
            $label = $resultarray[0]['label'];
            // Update FQDN
            commitUpdateObject($id, $facter['fqdn'], $label, 'no', $facter['serialnumber'], 'Facter Import::Update Common Name');
        }
    }
    // Find HW type id
    // 2011-08-31 <*****@*****.**>
    // * adjust format to match default Dictionary Sets
    if ($facter['is_virtual'] == "false") {
        $iHWTemp = preg_match('([a-zA-Z]{1,})', $facter['manufacturer'], $matches);
        $sManufacturer = $matches[0];
        $sHW = preg_replace('(\\ )', '\\1%GPASS%', $facter['productname']);
        $sHWType = $sManufacturer . ' ' . $sHW;
        $query = "select id from Attribute where name='HW type' LIMIT 1";
        unset($result);
        $result = usePreparedSelectBlade($query);
        $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
        if ($resultarray) {
            $id = $resultarray[0]['id'];
            // Update HW type
            $hw_dict_key = getdict($sHWType, $chapter = 11);
            commitUpdateAttrValue($object_id = $newmachine, $attr_id = $id, $value = $hw_dict_key);
        }
        //Also Check if HYPERVISOR
        if (isset($facter['is_hypervisor'])) {
            $query = "select id from Attribute where name REGEXP '^ *Hypervisor Type\$' LIMIT 1";
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
            if ($resultarray) {
                $id = $resultarray[0]['id'];
                // Update Hypervisor type
                $hypervisor_type = $facter['is_hypervisor'];
                $hypervisor_type_dict_key = getdict($hw = $hypervisor_type, $chapter = 10005);
                commitUpdateAttrValue($object_id = $newmachine, $attr_id = $id, $value = $hypervisor_type_dict_key);
            }
            //Set Value to Yes
            $query = "select id from Attribute where name REGEXP '^ *Hypervisor' LIMIT 1";
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
            if ($resultarray) {
                $id = $resultarray[0]['id'];
                // Update Hypervisor type
                $hypervisor = "Yes";
                $hypervisor_dict_key = getdict($hypervisor, $chapter = 29);
                commitUpdateAttrValue($object_id = $newmachine, $attr_id = $id, $value = $hypervisor_dict_key);
            }
            //Find Running VMs
            $vms = explode(',', $facter['vms']);
            $vm_count = count($vms);
            for ($i = 0; $i < $vm_count; $i++) {
                //addToParent
                addVmToParent($vms[$i], $newmachine);
            }
        } else {
            $query = "select id from Attribute where name REGEXP '^ *Hypervisor' LIMIT 1";
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
            if ($resultarray) {
                $id = $resultarray[0]['id'];
                // Update Hypervisor type
                $hypervisor = "No";
                $hypervisor_dict_key = getdict($hypervisor, $chapter = 29);
                commitUpdateAttrValue($object_id = $newmachine, $attr_id = $id, $value = "");
            }
        }
    }
    // Find SW type id (OS)
    $query = "select id from Attribute where name REGEXP '^ *SW type\$' LIMIT 1";
    unset($result);
    $result = usePreparedSelectBlade($query);
    $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
    if ($resultarray) {
        $id = $resultarray[0]['id'];
        // Update SW type (OS)
        $osrelease = $facter['operatingsystem'] . '%GSKIP%' . $facter['operatingsystem'] . ' V' . $facter['operatingsystemrelease'];
        $os_dict_key = getdict($hw = $osrelease, $chapter = 13);
        commitUpdateAttrValue($object_id = $newmachine, $attr_id = $id, $value = $os_dict_key);
    }
    //Generic to read in from file
    $manifest_file = fopen("../plugins/manifest", "r") or die("Could not open manifest, make sure it is in the websrv root and called manifest \n");
    while (!feof($manifest_file)) {
        $tmp_line = fgets($manifest_file);
        if (!empty($tmp_line) && !preg_match("/\\/\\//", $tmp_line)) {
            @(list($Fact, $Attr, $Chapter) = array_map('trim', explode(',', $tmp_line, 3)));
            //check for multi-facter names
            if (strstr($Fact, '.')) {
                @(list($Fact1, $Fact2) = array_map('trim', explode('.', $Fact)));
                $value = $facter[$Fact1] . ' ' . $facter[$Fact2];
                if (!isset($facter[$Fact1]) || !isset($facter[$Fact2])) {
                    echo "WARNING: {$Fact1} or {$Fact2} does not exist in Facter for this object \n";
                    continue;
                }
            } else {
                if (!isset($facter[$Fact])) {
                    echo "WARNING: {$Fact} does not exist in Facter for this object \n";
                    continue;
                } else {
                    $value = $facter[$Fact];
                }
            }
            $query = "select id from Attribute where name REGEXP '^ *{$Attr}' LIMIT 1";
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
            $id = $resultarray[0]['id'];
            if (!valid($type_id, $id)) {
                echo "WARNING: Not a valid Mapping for {$Fact} to {$Attr} for objectType {$type_id} \n";
            } else {
                if ($resultarray) {
                    if (!empty($Chapter)) {
                        $name = $value;
                        $name_dict_key = getdict($hw = $name, $chapter = $Chapter);
                        commitUpdateAttrValue($object_id = $newmachine, $attr_id = $id, $value = $name_dict_key);
                    } else {
                        if (preg_match("/[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}/", $value) || preg_match("/[0-9]{1,2}\\-[0-9]{1,2}\\-[0-9]{4}/", $value) || preg_match("/[0-9]{4}\\-[0-9]{1,2}\\-[0-9]{1,2}/", $value)) {
                            //handle dates
                            commitUpdateAttrValue($newmachine, $id, strtotime($value));
                        } else {
                            commitUpdateAttrValue($newmachine, $id, $value);
                        }
                    }
                }
            }
        }
    }
    fclose($manifest_file);
    // Add network interfaces
    // Create an array with interfaces
    $nics = explode(',', $facter['interfaces']);
    // Go through all interfaces and add IP and MAC
    $count = count($nics);
    for ($i = 0; $i < $count; $i++) {
        // Remove newline from the field
        $nics[$i] = str_replace("\n", "", $nics[$i]);
        // We generally don't monitor sit interfaces.
        // We don't do this for lo interfaces, too
        // 2011-08-31 <*****@*****.**>
        // * Only Document real interfaces, dont do bridges, bonds, vlan-interfaces
        //   when they have no IP defined.
        if (preg_match('(_|^(bond|lo|sit|vnet|virbr|veth|peth))', $nics[$i]) != 0) {
            // do nothing
        } else {
            // Get IP
            if (isset($facter['ipaddress_' . $nics[$i]])) {
                $ip = $facter['ipaddress_' . $nics[$i]];
            }
            // Get MAC
            if (isset($facter['macaddress_' . $nics[$i]])) {
                $mac = $facter['macaddress_' . $nics[$i]];
            }
            //check if VM or not
            if ($facter['is_virtual'] == "false") {
                // Find 1000Base-T id
                $query = "select id from PortOuterInterface where oif_name REGEXP '^ *1000Base-T\$' LIMIT 1";
            } else {
                // Find virtual port id
                $query = "select id from PortOuterInterface where oif_name REGEXP '^ *virtual port\$' LIMIT 1";
            }
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
            if ($resultarray) {
                $nictypeid = $resultarray[0]['id'];
            }
            // Remove newline from ip
            $ip = str_replace("\n", "", $ip);
            // Check to se if the interface has an ip assigned
            $query = "SELECT object_id FROM IPv4Allocation where object_id={$newmachine} and name=\"{$nics[$i]}\"";
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
            if ($resultarray) {
                unset($id);
                $ipcheck = $resultarray;
            }
            // Check if it's been configured a port already
            $query = "SELECT id,iif_id FROM Port where object_id={$newmachine} and name=\"{$nics[$i]}\"";
            unset($result);
            $result = usePreparedSelectBlade($query);
            $resultarray = $result->fetchAll(PDO::FETCH_ASSOC);
            if ($resultarray) {
                $portid = $resultarray[0]['id'];
                unset($id);
                $portcheck = $resultarray;
            }
            // Add/update port
            // 2011-08-31 <*****@*****.**>
            // * Don't touch already existing complex ports
            if ($resultarray[0]['type'] != 9) {
                if (count($portcheck) == 1) {
                    commitUpdatePort($newmachine, $portid, $nics[$i], $nictypeid, "Ethernet port", "{$mac}", NULL);
                } else {
                    commitAddPort($object_id = $newmachine, $nics[$i], $nictypeid, 'Ethernet port', "{$mac}");
                }
            } else {
                //We've got a complex port, don't touch it, it raises an error with 'Database error: foreign key violation'
            }
            if (count($ipcheck) == 1) {
                if ($ip) {
                    updateAddress(ip_parse($ip), $newmachine, $nics[$i], 'regular');
                }
            } else {
                if ($ip) {
                    bindIpToObject(ip_parse($ip), $newmachine, $nics[$i], 'regular');
                }
            }
            unset($portcheck);
            unset($ipcheck);
            unset($ip);
            unset($mac);
        }
    }
    //uncomment to start using auto tags
    //addTagToObject($facter, $newmachine);
    return buildRedirectURL();
}