Example #1
0
/** Create a Virtual Machine in the specified pool
	@param name 	The name of the new Virtual Machine
	@param ip		The IP address to assign the VM
	@param asset	Asset tag to use (VM UUID)
	@param osInfo	Operating System information (to be stored as a comment)
	@param taglist	Array of tags to use for this new object
	@param poolID	Virtual Machine pool to parent this object to
*/
function createVMInPool($name, $ip, $asset, $osInfo, $taglist, $poolID, $vmTypeID)
{
    // make sure there's no duplicates
    if (getSearchResultByField('RackObject', array('id'), 'name', $name, '', 2)) {
        return FALSE;
    }
    // commitAddObject ($new_name, $new_label, $new_type_id, $new_asset_no, $taglist = array())
    $newObject = commitAddObject($name, $name, $vmTypeID, $asset, $taglist);
    // add IP address to new object
    if (!empty($ip)) {
        bindIpToObject(ip_parse($ip), $newObject, 'eth0', 'regular');
    }
    // add OS info to new object
    if (!empty($osInfo)) {
        usePreparedUpdateBlade('Object', array('comment' => $osInfo), array('id' => $newObject));
    }
    // set container
    //commitLinkEntities($parent_entity_type, $parent_entity_id, $child_entity_type, $child_entity_id);
    commitLinkEntities("object", $poolID, "object", $newObject);
}
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);
}
Example #3
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 <neil.scholten@gamigo.com>
    // * 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 <neil.scholten@gamigo.com>
    // * 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 <neil.scholten@gamigo.com>
    // * 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 <neil.scholten@gamigo.com>
        // * 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 <neil.scholten@gamigo.com>
            // * 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();
}