Exemplo n.º 1
0
function addGroup($data)
{
    if ($data['type'] == "user") {
        if ($data['editgroupid'] == 0 || $data['editgroupid'] == '') {
            $data['editgroupid'] = 'NULL';
        }
        if (!array_key_exists('custom', $data)) {
            $data['custom'] = 1;
        } elseif ($data['custom'] == 0) {
            $ownerid = 'NULL';
            $data['editgroupid'] = 'NULL';
        }
        if ($data['custom']) {
            $ownerid = getUserlistID($data['owner']);
        }
        $query = "INSERT INTO usergroup " . "(name, " . "affiliationid, " . "ownerid, " . "editusergroupid, " . "custom, " . "initialmaxtime, " . "totalmaxtime, ";
        if (checkUserHasPerm('Set Overlapping Reservation Count')) {
            $query .= "overlapResCount, ";
        }
        $query .= "maxextendtime) " . "VALUES ('{$data['name']}', " . "{$data['affiliationid']}, " . "{$ownerid}, " . "{$data['editgroupid']}, " . "{$data['custom']}, " . "{$data['initialmax']}, " . "{$data['totalmax']}, ";
        if (checkUserHasPerm('Set Overlapping Reservation Count')) {
            $query .= "{$data['overlap']}, ";
        }
        $query .= "{$data['maxextend']})";
    } else {
        $query = "INSERT INTO resourcegroup " . "(name, " . "ownerusergroupid, " . "resourcetypeid) " . "VALUES ('{$data['name']}', " . "{$data['ownergroup']}, " . "'{$data['resourcetypeid']}')";
    }
    $qh = doQuery($query, 305);
    clearPrivCache();
    return mysql_affected_rows($GLOBALS['mysql_link_vcl']);
}
Exemplo n.º 2
0
 function AJsaveResource()
 {
     $add = getContinuationVar('add', 0);
     if ($add) {
         $this->createImage();
         return;
     }
     $data = $this->validateResourceData();
     if ($data['error']) {
         $ret = array('status' => 'error', 'msg' => $data['errormsg']);
         sendJSON($ret);
         return;
     }
     $olddata = getContinuationVar('olddata');
     $imagenotes = getImageNotes($data['imageid']);
     $ownerid = getUserlistID($data['owner']);
     if (empty($data['concurrent']) || !is_numeric($data['concurrent'])) {
         $data['concurrent'] = 'NULL';
     }
     $updates = array();
     # name
     if ($data['name'] != $olddata['prettyname']) {
         $updates[] = "prettyname = '{$data['name']}'";
     }
     # ownerid
     if ($ownerid != $olddata['ownerid']) {
         $updates[] = "ownerid = {$ownerid}";
         # update newimages groups
         $this->changeOwnerPermissions($olddata['ownerid'], $ownerid, $data['imageid']);
     }
     # minram
     if ($data['ram'] != $olddata['minram']) {
         $updates[] = "minram = {$data['ram']}";
     }
     # minprocnumber
     if ($data['cores'] != $olddata['minprocnumber']) {
         $updates[] = "minprocnumber = {$data['cores']}";
     }
     # minprocspeed
     if ($data['cpuspeed'] != $olddata['minprocspeed']) {
         $updates[] = "minprocspeed = {$data['cpuspeed']}";
     }
     # minnetwork
     if ($data['networkspeed'] != $olddata['minnetwork']) {
         $updates[] = "minnetwork = {$data['networkspeed']}";
     }
     # maxconcurrent
     if ($data['concurrent'] != $olddata['maxconcurrent']) {
         $updates[] = "maxconcurrent = {$data['concurrent']}";
     }
     # reloadtime
     if ($data['reload'] != $olddata['reloadtime']) {
         $updates[] = "reloadtime = {$data['reload']}";
     }
     # forcheckout
     if ($data['checkout'] != $olddata['forcheckout']) {
         $updates[] = "forcheckout = {$data['checkout']}";
     }
     # description
     if ($data['desc'] != $olddata['description']) {
         $escdesc = mysql_real_escape_string($data['desc']);
         $updates[] = "description = '{$escdesc}'";
     }
     # usage
     if ($data['usage'] != $olddata['usage']) {
         $escusage = mysql_real_escape_string($data['usage']);
         $updates[] = "`usage` = '{$escusage}'";
     }
     if (count($updates)) {
         $query = "UPDATE image SET " . implode(', ', $updates) . " WHERE id = {$data['imageid']}";
         doQuery($query);
     }
     if (empty($olddata['imagemetaid']) && ($data['checkuser'] == 0 || $data['rootaccess'] == 0 || $olddata['ostype'] == 'windows' && $data['sethostname'] == 1 || $olddata['ostype'] == 'linux' && $data['sethostname'] == 0)) {
         if ($olddata['ostype'] != 'windows' && $olddata['ostype'] != 'linux' || $olddata['ostype'] == 'windows' && $data['sethostname'] == 0 || $olddata['ostype'] == 'linux' && $data['sethostname'] == 1) {
             $data['sethostname'] = 'NULL';
         }
         $query = "INSERT INTO imagemeta " . "(checkuser, " . "rootaccess, " . "sethostname) " . "VALUES ({$data['checkuser']}, " . "{$data['rootaccess']}, " . "{$data['sethostname']})";
         doQuery($query, 101);
         $qh = doQuery("SELECT LAST_INSERT_ID() FROM imagemeta", 101);
         if (!($row = mysql_fetch_row($qh))) {
             abort(101);
         }
         $imagemetaid = $row[0];
         $query = "UPDATE image " . "SET imagemetaid = {$imagemetaid} " . "WHERE id = {$data['imageid']}";
         doQuery($query, 101);
     } elseif (!empty($olddata['imagemetaid'])) {
         if ($data['checkuser'] != $olddata['checkuser'] || $data['rootaccess'] != $olddata['rootaccess'] || ($olddata['ostype'] == 'windows' || $olddata['ostype'] == 'linux') && $data['sethostname'] != $olddata['sethostname']) {
             if ($olddata['ostype'] != 'windows' && $olddata['ostype'] != 'linux' || $olddata['ostype'] == 'windows' && $data['sethostname'] == 0 || $olddata['ostype'] == 'linux' && $data['sethostname'] == 1) {
                 $data['sethostname'] = 'NULL';
             }
             $query = "UPDATE imagemeta " . "SET checkuser = {$data['checkuser']}, " . "rootaccess = {$data['rootaccess']}, " . "sethostname = {$data['sethostname']} " . "WHERE id = {$olddata['imagemetaid']}";
             doQuery($query, 101);
         }
         checkClearImageMeta($olddata['imagemetaid'], $data['imageid']);
     }
     $args = $this->defaultGetDataArgs;
     $args['rscid'] = $data['imageid'];
     $tmp = $this->getData($args);
     $image = $tmp[$data['imageid']];
     $image['description'] = $data['desc'];
     $image['usage'] = $data['usage'];
     if (isset($imagemetaid)) {
         $image['imagemetaid'] = $imagemetaid;
     }
     sendJSON(array('status' => 'success', 'data' => $image));
 }
Exemplo n.º 3
0
function getStatGraphConBladeUserData($start, $end, $affilid)
{
    $startdt = $start . " 00:00:00";
    $enddt = $end . " 23:59:59";
    $startunix = datetimeToUnix($startdt);
    $endunix = datetimeToUnix($enddt) + 1;
    $days = ($endunix - $startunix) / SECINDAY;
    $data = array();
    $data["points"] = array();
    $data["labels"] = array();
    $reloadid = getUserlistID('vclreload@Local');
    for ($daystart = $startunix; $daystart < $endunix; $daystart += SECINDAY) {
        array_push($data["labels"], date('Y-m-d', $daystart));
        $count = array();
        for ($j = 0; $j < 24; $j++) {
            $count[$j] = 0;
        }
        $startdt = unixToDatetime($daystart);
        $enddt = unixToDatetime($daystart + SECINDAY);
        if ($affilid != 0) {
            $query = "SELECT l.start AS start, " . "l.finalend AS end " . "FROM log l, " . "sublog s, " . "computer c, " . "user u " . "WHERE l.userid = u.id AND " . "l.start < '{$enddt}' AND " . "l.finalend > '{$startdt}' AND " . "s.logid = l.id AND " . "s.computerid = c.id AND " . "l.wasavailable = 1 AND " . "c.type = 'blade' AND " . "l.userid != {$reloadid} AND " . "u.affiliationid = {$affilid}";
        } else {
            $query = "SELECT l.start AS start, " . "l.finalend AS end " . "FROM log l, " . "sublog s, " . "computer c " . "WHERE l.start < '{$enddt}' AND " . "l.finalend > '{$startdt}' AND " . "s.logid = l.id AND " . "s.computerid = c.id AND " . "l.wasavailable = 1 AND " . "c.type = 'blade' AND " . "l.userid != {$reloadid}";
        }
        $qh = doQuery($query, 101);
        while ($row = mysql_fetch_assoc($qh)) {
            $unixstart = datetimeToUnix($row["start"]);
            $unixend = datetimeToUnix($row["end"]);
            for ($binstart = $daystart, $binend = $daystart + 3600, $binindex = 0; $binstart <= $unixend && $binend <= $daystart + SECINDAY; $binstart += 3600, $binend += 3600, $binindex++) {
                if ($binend <= $unixstart) {
                    continue;
                } elseif ($unixstart < $binend && $unixend > $binstart) {
                    $count[$binindex]++;
                } elseif ($binstart >= $unixend) {
                    break;
                }
            }
        }
        rsort($count);
        array_push($data["points"], $count[0]);
    }
    return $data;
}
Exemplo n.º 4
0
 function addResource($data)
 {
     global $user;
     $ownerid = getUserlistID($data['owner']);
     $esc = array('sysadminemail' => mysql_real_escape_string($data['sysadminemail']), 'sharedmailbox' => mysql_real_escape_string($data['sharedmailbox']));
     $keys = array('IPaddress', 'hostname', 'ownerid', 'stateid', 'checkininterval', 'installpath', '`keys`', 'sshport', 'sysadminEmailAddress', 'sharedMailBox', 'availablenetworks', 'NOT_STANDALONE', 'imagelibenable', 'publicIPconfiguration', 'imagelibgroupid', 'imagelibuser', 'imagelibkey', 'publicSubnetMask', 'publicDefaultGateway', 'publicDNSserver');
     $values = array("'{$data['ipaddress']}'", "'{$data['name']}'", $ownerid, $data['stateid'], $data['checkininterval'], "'{$data['installpath']}'", "'{$data['keys']}'", $data['sshport'], "'{$esc['sysadminemail']}'", "'{$esc['sharedmailbox']}'", "'{$data['availablenetworks']}'", "'{$data['federatedauth']}'", $data['imagelibenable'], "'{$data['publicIPconfig']}'");
     if ($data['imagelibenable'] == 1) {
         $values[] = $data['imagelibgroupid'];
         $values[] = "'{$data['imagelibuser']}'";
         $values[] = "'{$data['imagelibkey']}'";
     } else {
         $values[] = 'NULL';
         $values[] = 'NULL';
         $values[] = 'NULL';
     }
     if ($data['publicIPconfig'] == 'static') {
         $values[] = "'{$data['publicnetmask']}'";
         $values[] = "'{$data['publicgateway']}'";
         $values[] = "'{$data['publicdnsserver']}'";
     } else {
         $values[] = 'NULL';
         $values[] = 'NULL';
         $values[] = 'NULL';
     }
     $query = "INSERT INTO managementnode (" . implode(', ', $keys) . ") VALUES (" . implode(', ', $values) . ")";
     doQuery($query);
     $rscid = dbLastInsertID();
     // add entry in resource table
     $query = "INSERT INTO resource " . "(resourcetypeid, " . "subid) " . "VALUES (16, " . "{$rscid})";
     doQuery($query);
     $resourceid = dbLastInsertID();
     # NAT host
     if ($data['nathostenabled']) {
         $query = "INSERT INTO nathost " . "(resourceid, " . "publicIPaddress, " . "internalIPaddress) " . "VALUES " . "({$resourceid}, " . "'{$data['natpublicIPaddress']}', " . "'{$data['natinternalIPaddress']}')";
         doQuery($query);
     }
     # time server
     $globalval = getVariable('timesource|global');
     if ($data['timeservers'] != $globalval) {
         setVariable("timesource|{$data['name']}", $data['timeservers'], 'none');
     }
     return $rscid;
 }
Exemplo n.º 5
0
function updateRequest($requestid)
{
    global $requestInfo, $user;
    $userid = getUserlistID($user['unityid']);
    $startstamp = unixToDatetime($requestInfo["start"]);
    $endstamp = unixToDatetime($requestInfo["end"]);
    if ($requestInfo["start"] <= time()) {
        $nowfuture = "now";
    } else {
        $nowfuture = "future";
    }
    $query = "SELECT logid FROM request WHERE id = {$requestid}";
    $qh = doQuery($query, 146);
    if (!($row = mysql_fetch_row($qh))) {
        abort(148);
    }
    $logid = $row[0];
    $query = "UPDATE request " . "SET start = '{$startstamp}', " . "end = '{$endstamp}', " . "datemodified = NOW() " . "WHERE id = {$requestid}";
    doQuery($query, 101);
    if ($nowfuture == 'now') {
        addChangeLogEntry($logid, NULL, $endstamp, $startstamp, NULL, NULL, 1);
        return;
    }
    $requestData = getRequestInfo($requestid);
    foreach ($requestInfo["images"] as $key => $imgid) {
        foreach ($requestData["reservations"] as $key2 => $res) {
            if ($res["imageid"] == $imgid) {
                $oldCompid = $res["computerid"];
                unset($requestData['reservations'][$key2]);
                break;
            }
        }
        $computerid = $requestInfo["computers"][$key];
        $mgmtnodeid = $requestInfo['mgmtnodes'][$key];
        $query = "UPDATE reservation " . "SET computerid = {$computerid}, " . "managementnodeid = {$mgmtnodeid} " . "WHERE requestid = {$requestid} AND " . "imageid = {$imgid} AND " . "computerid = {$oldCompid}";
        doQuery($query, 147);
        addChangeLogEntry($logid, NULL, $endstamp, $startstamp, $computerid, NULL, 1);
        $query = "UPDATE sublog " . "SET computerid = {$computerid} " . "WHERE logid = {$logid} AND " . "imageid = {$imgid} AND " . "computerid = {$oldCompid}";
        doQuery($query, 101);
    }
}
Exemplo n.º 6
0
function getStatGraphConVMUserData($start, $end, $affilid, $mode, $provid)
{
    $startdt = $start . " 00:00:00";
    $enddt = $end . " 23:59:59";
    $startunix = datetimeToUnix($startdt);
    $endunix = datetimeToUnix($enddt) + 1;
    $daycnt = ($endunix - $startunix) / SECINDAY;
    if ($daycnt - (int) $daycnt > 0.5) {
        $daycnt = (int) $daycnt + 1;
    } else {
        $daycnt = (int) $daycnt;
    }
    if ($endunix >= time()) {
        $daycnt--;
    }
    $data = array();
    $data["points"] = array();
    $data["xlabels"] = array();
    $data["maxy"] = 0;
    $cachepts = array();
    $addcache = array();
    $reloadid = getUserlistID('vclreload@Local');
    $cnt = 0;
    $query = "SELECT statdate, " . "value " . "FROM statgraphcache " . "WHERE graphtype = 'concurvm' AND " . "affiliationid = {$affilid} AND " . "statdate >= '{$start}' AND " . "statdate <= '{$end}' AND " . "provisioningid = {$provid}";
    $qh = doQuery($query, 101);
    while ($row = mysql_fetch_assoc($qh)) {
        $cachepts[$row['statdate']] = $row['value'];
    }
    if (count($cachepts) + 31 < $daycnt) {
        $data = array('nodata' => i('(too much computational time required to generate this graph)'));
        return $data;
    }
    for ($daystart = $startunix; $daystart < $endunix; $daystart += SECINDAY) {
        $cnt++;
        $startdt = unixToDatetime($daystart);
        $enddt = unixToDatetime($daystart + SECINDAY);
        $tmp = explode(' ', $startdt);
        $key = $tmp[0];
        if (array_key_exists($key, $cachepts)) {
            $value = $cachepts[$key];
        } else {
            $count = array();
            for ($j = 0; $j < 24; $j++) {
                $count[$j] = 0;
            }
            if ($affilid != 0) {
                $query = "SELECT l.start AS start, " . "l.finalend AS end " . "FROM log l, " . "sublog s, " . "computer c, " . "user u " . "WHERE l.userid = u.id AND " . "l.start < '{$enddt}' AND " . "l.finalend > '{$startdt}' AND " . "s.logid = l.id AND " . "s.computerid = c.id AND " . "l.wasavailable = 1 AND " . "c.type = 'virtualmachine' AND " . "l.userid != {$reloadid} AND " . "u.affiliationid = {$affilid}";
            } else {
                if ($mode == 'default') {
                    $query = "SELECT l.start AS start, " . "l.finalend AS end " . "FROM log l, " . "sublog s, " . "computer c " . "WHERE l.start < '{$enddt}' AND " . "l.finalend > '{$startdt}' AND " . "s.logid = l.id AND " . "s.computerid = c.id AND " . "l.wasavailable = 1 AND " . "c.type = 'virtualmachine' AND " . "l.userid != {$reloadid}";
                } elseif ($mode == 'provisioning') {
                    $query = "SELECT l.start AS start, " . "l.finalend AS end " . "FROM computer c, " . "sublog s, " . "log l " . "JOIN (" . "SELECT s.logid, " . "MIN(s.computerid) AS computerid " . "FROM sublog s, " . "computer c " . "WHERE s.computerid = c.id AND " . "c.provisioningid = {$provid} " . "GROUP BY logid " . ") AS s2 ON (s2.logid = l.id) " . "WHERE l.start < '{$enddt}' AND " . "l.finalend > '{$startdt}' AND " . "s.logid = l.id AND " . "s.computerid = c.id AND " . "l.wasavailable = 1 AND " . "c.type = 'virtualmachine' AND " . "l.userid != {$reloadid}";
                }
            }
            $qh = doQuery($query, 101);
            while ($row = mysql_fetch_assoc($qh)) {
                $unixstart = datetimeToUnix($row["start"]);
                $unixend = datetimeToUnix($row["end"]);
                for ($binstart = $daystart, $binend = $daystart + 3600, $binindex = 0; $binstart <= $unixend && $binend <= $daystart + SECINDAY; $binstart += 3600, $binend += 3600, $binindex++) {
                    if ($binend <= $unixstart) {
                        continue;
                    } elseif ($unixstart < $binend && $unixend > $binstart) {
                        $count[$binindex]++;
                    } elseif ($binstart >= $unixend) {
                        break;
                    }
                }
            }
            rsort($count);
            $value = $count[0];
            $addcache[$startdt] = (int) $value;
        }
        $label = date('m/d/Y', $daystart);
        $data["points"][] = array('y' => $value, 'tooltip' => "{$label}: {$value}");
        if ($value > $data['maxy']) {
            $data['maxy'] = $value;
        }
        $data['xlabels'][] = array('value' => $cnt, 'text' => $label);
    }
    if (count($addcache)) {
        addToStatGraphCache('concurvm', $addcache, $affilid, $provid);
    }
    return $data;
}
Exemplo n.º 7
0
function processBlockAllocationInput()
{
    global $user;
    $return = array();
    $method = getContinuationVar('method');
    $return['name'] = processInputVar('name', ARG_STRING);
    $return['owner'] = processInputVar('owner', ARG_STRING);
    $return['imageid'] = processInputVar('imageid', ARG_NUMERIC);
    $return['seats'] = processInputVar('seats', ARG_NUMERIC);
    $return['groupid'] = processInputVar('groupid', ARG_NUMERIC);
    $override = getContinuationVar('override', 0);
    $type = processInputVar('type', ARG_STRING);
    $err = 0;
    if ($method != 'request' && !preg_match('/^([-a-zA-Z0-9\\. \\(\\)]){3,80}$/', $return['name'])) {
        $errmsg = i("The name can only contain letters, numbers, spaces, dashes(-), and periods(.) and can be from 3 to 80 characters long");
        $err = 1;
    }
    $resources = getUserResources(array("imageAdmin", "imageCheckOut"));
    $resources["image"] = removeNoCheckout($resources["image"]);
    if (!array_key_exists($return['imageid'], $resources['image'])) {
        $errmsg = i("The submitted image is invalid.");
        $err = 1;
    }
    if (!$err && $method != 'request' && !validateUserid($return['owner'])) {
        $errmsg = i("The submitted owner is invalid.");
        $err = 1;
    } else {
        $return['ownerid'] = getUserlistID($return['owner']);
    }
    $groups = getUserGroups(0, $user['affiliationid']);
    $extragroups = getContinuationVar('extragroups');
    if (!$err && !array_key_exists($return['groupid'], $groups) && !array_key_exists($return['groupid'], $extragroups) && $return['groupid'] != 0) {
        $errmsg = i("The submitted user group is invalid.");
        $err = 1;
    }
    if (!$err && $return['groupid'] == 0) {
        $return['groupid'] = 'NULL';
    }
    if (!$err && ($return['seats'] < MIN_BLOCK_MACHINES || $return['seats'] > MAX_BLOCK_MACHINES)) {
        $errmsg = sprintf(i("The submitted number of seats must be between %d and %d."), MIN_BLOCK_MACHINES, MAX_BLOCK_MACHINES);
        $err = 1;
    }
    if (!$err) {
        $imgdata = getImages(0, $return['imageid']);
        $concur = $imgdata[$return['imageid']]['maxconcurrent'];
        if (!is_null($concur) && $concur != 0 && $return['seats'] > $concur) {
            $errmsg = sprintf(i("The selected image can only have %d concurrent reservations. Please reduce the number of requested seats to %d or less."), $concur, $concur);
            $err = 1;
        }
    }
    $dooverride = 0;
    # check user group access to image
    if (($method == 'new' || $method == 'edit') && !$err && !$override) {
        $groupresources = getUserResources(array("imageAdmin", "imageCheckOut"), array("available"), 0, 0, 0, $return['groupid']);
        if (!array_key_exists($return['imageid'], $groupresources['image'])) {
            $dooverride = 1;
            $errmsg = i("WARNING - The selected user group does not currently have access to the selected environment. You can submit the Block Allocation again to ignore this warning.");
            $err = 1;
        }
    }
    if (!$err && $type != 'weekly' && $type != 'monthly' && $type != 'list') {
        $errmsg = i("You must select one of \"Repeating Weekly\", \"Repeating Monthly\", or \"List of Dates/Times\".");
        $err = 1;
    }
    if (!$err) {
        if ($type == 'list') {
            $slots = processInputVar('slots', ARG_STRING);
            $return['slots'] = explode(',', $slots);
            $return['times'] = array();
            $lastdate = array('day' => '', 'ts' => 0);
            foreach ($return['slots'] as $slot) {
                $tmp = explode('|', $slot);
                if (count($tmp) != 3) {
                    $errmsg = i("Invalid date/time submitted.");
                    $err = 1;
                    break;
                }
                $date = $tmp[0];
                if (!$err) {
                    $datets = strtotime($date);
                    if ($method != 'edit' && $datets < time() - SECINDAY) {
                        $errmsg = i("The date must be today or later.");
                        $err = 1;
                        break;
                    }
                }
                $return['times'][] = "{$tmp[1]}|{$tmp[2]}";
                if ($datets > $lastdate['ts']) {
                    $lastdate['ts'] = $datets;
                    $lastdate['day'] = $date;
                }
            }
            if (!$err) {
                $expirets = strtotime("{$lastdate['day']} 23:59:59");
                $return['expiretime'] = unixToDatetime($expirets);
            }
        }
        if ($type == 'weekly' || $type == 'monthly') {
            $return['startdate'] = processInputVar('startdate', ARG_NUMERIC);
            $return['enddate'] = processInputVar('enddate', ARG_NUMERIC);
            $times = processInputVar('times', ARG_STRING);
            $return['startts'] = strtotime($return['startdate']);
            $return['endts'] = strtotime($return['enddate']);
            if ($return['startts'] > $return['endts']) {
                $errmsg = i("The Last Date of Usage must be the same or later than the First Date of Usage.");
                $err = 1;
            } elseif ($method != 'edit' && $return['startts'] < time() - SECINDAY) {
                $errmsg = i("The start date must be today or later.");
                $err = 1;
            }
            $expirets = strtotime("{$return['enddate']} 23:59:59");
            $return['expiretime'] = unixToDatetime($expirets);
            $return['times'] = explode(',', $times);
        }
        foreach ($return['times'] as $time) {
            $tmp = explode('|', $time);
            if (count($tmp) != 2) {
                $errmsg = i("Invalid start/end time submitted");
                $err = 1;
                break;
            }
            $start = explode(':', $tmp[0]);
            if (count($start) != 2 || !is_numeric($start[0]) || !is_numeric($start[1]) || $start[0] < 0 || $start[0] > 23 || $start[1] < 0 || $start[1] > 59) {
                $errmsg = i("Invalid start time submitted");
                $err = 1;
                break;
            }
            $end = explode(':', $tmp[1]);
            if (count($end) != 2 || !is_numeric($end[0]) || !is_numeric($end[1]) || $end[0] < 0 || $end[0] > 23 || $end[1] < 0 || $end[1] > 59) {
                $errmsg = i("Invalid end time submitted");
                $err = 1;
                break;
            }
            $start = minuteOfDay($start[0], $start[1]);
            $end = minuteOfDay($end[0], $end[1]);
            if ($start >= $end) {
                $errmsg = i("Each start time must be less than the corresponding end time.");
                $err = 1;
                break;
            }
        }
        if ($type == 'weekly') {
            $validdays = 0;
            $errmsg = '';
            for ($day = $return['startts'], $i = 0; $i < 7, $day < $return['endts'] + SECINDAY; $i++, $day += SECINDAY) {
                $daynum = date('w', $day);
                $validdays |= 1 << $daynum;
            }
            $days = processInputVar('days', ARG_STRING);
            $dayscheck = processInputVar('days', ARG_NUMERIC);
            if ($days == '' && $dayscheck == '0') {
                $days = 0;
            }
            $return['daymask'] = 0;
            if (!$err) {
                foreach (explode(',', $days) as $day) {
                    if ($day == '' || $day < 0 || $day > 6) {
                        $errmsg = i("Invalid day submitted.");
                        $err = 1;
                        break;
                    }
                    $return['daymask'] |= 1 << $day;
                }
            }
            if (!$err && ($return['daymask'] & $validdays) == 0) {
                $errmsg = i("No valid days submitted for the specified date range.");
                $err = 1;
            }
        }
        if ($type == 'monthly') {
            $return['weeknum'] = processInputVar('weeknum', ARG_NUMERIC);
            $return['day'] = processInputVar('day', ARG_NUMERIC);
            if (!$err && ($return['weeknum'] < 1 || $return['weeknum'] > 5)) {
                $errmsg = i("Invalid week number submitted.");
                $err = 1;
            }
            if (!$err && ($return['day'] < 1 || $return['day'] > 7)) {
                $errmsg = i("Invalid day of week submitted.");
                $err = 1;
            }
            $times = getMonthlyBlockTimes('', $return['startts'], $return['endts'], $return['day'], $return['weeknum'], $return['times']);
            if (!$err && empty($times)) {
                $errmsg = i("Specified day of month not found in date range.");
                $err = 1;
            }
        }
    }
    if ($method == 'request') {
        $return['comments'] = processInputVar('comments', ARG_STRING);
        if (get_magic_quotes_gpc()) {
            $return['comments'] = stripslashes($return['comments']);
        }
        if (!$err && preg_match('/[<>]/', $return['comments'])) {
            $errmsg = i("<>\\'s are not allowed in the comments.");
            $err = 1;
        }
    }
    if ($err) {
        print "clearHideConfirmForm();";
        print "alert('{$errmsg}');";
        $data = array('extragroups' => $extragroups, 'method' => $method);
        if ($method == 'edit') {
            $data['blockid'] = getContinuationVar('blockid');
        }
        $cont = addContinuationsEntry('AJblockAllocationSubmit', $data, SECINWEEK, 1, 0);
        print "dojo.byId('submitcont').value = '{$cont}';";
        if ($dooverride) {
            $data['override'] = 1;
            $cont = addContinuationsEntry('AJblockAllocationSubmit', $data, SECINWEEK, 1, 0);
            print "dojo.byId('submitcont2').value = '{$cont}';";
        } else {
            print "dojo.byId('submitcont2').value = '';";
        }
    }
    $return['type'] = $type;
    $return['err'] = $err;
    return $return;
}
Exemplo n.º 8
0
function addGroup($data)
{
    global $viewmode;
    if ($data["type"] == "user") {
        $ownerid = getUserlistID($data["owner"]);
        $query = "INSERT INTO usergroup " . "(name, " . "affiliationid, " . "ownerid, " . "editusergroupid, " . "custom, " . "initialmaxtime, " . "totalmaxtime, ";
        if ($viewmode == ADMIN_DEVELOPER) {
            $query .= "overlapResCount, ";
        }
        $query .= "maxextendtime) " . "VALUES ('{$data["name"]}', " . "{$data["affiliationid"]}, " . "{$ownerid}, " . "{$data["editgroupid"]}, " . "1, " . "{$data["initialmax"]}, " . "{$data["totalmax"]}, ";
        if ($viewmode == ADMIN_DEVELOPER) {
            $query .= "{$data["overlap"]}, ";
        }
        $query .= "{$data["maxextend"]})";
    } else {
        $query = "INSERT INTO resourcegroup " . "(name, " . "ownerusergroupid, " . "resourcetypeid) " . "VALUES ('" . $data["name"] . "', " . $data["ownergroup"] . ", " . "'" . $data["resourcetypeid"] . "')";
    }
    $qh = doQuery($query, 305);
    clearPrivCache();
    return mysql_affected_rows($GLOBALS["mysql_link_vcl"]);
}
Exemplo n.º 9
0
function updateImage($data)
{
    $imgdata = getImages(0, $data["imageid"]);
    $imagenotes = getImageNotes($data['imageid']);
    $ownerid = getUserlistID($data["owner"]);
    if (empty($data['maxconcurrent']) || !is_numeric($data['maxconcurrent'])) {
        $data['maxconcurrent'] = 'NULL';
    }
    $query = "UPDATE image " . "SET prettyname = '{$data["prettyname"]}', " . "ownerid = {$ownerid}, " . "minram = {$data["minram"]}, " . "minprocnumber = {$data["minprocnumber"]}, " . "minprocspeed = {$data["minprocspeed"]}, " . "minnetwork = {$data["minnetwork"]}, " . "maxconcurrent = {$data["maxconcurrent"]}, " . "reloadtime = {$data["reloadtime"]}, " . "forcheckout = {$data["forcheckout"]}, " . "description = '{$data["description"]}', " . "`usage` = '{$data["usage"]}' " . "WHERE id = {$data["imageid"]}";
    $qh = doQuery($query, 200);
    $return = mysql_affected_rows($GLOBALS["mysql_link_vcl"]);
    if (empty($imgdata[$data["imageid"]]["imagemetaid"]) && ($data["checkuser"] == 0 || $data["usergroupid"] != 0)) {
        if ($data["usergroupid"] == 0) {
            $data["usergroupid"] = "NULL";
        }
        $query = "INSERT INTO imagemeta " . "(checkuser, " . "usergroupid) " . "VALUES ({$data["checkuser"]}, " . "{$data["usergroupid"]})";
        doQuery($query, 101);
        $qh = doQuery("SELECT LAST_INSERT_ID() FROM imagemeta", 101);
        if (!($row = mysql_fetch_row($qh))) {
            abort(101);
        }
        $imagemetaid = $row[0];
        $query = "UPDATE image " . "SET imagemetaid = {$imagemetaid} " . "WHERE id = {$data["imageid"]}";
        doQuery($query, 101);
    } elseif (!empty($imgdata[$data["imageid"]]["imagemetaid"]) && ($data["checkuser"] != $imgdata[$data["imageid"]]["checkuser"] || $data["usergroupid"] != $imgdata[$data["imageid"]]["usergroupid"])) {
        if ($data["usergroupid"] == 0) {
            $data["usergroupid"] = "NULL";
        }
        $query = "UPDATE imagemeta " . "SET checkuser = {$data["checkuser"]}, " . "usergroupid = {$data["usergroupid"]} " . "WHERE id = {$imgdata[$data["imageid"]]["imagemetaid"]}";
        doQuery($query, 101);
    }
    return $return;
}
Exemplo n.º 10
0
function addSchedule($data)
{
    $ownerid = getUserlistID($data["owner"]);
    $query = "INSERT INTO schedule " . "(name, " . "ownerid) " . "VALUES ('" . $data["name"] . "', " . "{$ownerid})";
    doQuery($query, 220);
    $affectedrows = mysql_affected_rows($GLOBALS["mysql_link_vcl"]);
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM schedule", 221);
    if (!($row = mysql_fetch_row($qh))) {
        abort(222);
    }
    $query = "INSERT INTO resource " . "(resourcetypeid, " . "subid) " . "VALUES (15, " . $row[0] . ")";
    doQuery($query, 223);
    return $row[0];
}
Exemplo n.º 11
0
function AJvmFromHostDelayed()
{
    $data = getContinuationVar();
    $vclreloadid = getUserlistID('vclreload@Local');
    $imageid = getImageId('noimage');
    $imagerevisionid = getProductionRevisionid($imageid);
    $fails = array();
    foreach ($data as $comp) {
        $end = datetimeToUnix($comp['end2']) + SECINMONTH;
        $end = unixToDatetime($end);
        if (!simpleAddRequest($comp['id'], $imageid, $imagerevisionid, $comp['end2'], $end, 18, $vclreloadid)) {
            $fails[] = array('name' => $comp['hostname'], 'reason' => 'nomgtnode');
        }
    }
    $cont = addContinuationsEntry('vmhostdata');
    $arr = array('msg' => 'SUCCESS', 'cont' => $cont, 'fails' => $fails);
    sendJSON($arr);
}
Exemplo n.º 12
0
function XMLRPCremoveUsersFromGroup($name, $affiliation, $users)
{
    global $user, $findAffilFuncs;
    if (!in_array('groupAdmin', $user['privileges'])) {
        return array('status' => 'error', 'errorcode' => 16, 'errormsg' => 'access denied for managing user groups');
    }
    $validate = array('name' => $name, 'affiliation' => $affiliation);
    $rc = validateAPIgroupInput($validate, 1);
    if ($rc['status'] == 'error') {
        return $rc;
    }
    $query = "SELECT ownerid, " . "editusergroupid AS editgroupid " . "FROM usergroup " . "WHERE id = {$rc['id']}";
    $qh = doQuery($query, 101);
    if (!($row = mysql_fetch_assoc($qh))) {
        return array('status' => 'error', 'errorcode' => 18, 'errormsg' => 'user group with submitted name and affiliation does not exist');
    }
    # if not owner and not member of managing group, no access
    if ($user['id'] != $row['ownerid'] && !array_key_exists($row['editgroupid'], $user['groups'])) {
        return array('status' => 'error', 'errorcode' => 28, 'errormsg' => 'access denied to user group with submitted name and affiliation');
    }
    $fails = array();
    foreach ($users as $_user) {
        if (empty($_user)) {
            continue;
        }
        $esc_user = mysql_escape_string($_user);
        # check that affiliation of user can be determined because getUserlistID
        #   will abort if it can't find it
        $affilok = 0;
        foreach ($findAffilFuncs as $func) {
            if ($func($_user, $dump)) {
                $affilok = 1;
            }
        }
        if (!$affilok) {
            $fails[] = $_user;
            continue;
        }
        $userid = getUserlistID($esc_user, 1);
        if (is_null($userid)) {
            $fails[] = $_user;
        } else {
            deleteUserGroupMember($userid, $rc['id']);
        }
    }
    if (count($fails)) {
        $cnt = 'some';
        $code = 36;
        if (count($fails) == count($users)) {
            $cnt = 'any';
            $code = 37;
        }
        return array('status' => 'warning', 'failedusers' => $fails, 'warningcode' => $code, 'warningmsg' => "failed to remove {$cnt} users from user group");
    }
    return array('status' => 'success');
}
Exemplo n.º 13
0
function addComputer($data)
{
    $ownerid = getUserlistID($data["owner"]);
    $query = "INSERT INTO computer " . "(stateid, " . "ownerid, " . "platformid, " . "scheduleid, " . "currentimageid, " . "RAM, " . "procnumber, " . "procspeed, " . "network, " . "hostname, " . "IPaddress, " . "type, " . "provisioningid) " . "VALUES (" . $data["stateid"] . ", " . "{$ownerid}, " . $data["platformid"] . ", " . $data["scheduleid"] . ", " . "4, " . $data["ram"] . ", " . $data["numprocs"] . ", " . $data["procspeed"] . ", " . $data["network"] . ", " . "'" . $data["hostname"] . "', " . "'" . $data["ipaddress"] . "', " . "'" . $data["type"] . "', " . "'" . $data["provisioningid"] . "')";
    doQuery($query, 195);
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM computer", 196);
    if (!($row = mysql_fetch_row($qh))) {
        abort(197);
    }
    $query = "INSERT INTO resource " . "(resourcetypeid, " . "subid) " . "VALUES (12, " . $row[0] . ")";
    doQuery($query, 198);
    // add computer into selected groups
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM resource", 101);
    if (!($row = mysql_fetch_row($qh))) {
        abort(197);
    }
    foreach (array_keys($data["computergroup"]) as $groupid) {
        $query = "INSERT INTO resourcegroupmembers " . "(resourceid, " . "resourcegroupid) " . "VALUES ({$row[0]}, " . "{$groupid})";
        doQuery($query, 101);
    }
}
Exemplo n.º 14
0
function XMLRPCprocessBlockTime($blockTimesid, $ignoreprivileges = 0)
{
    global $requestInfo, $user, $xmlrpcBlockAPIUsers;
    if (!in_array($user['id'], $xmlrpcBlockAPIUsers)) {
        return array('status' => 'error', 'errorcode' => 34, 'errormsg' => 'access denied for managing block allocations');
    }
    # validate $blockTimesid
    if (!is_numeric($blockTimesid)) {
        return array('status' => 'error', 'errorcode' => 77, 'errormsg' => 'Invalid blockTimesid specified');
    }
    # validate ignoreprivileges
    if (!is_numeric($ignoreprivileges) || $ignoreprivileges < 0 || $ignoreprivileges > 1) {
        return array('status' => 'error', 'errorcode' => 86, 'errormsg' => 'ignoreprivileges must be 0 or 1');
    }
    $return = array('status' => 'success');
    $query = "SELECT bt.start, " . "bt.end, " . "br.imageid, " . "br.numMachines, " . "br.groupid, " . "br.expireTime " . "FROM blockRequest br, " . "blockTimes bt " . "WHERE bt.blockRequestid = br.id AND " . "bt.id = {$blockTimesid}";
    $qh = doQuery($query, 101);
    if (!($rqdata = mysql_fetch_assoc($qh))) {
        return array('status' => 'error', 'errorcode' => 8, 'errormsg' => 'unknown blockTimesid');
    }
    if (datetimeToUnix($rqdata['expireTime']) < time()) {
        return array('status' => 'error', 'errorcode' => 9, 'errormsg' => 'expired block allocation');
    }
    $images = getImages(0, $rqdata['imageid']);
    if (empty($images)) {
        return array('status' => 'error', 'errorcode' => 10, 'errormsg' => 'invalid image associated with block allocation');
    }
    $unixstart = datetimeToUnix($rqdata['start']);
    $unixend = datetimeToUnix($rqdata['end']);
    $revisionid = getProductionRevisionid($rqdata['imageid']);
    $imgLoadTime = getImageLoadEstimate($rqdata['imageid']);
    if ($imgLoadTime == 0) {
        $imgLoadTime = $images[$rqdata['imageid']]['reloadtime'] * 60;
    }
    $vclreloadid = getUserlistID('vclreload@Local');
    $groupmembers = getUserGroupMembers($rqdata['groupid']);
    $userids = array_keys($groupmembers);
    # add any computers from future reservations users in the group made
    if (!empty($groupmembers)) {
        ## find reservations by users
        $allids = implode(',', $userids);
        $query = "SELECT rq.id AS reqid, " . "UNIX_TIMESTAMP(rq.start) AS start, " . "rq.userid " . "FROM request rq, " . "reservation rs " . "WHERE rs.requestid = rq.id AND " . "rq.userid IN ({$allids}) AND " . "rq.start < '{$rqdata['end']}' AND " . "rq.end > '{$rqdata['start']}' AND " . "rs.imageid = {$rqdata['imageid']} AND " . "rs.computerid NOT IN (SELECT computerid " . "FROM blockComputers " . "WHERE blockTimeid = {$blockTimesid})";
        $qh = doQuery($query);
        $donereqids = array();
        $blockCompVals = array();
        $checkstartbase = $unixstart - $imgLoadTime - 300;
        $reloadstartbase = unixToDatetime($checkstartbase);
        $rows = mysql_num_rows($qh);
        while ($row = mysql_fetch_assoc($qh)) {
            if (array_key_exists($row['reqid'], $donereqids)) {
                continue;
            }
            $donereqids[$row['reqid']] = 1;
            if ($row['start'] < datetimeToUnix($rqdata['start'])) {
                $checkstart = $row['start'] - $imgLoadTime - 300;
                $reloadstart = unixToDatetime($checkstart);
                $reloadend = unixToDatetime($row['start']);
            } else {
                $checkstart = $checkstartbase;
                $reloadstart = $reloadstartbase;
                $reloadend = $rqdata['start'];
            }
            # check to see if computer is available for whole block
            $rc = isAvailable($images, $rqdata['imageid'], $revisionid, $checkstart, $unixend, 1, $row['reqid'], $row['userid'], $ignoreprivileges, 0, '', '', 1);
            // if not available for whole block, just skip this one
            if ($rc < 1) {
                continue;
            }
            $compid = $requestInfo['computers'][0];
            # create reload reservation
            $reqid = simpleAddRequest($compid, $rqdata['imageid'], $revisionid, $reloadstart, $reloadend, 19, $vclreloadid);
            if ($reqid == 0) {
                continue;
            }
            # add to blockComputers
            $blockCompVals[] = "({$blockTimesid}, {$compid}, {$rqdata['imageid']}, {$reqid})";
            # process any subimages
            for ($key = 1; $key < count($requestInfo['computers']); $key++) {
                $subimageid = $requestInfo['images'][$key];
                $subrevid = getProductionRevisionid($subimageid);
                $compid = $requestInfo['computers'][$key];
                $mgmtnodeid = $requestInfo['mgmtnodes'][$key];
                $blockCompVals[] = "({$blockTimesid}, {$compid}, {$subimageid}, {$reqid})";
                $query = "INSERT INTO reservation " . "(requestid, " . "computerid, " . "imageid, " . "imagerevisionid, " . "managementnodeid) " . "VALUES " . "({$reqid}, " . "{$compid}, " . "{$subimageid}, " . "{$subrevid}, " . "{$mgmtnodeid})";
                doQuery($query, 101);
            }
        }
        if (count($blockCompVals)) {
            $blockComps = implode(',', $blockCompVals);
            $query = "INSERT INTO blockComputers " . "(blockTimeid, computerid, imageid, reloadrequestid) " . "VALUES {$blockComps}";
            doQuery($query);
        }
        cleanSemaphore();
    }
    # check to see if all computers have been allocated
    $query = "SELECT COUNT(computerid) AS allocated " . "FROM blockComputers " . "WHERE blockTimeid = {$blockTimesid}";
    $qh = doQuery($query, 101);
    if (!($row = mysql_fetch_assoc($qh))) {
        return array('status' => 'error', 'errorcode' => 15, 'errormsg' => 'failure to communicate with database');
    }
    $compCompleted = $row['allocated'];
    if (array_key_exists('subimages', $images[$rqdata['imageid']])) {
        $compsPerAlloc = 1 + count($images[$rqdata['imageid']]['subimages']);
    } else {
        $compsPerAlloc = 1;
    }
    $toallocate = $rqdata['numMachines'] * $compsPerAlloc - $compCompleted;
    if ($toallocate == 0) {
        if (count($blockCompVals)) {
            return array('status' => 'success', 'allocated' => $rqdata['numMachines'], 'unallocated' => 0);
        }
        return array('status' => 'completed');
    }
    $reqToAlloc = $toallocate / $compsPerAlloc;
    if (!$ignoreprivileges) {
        # get userids in user group
        if (empty($groupmembers)) {
            return array('status' => 'error', 'errorcode' => 11, 'errormsg' => 'empty user group and ignoreprivileges set to 0');
        }
        # make length of $userids match $reqToAlloc by duplicating or trimming some users
        while ($reqToAlloc > count($userids)) {
            $userids = array_merge($userids, $userids);
        }
        if ($reqToAlloc < count($userids)) {
            $userids = array_splice($userids, 0, $reqToAlloc);
        }
    }
    # staggering: stagger start times for this round (ie, do not worry about
    #   previous processing of this block time) such that there is 1 minute
    #   between the start times for each allocation
    $stagExtra = $reqToAlloc * 60;
    # determine estimated load time
    $loadtime = $imgLoadTime + 10 * 60;
    # add 10 minute fudge factor
    if (time() + $loadtime + $stagExtra > $unixstart) {
        $return['status'] = 'warning';
        $return['warningcode'] = 13;
        $return['warningmsg'] = 'possibly insufficient time to load machines';
    }
    $start = unixToDatetime($unixstart - $loadtime);
    $userid = 0;
    $allocated = 0;
    $blockCompVals = array();
    # FIXME (maybe) - if some subset of users in the user group have available
    # computers, but others do not, $allocated will be less than the desired
    # number of machines; however, calling this function enough times will
    # result in enough machines being allocated because they will continue to be
    # allocated based on the ones with machines available; this seems like odd
    # behavior
    $stagCnt = 0;
    $stagTime = 60;
    # stagger reload reservations by 1 min
    if ($imgLoadTime > 840) {
        // if estimated load time is > 14 min
        $stagTime = 120;
    }
    #    stagger reload reservations by 2 min
    for ($i = 0; $i < $reqToAlloc; $i++) {
        $stagunixstart = $unixstart - $loadtime - $stagCnt * $stagTime;
        $stagstart = unixToDatetime($stagunixstart);
        if (!$ignoreprivileges) {
            $userid = array_pop($userids);
        }
        # use end of block time to find available computers, but...
        $rc = isAvailable($images, $rqdata['imageid'], $revisionid, $stagunixstart, $unixend, 1, 0, $userid, $ignoreprivileges);
        if ($rc < 1) {
            continue;
        }
        $compid = $requestInfo['computers'][0];
        # ...use start of block time as end of reload reservation
        $reqid = simpleAddRequest($compid, $rqdata['imageid'], $revisionid, $stagstart, $rqdata['start'], 19, $vclreloadid);
        if ($reqid == 0) {
            continue;
        }
        $stagCnt++;
        $allocated++;
        $blockCompVals[] = "({$blockTimesid}, {$compid}, {$rqdata['imageid']}, {$reqid})";
        # process any subimages
        for ($key = 1; $key < count($requestInfo['computers']); $key++) {
            $subimageid = $requestInfo['images'][$key];
            $subrevid = getProductionRevisionid($subimageid);
            $compid = $requestInfo['computers'][$key];
            $mgmtnodeid = $requestInfo['mgmtnodes'][$key];
            $blockCompVals[] = "({$blockTimesid}, {$compid}, {$subimageid}, {$reqid})";
            $query = "INSERT INTO reservation " . "(requestid, " . "computerid, " . "imageid, " . "imagerevisionid, " . "managementnodeid) " . "VALUES " . "({$reqid}, " . "{$compid}, " . "{$subimageid}, " . "{$subrevid}, " . "{$mgmtnodeid})";
            doQuery($query, 101);
        }
        $blockComps = implode(',', $blockCompVals);
        $query = "INSERT INTO blockComputers " . "(blockTimeid, computerid, imageid, reloadrequestid) " . "VALUES {$blockComps}";
        doQuery($query, 101);
        cleanSemaphore();
        $blockCompVals = array();
    }
    if ($allocated == 0) {
        $return['status'] = 'warning';
        $return['warningcode'] = 14;
        $return['warningmsg'] = 'unable to allocate any machines';
    }
    $return['allocated'] = $compCompleted / $compsPerAlloc + $allocated;
    $return['unallocated'] = $rqdata['numMachines'] - $return['allocated'];
    return $return;
}
Exemplo n.º 15
0
 function scheduleVMsToAvailable($vmids)
 {
     # TODO test with vcld that will handle reservation for noimage okay
     # schedule $vmids to have noimage "loaded" on them in 15 minutes
     $allids = implode(',', $vmids);
     $query = "UPDATE computer " . "SET stateid = 5, " . "notes = '' " . "WHERE id IN ({$allids})";
     doQuery($query);
     $imageid = getImageId('noimage');
     $revid = getProductionRevisionid($imageid);
     $start = time() + 900;
     $end = $start + 3600;
     $startdt = unixToDatetime($start);
     $enddt = unixToDatetime($end);
     $vclreloadid = getUserlistID('vclreload@Local');
     foreach ($vmids as $vmid) {
         // if simpleAddRequest fails, vm is left assigned and in failed state, which is fine
         simpleAddRequest($vmid, $imageid, $revid, $startdt, $enddt, 19, $vclreloadid);
     }
 }
Exemplo n.º 16
0
function AJvmFromHostDelayed()
{
    $data = getContinuationVar();
    $vclreloadid = getUserlistID('vclreload@Local');
    foreach ($data as $comp) {
        $end = datetimeToUnix($comp['end2']) + SECINMONTH;
        $end = unixToDatetime($end);
        simpleAddRequest($comp['id'], 4, 3, $comp['end2'], $end, 18, $vclreloadid);
    }
    header('Content-Type: text/json-comment-filtered; charset=utf-8');
    $cont = addContinuationsEntry('vmhostdata');
    $arr = array('msg' => 'SUCCESS', 'cont' => $cont);
    print '/*{"items":' . json_encode($arr) . '}*/';
}
Exemplo n.º 17
0
        $newaffilname = $affilname;
    }
    $query = "INSERT INTO affiliation " . "(name, " . "shibname, " . "shibonly) " . "VALUES " . "('{$newaffilname}', " . "'" . mysql_escape_string($affil) . "', " . "1)";
    doQuery($query, 101, 'vcl', 1);
    unset($row);
    $row = array('name' => $newaffilname, 'shibonly' => 1);
}
$affil = $row['name'];
# create VCL userid
$userid = "{$username}@{$affil}";
if ($row['shibonly']) {
    $userdata = updateShibUser($userid);
    updateShibGroups($userdata['id'], $_SERVER['affiliation']);
    $usernid = $userdata['id'];
} else {
    $usernid = getUserlistID($userid);
}
# save data to shibauth table
$shibdata = array('Shib-Application-ID' => $_SERVER['Shib-Application-ID'], 'Shib-Identity-Provider' => $_SERVER['Shib-Identity-Provider'], 'Shib-AuthnContext-Dec' => $_SERVER['Shib-AuthnContext-Decl'], 'Shib-logouturl' => $_SERVER['Shib-logouturl'], 'eppn' => $_SERVER['Shib-logouturl'], 'unscoped-affiliation' => $_SERVER['unscoped-affiliation'], 'affiliation' => $_SERVER['affiliation']);
$serdata = mysql_escape_string(serialize($shibdata));
$query = "SELECT id " . "FROM shibauth " . "WHERE sessid = '{$_SERVER['Shib-Session-ID']}'";
$qh = doQuery($query, 101);
if ($row = mysql_fetch_assoc($qh)) {
    $shibauthid = $row['id'];
} else {
    $ts = strtotime($_SERVER['Shib-Authentication-Instant']);
    $ts = unixToDatetime($ts);
    $query = "INSERT INTO shibauth " . "(userid, " . "ts, " . "sessid, " . "data) " . "VALUES " . "({$usernid}, " . "'{$ts}', " . "'{$_SERVER['Shib-Session-ID']}', " . "'{$serdata}')";
    doQuery($query, 101);
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM shibauth", 101);
    if (!($row = mysql_fetch_row($qh))) {
Exemplo n.º 18
0
function getActiveResChartData()
{
    $data = array();
    $chartstart = unixFloor15(time() - 12 * 3600);
    $chartend = $chartstart + 12 * 3600 + 900;
    for ($time = $chartstart, $i = 0; $time < $chartend; $time += 900, $i++) {
        $fmttime = date('g:i a', $time);
        $data["points"][$i] = array('x' => $i, 'y' => 0, 'value' => $i, 'text' => $fmttime);
    }
    $data['maxy'] = 0;
    $reloadid = getUserlistID('vclreload@Local');
    $affilid = getDashboardAffilID();
    if ($affilid == 0) {
        $query = "SELECT l.id, " . "UNIX_TIMESTAMP(l.start) AS start, " . "UNIX_TIMESTAMP(l.finalend) AS end, " . "rq.stateid, " . "rq.laststateid " . "FROM log l " . "LEFT JOIN request rq ON (l.requestid = rq.id) " . "WHERE l.start < NOW() AND " . "l.finalend > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND " . "l.ending NOT IN ('failed', 'failedtest') AND " . "l.wasavailable = 1 AND " . "l.userid != {$reloadid}";
    } else {
        $query = "SELECT l.id, " . "UNIX_TIMESTAMP(l.start) AS start, " . "UNIX_TIMESTAMP(l.finalend) AS end, " . "rq.stateid, " . "rq.laststateid " . "FROM user u, " . "log l " . "LEFT JOIN request rq ON (l.requestid = rq.id) " . "WHERE l.userid = u.id AND " . "u.affiliationid = {$affilid} AND " . "l.start < NOW() AND " . "l.finalend > DATE_SUB(NOW(), INTERVAL 12 HOUR) AND " . "l.ending NOT IN ('failed', 'failedtest') AND " . "l.wasavailable = 1 AND " . "l.userid != {$reloadid}";
    }
    $qh = doQuery($query, 101);
    while ($row = mysql_fetch_assoc($qh)) {
        if ($row['stateid'] == 14) {
            $row['stateid'] = $row['laststateid'];
        }
        if ($row['end'] > time() && (is_null($row['stateid']) || preg_match('/^(1|5|10|11|12|16|17|18|19|21|22)$/', $row['stateid']))) {
            continue;
        }
        for ($binstart = $chartstart, $binend = $chartstart + 900, $binindex = 0; $binend <= $chartend; $binstart += 900, $binend += 900, $binindex++) {
            if ($binend <= $row['start']) {
                continue;
            } elseif ($row['start'] < $binend && $row['end'] > $binstart) {
                $data["points"][$binindex]['y']++;
            } elseif ($binstart >= $row['end']) {
                break;
            }
        }
    }
    for ($time = $chartstart, $i = 0; $time < $chartend; $time += 900, $i++) {
        if ($data["points"][$i]['y'] > $data['maxy']) {
            $data['maxy'] = $data['points'][$i]['y'];
        }
        $data["points"][$i]['tooltip'] = "{$data['points'][$i]['text']}: {$data['points'][$i]['y']}";
    }
    return $data;
}
Exemplo n.º 19
0
 function processInput($configid)
 {
     $return = array();
     $configtypes = getConfigTypes();
     $return['typeid'] = processInputVar('typeid', ARG_NUMERIC);
     if (!array_key_exists($return['typeid'], $configtypes)) {
         $this->errmsg = "Invalid type submitted";
         return 0;
     }
     $return['name'] = processInputVar('name', ARG_STRING);
     if (!preg_match('/^([-a-zA-Z0-9\\. ]){3,80}$/', $return['name'])) {
         $this->errmsg = "The name can only contain letters, numbers, spaces, dashes(-)," . "\\nand periods(.) and can be from 3 to 80 characters long";
         return 0;
     }
     # check for existance of name
     $name = mysql_real_escape_string($return['name']);
     $query = "SELECT id FROM config WHERE name = '{$name}' AND id != {$configid}";
     $qh = doQuery($query);
     if (mysql_num_rows($qh)) {
         $this->errmsg = "Another config with this name already exists.";
         return 0;
     }
     # owner
     $return['owner'] = processInputVar('owner', ARG_STRING);
     if (!validateUserid($return['owner'])) {
         $this->errmsg = "Invalid user submitted for owner";
         return 0;
     }
     $return['ownerid'] = getUserlistID($return['owner']);
     if (is_null($return['owner'])) {
         $this->errmsg = "Invalid user submitted for owner";
         return 0;
     }
     # optional
     $return['optional'] = processInputVar('optional', ARG_NUMERIC);
     if ($return['optional'] !== '0' && $return['optional'] !== '1') {
         $this->errmsg = "Invalid data submitted";
         return 0;
     }
     # type
     $return['type'] = $configtypes[$return['typeid']];
     # cluster
     if ($return['type'] == 'Cluster') {
         if (get_magic_quotes_gpc()) {
             $tmp = stripslashes($_POST['subimages']);
         } else {
             $tmp = $_POST['subimages'];
         }
         $tmp = json_decode($tmp, 1);
         if (is_null($tmp)) {
             $this->errmsg = "Invalid data submitted";
             return 0;
         }
         $resources = getUserResources(array("imageAdmin"));
         $return['subimages'] = $tmp['items'];
         foreach ($return['subimages'] as $key => $sub) {
             if (!array_key_exists($sub['imageid'], $resources['image'])) {
                 $this->errmsg = "Invalid subimage submitted";
                 return 0;
             } elseif (!is_numeric($sub['min']) || $sub['min'] < 1 || $sub['min'] > MAXSUBIMAGES || !is_numeric($sub['max']) || $sub['max'] < 1 || $sub['max'] > MAXSUBIMAGES || $sub['min'] > $sub['max']) {
                 $this->errmsg = "Invalid min/max value submitted for {$resources['image'][$sub['imageid']]}";
                 return 0;
             } elseif ($sub['deleted'] != 0 && $sub['deleted'] != 1) {
                 if ($sub['id'] > 15000000) {
                     unset($return['subimages'][$key]);
                 } else {
                     $return['subimages'][$key]['deleted'] = 0;
                 }
             }
         }
         $return['data'] = '';
     } elseif ($return['type'] == 'VLAN') {
         $tmp = getContinuationVar('configdata');
         $vdata = $tmp['variables'][0];
         $return['data'] = processInputVar('vlanid', ARG_NUMERIC);
         if ($return['data'] < 1 || $return['data'] > 4095) {
             $this->errmsg = "VLAN ID must be between 1 and 4095";
             return 0;
         }
         $var = array($vdata['id'] => array('id' => $vdata['id'], 'name' => 'VLAN', 'identifier' => $vdata['identifier'], 'datatypeid' => $vdata['datatypeid'], 'defaultvalue' => $return['data'], 'required' => '1', 'ask' => '0', 'deleted' => '0'));
         $return['configvariables'] = $var;
     } else {
         # TODO may need more validation on data
         $return['data'] = trim($_POST['data']);
         if (get_magic_quotes_gpc()) {
             $return['data'] = stripslashes($return['data']);
         }
         if (!is_string($return['data']) || $return['data'] == '') {
             $this->errmsg = "cannot be empty";
             return 0;
         }
         # TODO validate configvariable input
         if (get_magic_quotes_gpc()) {
             $tmp = stripslashes($_POST['configvariables']);
         } else {
             $tmp = $_POST['configvariables'];
         }
         $tmp = json_decode($tmp, 1);
         $return['configvariables'] = $tmp['items'];
     }
     return $return;
 }
Exemplo n.º 20
0
function isAvailable($images, $imageid, $imagerevisionid, $start, $end, $holdcomps, $requestid = 0, $userid = 0, $ignoreprivileges = 0, $forimaging = 0, $ip = '', $mac = '', $skipconcurrentcheck = 0)
{
    global $requestInfo, $user;
    $requestInfo["start"] = $start;
    $requestInfo["end"] = $end;
    $requestInfo["imageid"] = $imageid;
    $requestInfo["ipwarning"] = 0;
    $allocatedcompids = array(0);
    if (!is_array($imagerevisionid)) {
        $imagerevisionid = array($imageid => array($imagerevisionid));
    } elseif (empty($imagerevisionid)) {
        $imagerevisionid = array($imageid => array(getProductionRevisionid($imageid)));
    }
    if (schCheckMaintenance($start, $end)) {
        return debugIsAvailable(-2, 1, $start, $end, $imagerevisionid);
    }
    if (!array_key_exists($imageid, $images)) {
        return debugIsAvailable(0, 20, $start, $end, $imagerevisionid);
    }
    if ($requestInfo["start"] <= time()) {
        $now = 1;
        $nowfuture = 'now';
    } else {
        $now = 0;
        $nowfuture = 'future';
    }
    $scheduleids = getAvailableSchedules($start, $end);
    $requestInfo["computers"] = array();
    $requestInfo["computers"][0] = 0;
    $requestInfo["images"][0] = $imageid;
    $requestInfo["imagerevisions"][0] = $imagerevisionid[$imageid][0];
    # build array of subimages
    # TODO handle mininstance
    if (!$forimaging && $images[$imageid]["imagemetaid"] != NULL) {
        $count = 1;
        foreach ($images[$imageid]["subimages"] as $imgid) {
            $requestInfo['computers'][$count] = 0;
            $requestInfo['images'][$count] = $imgid;
            if (array_key_exists($imgid, $imagerevisionid) && array_key_exists($count, $imagerevisionid[$imgid])) {
                $requestInfo['imagerevisions'][$count] = $imagerevisionid[$imgid][$count];
            } else {
                $requestInfo['imagerevisions'][$count] = getProductionRevisionid($imgid);
            }
            $count++;
        }
    }
    $startstamp = unixToDatetime($start);
    $endstamp = unixToDatetime($end + 900);
    if (!empty($mac) || !empty($ip)) {
        # check for overlapping use of mac or ip
        $query = "SELECT rq.id " . "FROM reservation rs, " . "request rq, " . "serverrequest sr " . "WHERE '{$startstamp}' < (rq.end + INTERVAL 900 SECOND) AND " . "'{$endstamp}' > rq.start AND " . "sr.requestid = rq.id AND " . "rs.requestid = rq.id AND " . "(sr.fixedIP = '{$ip}' OR " . "sr.fixedMAC = '{$mac}') AND " . "rq.stateid NOT IN (1,5,11,12) ";
        if ($requestid) {
            $query .= "AND rq.id != {$requestid} ";
        }
        $query .= "LIMIT 1";
        $qh = doQuery($query, 101);
        if (mysql_num_rows($qh)) {
            return debugIsAvailable(-3, 2, $start, $end, $imagerevisionid);
        }
        # check for IP being used by a management node
        $query = "SELECT id " . "FROM managementnode " . "WHERE IPaddress = '{$ip}' AND " . "stateid != 1";
        $qh = doQuery($query, 101);
        if (mysql_num_rows($qh)) {
            return debugIsAvailable(-4, 16, $start, $end, $imagerevisionid);
        }
    }
    if ($requestid) {
        $requestData = getRequestInfo($requestid);
    }
    $vmhostcheckdone = 0;
    $ignorestates = "'maintenance','vmhostinuse','hpc','failed'";
    if ($now) {
        $ignorestates .= ",'reloading','reload','timeout','inuse'";
    }
    foreach ($requestInfo["images"] as $key => $imageid) {
        # check for max concurrent usage of image
        if (!$skipconcurrentcheck && $images[$imageid]['maxconcurrent'] != NULL) {
            if ($userid == 0) {
                $usersgroups = $user['groups'];
            } else {
                $testuser = getUserInfo($userid, 0, 1);
                if (is_null($testuser)) {
                    return debugIsAvailable(0, 17, $start, $end, $imagerevisionid);
                }
                $usersgroups = $testuser['groups'];
            }
            $decforedit = 0;
            $compids = array();
            $reloadid = getUserlistID('vclreload@Local');
            $query = "SELECT rs.computerid, " . "rq.id AS reqid " . "FROM reservation rs, " . "request rq " . "WHERE '{$startstamp}' < (rq.end + INTERVAL 900 SECOND) AND " . "'{$endstamp}' > rq.start AND " . "rs.requestid = rq.id AND " . "rs.imageid = {$imageid} AND " . "rq.stateid NOT IN (1,5,11,12,16,17) AND " . "rq.userid != {$reloadid}";
            $qh = doQuery($query, 101);
            while ($row = mysql_fetch_assoc($qh)) {
                $compids[] = $row['computerid'];
                if ($row['reqid'] == $requestid) {
                    $decforedit = 1;
                }
            }
            $usagecnt = count($compids);
            $allids = implode("','", $compids);
            $ignoregroups = implode("','", array_keys($usersgroups));
            $query = "SELECT COUNT(bc.imageid) AS currentusage " . "FROM blockComputers bc, " . "blockRequest br, " . "blockTimes bt " . "WHERE bc.blockTimeid = bt.id AND " . "bt.blockRequestid = br.id AND " . "bc.imageid = {$imageid} AND " . "bc.computerid NOT IN ('{$allids}') AND " . "br.groupid NOT IN ('{$ignoregroups}') AND " . "'{$startstamp}' < (bt.end + INTERVAL 900 SECOND) AND " . "'{$endstamp}' > bt.start AND " . "bt.skip != 1 AND " . "br.status != 'deleted'";
            $qh = doQuery($query);
            if (!($row = mysql_fetch_assoc($qh))) {
                cleanSemaphore();
                return debugIsAvailable(0, 3, $start, $end, $imagerevisionid);
            }
            if ($usagecnt + $row['currentusage'] - $decforedit >= $images[$imageid]['maxconcurrent']) {
                cleanSemaphore();
                return debugIsAvailable(-1, 4, $start, $end, $imagerevisionid);
            }
        }
        $platformid = getImagePlatform($imageid);
        if (is_null($platformid)) {
            cleanSemaphore();
            return debugIsAvailable(0, 5, $start, $end, $imagerevisionid);
        }
        # get computers $imageid maps to
        $compids = getMappedResources($imageid, "image", "computer");
        if (!count($compids)) {
            cleanSemaphore();
            return debugIsAvailable(0, 6, $start, $end, $imagerevisionid);
        }
        $mappedcomputers = implode(',', $compids);
        // if $ip specified, only look at computers under management nodes that can
        #   handle that network
        if ($ip != '') {
            $mappedmns = getMnsFromImage($imageid);
            $mnnets = checkAvailableNetworks($ip);
            $intersect = array_intersect($mappedmns, $mnnets);
            $tmpcompids = array();
            foreach ($intersect as $mnid) {
                $tmp2 = getMappedResources($mnid, 'managementnode', 'computer');
                $tmpcompids = array_merge($tmpcompids, $tmp2);
            }
            $tmpcompids = array_unique($tmpcompids);
            $newcompids = array_intersect($compids, $tmpcompids);
            if (!count($newcompids)) {
                cleanSemaphore();
                return debugIsAvailable(0, 18, $start, $end, $imagerevisionid);
            }
            $mappedcomputers = implode(',', $newcompids);
        }
        #get computers for available schedules and platforms
        $computerids = array();
        $currentids = array();
        $blockids = array();
        $altRemoveBlockCheck = 0;
        // if we are modifying a request and it is after the start time, only allow
        // the scheduled computer(s) to be modified
        if ($requestid && datetimeToUnix($requestData["start"]) <= time()) {
            $altRemoveBlockCheck = 1;
            foreach ($requestData["reservations"] as $key2 => $res) {
                if ($res["imageid"] == $imageid) {
                    $compid = $res["computerid"];
                    unset($requestData['reservations'][$key2]);
                    break;
                }
            }
            array_push($computerids, $compid);
            array_push($currentids, $compid);
            $query = "SELECT scheduleid " . "FROM computer " . "WHERE id = {$compid}";
            $qh = doQuery($query, 128);
            $row = mysql_fetch_row($qh);
            if (!in_array($row[0], $scheduleids)) {
                cleanSemaphore();
                return debugIsAvailable(0, 7, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids);
            }
            // set $virtual to 0 so that it is defined later but skips the additional code
            $virtual = 0;
        } else {
            # determine if image is bare metal or virtual
            $query = "SELECT OS.installtype " . "FROM image i " . "LEFT JOIN OS ON (i.OSid = OS.id) " . "WHERE i.id = {$imageid}";
            $qh = doQuery($query, 101);
            if (!($row = mysql_fetch_assoc($qh))) {
                cleanSemaphore();
                return debugIsAvailable(0, 8, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids);
            }
            # TODO might need to check for other strings for KVM, OpenStack, etc
            if (preg_match('/(vmware)/', $row['installtype'])) {
                $virtual = 1;
            } else {
                $virtual = 0;
            }
            # get list of available computers
            if (!$ignoreprivileges) {
                $resources = getUserResources(array("imageAdmin", "imageCheckOut"), array("available"), 0, 0, $userid);
                $usercomputers = implode("','", array_keys($resources["computer"]));
                $usercomputers = "'{$usercomputers}'";
            }
            $alloccompids = implode(",", $allocatedcompids);
            # get list of computers we can provision image to
            $schedules = implode(',', $scheduleids);
            #image.OSid->OS.installtype->OSinstalltype.id->provisioningOSinstalltype.provisioningid->computer.provisioningid
            $query = "SELECT DISTINCT c.id, " . "c.currentimageid, " . "c.imagerevisionid " . "FROM state s, " . "image i " . "LEFT JOIN OS o ON (o.id = i.OSid) " . "LEFT JOIN OSinstalltype oi ON (oi.name = o.installtype) " . "LEFT JOIN provisioningOSinstalltype poi ON (poi.OSinstalltypeid = oi.id) " . "LEFT JOIN computer c ON (poi.provisioningid = c.provisioningid) " . "LEFT JOIN semaphore se ON (c.id = se.computerid) " . "WHERE i.id = {$imageid} AND " . "c.scheduleid IN ({$schedules}) AND " . "c.platformid = {$platformid} AND " . "c.stateid = s.id AND " . "s.name NOT IN ({$ignorestates}) AND " . "c.RAM >= i.minram AND " . "c.procnumber >= i.minprocnumber AND " . "c.procspeed >= i.minprocspeed AND " . "c.network >= i.minnetwork AND " . "c.deleted = 0 AND " . "(c.type != 'virtualmachine' OR c.vmhostid IS NOT NULL) AND ";
            if (!$ignoreprivileges) {
                $query .= "c.id IN ({$usercomputers}) AND ";
            }
            $query .= "c.id IN ({$mappedcomputers}) AND " . "c.id NOT IN ({$alloccompids}) AND " . "(se.expires IS NULL OR se.expires < NOW()) " . "ORDER BY RAM, " . "(c.procspeed * c.procnumber), " . "network";
            $qh = doQuery($query, 129);
            while ($row = mysql_fetch_assoc($qh)) {
                array_push($computerids, $row['id']);
                if ($row['currentimageid'] == $imageid && $row['imagerevisionid'] == $requestInfo['imagerevisions'][$key]) {
                    array_push($currentids, $row['id']);
                }
            }
            # get computer ids available from block allocations
            $blockdata = getAvailableBlockComputerids($imageid, $start, $end, $allocatedcompids);
            $blockids = $blockdata['compids'];
        }
        # return 0 if no computers available
        if (empty($computerids) && empty($blockids)) {
            return debugIsAvailable(0, 21, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, array(), $virtual);
        }
        #remove computers from list that are already scheduled
        $usedComputerids = array();
        $query = "SELECT DISTINCT rs.computerid " . "FROM reservation rs, " . "request rq " . "WHERE '{$startstamp}' < (rq.end + INTERVAL 900 SECOND) AND " . "'{$endstamp}' > rq.start AND " . "rq.id != {$requestid} AND " . "rs.requestid = rq.id AND " . "rq.stateid NOT IN (1, 5, 12)";
        # deleted, failed, complete
        $qh = doQuery($query, 130);
        while ($row = mysql_fetch_row($qh)) {
            array_push($usedComputerids, $row[0]);
        }
        $computerids = array_diff($computerids, $usedComputerids);
        $currentids = array_diff($currentids, $usedComputerids);
        $blockids = array_diff($blockids, $usedComputerids);
        // if modifying a reservation and $computerids is now empty, return 0
        if ($requestid && empty($computerids)) {
            cleanSemaphore();
            return debugIsAvailable(0, 9, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, array(), $virtual);
        }
        # return 0 if no computers available
        if (empty($computerids) && empty($currentids) && empty($blockids)) {
            return debugIsAvailable(0, 19, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, array(), $virtual);
        }
        # remove computers from list that are allocated to block allocations
        if ($altRemoveBlockCheck) {
            if (editRequestBlockCheck($computerids[0], $imageid, $start, $end)) {
                cleanSemaphore();
                return debugIsAvailable(0, 10, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, array(), $virtual);
            }
        } elseif (!count($blockids)) {
            # && ! $altRemoveBlockCheck
            $usedBlockCompids = getUsedBlockComputerids($start, $end);
            $computerids = array_diff($computerids, $usedBlockCompids);
            $currentids = array_diff($currentids, $usedBlockCompids);
        }
        if ($virtual && empty($currentids) && !empty($computerids)) {
            # find computers whose hosts can handle the required RAM - we don't
            #   need to do this if there are VMs with the requested image already
            #   available because they would already fit within the host's available
            #   RAM
            if (!$vmhostcheckdone) {
                $vmhostcheckdone = 1;
                $query = "DROP TEMPORARY TABLE IF EXISTS VMhostCheck";
                doQuery($query, 101);
                $query = "CREATE TEMPORARY TABLE VMhostCheck ( " . "RAM mediumint unsigned NOT NULL, " . "allocRAM mediumint unsigned NOT NULL, " . "vmhostid smallint unsigned NOT NULL " . ") ENGINE=MEMORY";
                doQuery($query, 101);
                $query = "INSERT INTO VMhostCheck " . "SELECT c.RAM, " . "SUM(i.minram), " . "v.id " . "FROM vmhost v " . "LEFT JOIN computer c ON (v.computerid = c.id) " . "LEFT JOIN computer c2 ON (v.id = c2.vmhostid) " . "LEFT JOIN image i ON (c2.currentimageid = i.id) " . "WHERE c.stateid = 20 " . "GROUP BY v.id";
                doQuery($query, 101);
            }
            $inids = implode(',', $computerids);
            // if want overbooking, modify the last part of the WHERE clause
            $query = "SELECT c.id " . "FROM VMhostCheck v " . "LEFT JOIN computer c ON (v.vmhostid = c.vmhostid) " . "LEFT JOIN image i ON (c.currentimageid = i.id) " . "WHERE c.id IN ({$inids}) AND " . "(v.allocRAM - i.minram + {$images[$imageid]['minram']}) < v.RAM " . "ORDER BY c.RAM, " . "(c.procspeed * c.procnumber), " . "c.network";
            $qh = doQuery($query, 101);
            $newcompids = array();
            while ($row = mysql_fetch_assoc($qh)) {
                $newcompids[] = $row['id'];
            }
            $computerids = $newcompids;
        }
        # check for use of specified IP address, have to wait until here
        #   because there may be a computer already assigned the IP that
        #   can be used for this reservation
        if (!empty($ip) && $now) {
            $allcompids = array_merge($computerids, $blockids);
            if (empty($allcompids)) {
                return debugIsAvailable(0, 13, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, array(), $virtual);
            }
            $inids = implode(',', $allcompids);
            $query = "SELECT id " . "FROM computer " . "WHERE id NOT IN ({$inids}) AND " . "deleted = 0 AND " . "stateid != 1 AND " . "IPaddress = '{$ip}' AND " . "(type != 'virtualmachine' OR " . "vmhostid IS NOT NULL)";
            $qh = doQuery($query);
            if (mysql_num_rows($qh)) {
                if ($now) {
                    return debugIsAvailable(-4, 18, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, array(), $virtual);
                }
                $requestInfo['ipwarning'] = 1;
            }
            $query = "SELECT id " . "FROM computer " . "WHERE id in ({$inids}) AND " . "IPaddress = '{$ip}'";
            if ($requestid) {
                $query .= " AND id != {$compid}";
            }
            # TODO test this
            $qh = doQuery($query);
            $cnt = mysql_num_rows($qh);
            if ($cnt > 1) {
                if ($now) {
                    return debugIsAvailable(-4, 19, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, array(), $virtual);
                }
                $requestInfo['ipwarning'] = 1;
            } elseif ($cnt == 1) {
                $row = mysql_fetch_assoc($qh);
                $computerids = array($row['id']);
                $blockids = array();
            }
        }
        # remove any recently reserved computers that could have been an
        #   undetected failure
        $failedids = getPossibleRecentFailures($userid, $imageid);
        $shortened = 0;
        if (!empty($failedids)) {
            $origcomputerids = $computerids;
            $origcurrentids = $currentids;
            $origblockids = $blockids;
            if (!empty($computerids)) {
                $testids = array_diff($computerids, $failedids);
                if (!empty($testids)) {
                    $shortened = 1;
                    $computerids = $testids;
                    $currentids = array_diff($currentids, $failedids);
                }
            }
            if (!empty($blockids)) {
                $testids = array_diff($blockids, $failedids);
                if (!empty($testids)) {
                    $shortened = 1;
                    $blockids = $testids;
                }
            }
        }
        # allocate a computer
        $_imgrevid = $requestInfo['imagerevisions'][$key];
        $comparr = allocComputer($blockids, $currentids, $computerids, $startstamp, $endstamp, $nowfuture, $imageid, $_imgrevid, $holdcomps, $requestid);
        if (empty($comparr) && $shortened) {
            $comparr = allocComputer($origblockids, $origcurrentids, $origcomputerids, $startstamp, $endstamp, $nowfuture, $imageid, $_imgrevid, $holdcomps, $requestid);
        }
        if (empty($comparr)) {
            cleanSemaphore();
            return debugIsAvailable(0, 11, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, $failedids, $virtual);
        }
        $requestInfo["computers"][$key] = $comparr['compid'];
        $requestInfo["mgmtnodes"][$key] = $comparr['mgmtid'];
        $requestInfo["loaded"][$key] = $comparr['loaded'];
        $requestInfo['fromblock'][$key] = $comparr['fromblock'];
        if ($comparr['fromblock']) {
            $requestInfo['blockdata'][$key] = $blockdata[$comparr['compid']];
        }
        array_push($allocatedcompids, $comparr['compid']);
    }
    return debugIsAvailable(1, 12, $start, $end, $imagerevisionid, $computerids, $currentids, $blockids, array(), $virtual);
}
Exemplo n.º 21
0
function addMgmtnode($data)
{
    $ownerid = getUserlistID($data["owner"]);
    $data['installpath'] = mysql_escape_string($data['installpath']);
    $data['keys'] = mysql_escape_string($data['keys']);
    $data['imagelibuser'] = mysql_escape_string($data['imagelibuser']);
    if ($data['imagelibuser'] != 'NULL') {
        $data['imagelibuser'] = "******";
    }
    $data['imagelibkey'] = mysql_escape_string($data['imagelibkey']);
    if ($data['imagelibkey'] != 'NULL') {
        $data['imagelibkey'] = "'{$data['imagelibkey']}'";
    }
    if ($data['imagelibenable'] != 1) {
        $data['imagelibenable'] = 0;
    }
    if ($data['keys'] == '') {
        $data['keys'] = 'NULL';
    } else {
        $data['keys'] = "'{$data['keys']}'";
    }
    $query = "INSERT INTO managementnode " . "(hostname, " . "IPaddress, " . "ownerid, " . "stateid, " . "checkininterval, " . "installpath, " . "imagelibenable, " . "imagelibgroupid, " . "imagelibuser, " . "imagelibkey, " . "`keys`, " . "predictivemoduleid, " . "sshport) " . "VALUES ('{$data["hostname"]}', " . "'{$data["IPaddress"]}', " . "{$ownerid}, " . "{$data["stateid"]}, " . "{$data["checkininterval"]}, " . "'{$data["installpath"]}', " . "{$data["imagelibenable"]}, " . "{$data["imagelibgroupid"]}, " . "{$data["imagelibuser"]}, " . "{$data["imagelibkey"]}, " . "{$data["keys"]}, " . "{$data["premoduleid"]}, " . "{$data["sshport"]}) ";
    doQuery($query, 205);
    // get last insert id
    $qh = doQuery("SELECT LAST_INSERT_ID() FROM managementnode", 101);
    if (!($row = mysql_fetch_row($qh))) {
        abort(101);
    }
    $id = $row[0];
    // add entry in resource table
    $query = "INSERT INTO resource " . "(resourcetypeid, " . "subid) " . "VALUES (16, " . "{$id})";
    doQuery($query, 209);
    return $id;
}
Exemplo n.º 22
0
 function addResource($data)
 {
     global $user;
     $ownerid = getUserlistID($data['owner']);
     $query = "INSERT INTO schedule " . "(name, " . "ownerid) " . "VALUES ('{$data['name']}', " . "{$ownerid})";
     doQuery($query);
     $rscid = dbLastInsertID();
     if ($rscid == 0) {
         return 0;
     }
     $query = "INSERT INTO resource " . "(resourcetypeid, " . "subid) " . "VALUES (15, " . "{$rscid})";
     doQuery($query, 223);
     return $rscid;
 }