function handle_lead_request($request_id, $new_status, $approver, $user_uid, $reason, $signer)
{
    $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
    $conn = portal_conn();
    if ($new_status == "approved") {
        $response = add_member_privilege($ma_url, $signer, $user_uid, "PROJECT_LEAD");
        if (!$response) {
            error_log("User {$user_uid} already a project lead, cannot be made a project lead");
        } else {
            send_approved_mail(geni_load_user_by_member_id($user_uid), $reason, $approver);
        }
    }
    $sql = "UPDATE lead_request set " . "status = " . $conn->quote($new_status, 'text') . ", " . "reason = " . $conn->quote($reason, 'text') . ", " . "approver = " . $conn->quote($approver, 'text') . "where id = " . $conn->quote($request_id, 'text');
    $db_response = db_execute_statement($sql, "Update lead request id#:" . $request_id);
    $db_error = $db_response[RESPONSE_ARGUMENT::OUTPUT];
    if ($db_error == "") {
        print "Response successfully stored";
    } else {
        print "DB error: " . $db_error;
        error_log("DB error when updating lead request table: " . $db_error);
    }
}
Example #2
0
function get_users_projects($user)
{
    global $has_projects;
    $sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
    $member_id = $user->account_id;
    $projects = get_project_info_for_member($sa_url, $user, $member_id);
    $options = '';
    foreach ($projects as $project) {
        $project_id = $project[PA_PROJECT_TABLE_FIELDNAME::PROJECT_ID];
        if ($user->isAllowed(SA_ACTION::CREATE_SLICE, CS_CONTEXT_TYPE::PROJECT, $project_id)) {
            $options .= "<option value='" . $project_id . "'>";
            $options .= $project[PA_PROJECT_TABLE_FIELDNAME::PROJECT_NAME];
            $options .= "</option>";
            $has_projects = true;
        }
    }
    if ($has_projects) {
        $select = "<select name='project_id' form='createsliceform'>{$options}</select>";
    } else {
        $select = '<i>You are not a member of any project where you can create a slice. </i><a href="dashboard.php#projects">View projects</a>';
    }
    return $select;
}
//
?>

<?php 
require_once 'user.php';
require_once 'sr_constants.php';
require_once 'sr_client.php';
require_once "pa_client.php";
require_once "pa_constants.php";
require_once "response_format.php";
$user = geni_loadUser();
if (!isset($user) || is_null($user) || !$user->isActive()) {
    relative_redirect('home.php');
}
$ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
$sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
// Invoke geni-sync-wireless tool on given project
function sync_object($object_type, $object_name)
{
    # Should only provide error information on stderr: put stdout to syslog
    $cmd = "geni-sync-wireless {$object_type} {$object_name}";
    error_log("SYNC(cmd) " . $cmd);
    $descriptors = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
    $process = proc_open($cmd, $descriptors, $pipes);
    $std_output = stream_get_contents($pipes[1]);
    # Should be empty
    $err_output = stream_get_contents($pipes[2]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $proc_value = proc_close($process);
    $full_output = $std_output . $err_output;
// Check the selections from the handle-project-request are valid
// If so, add the approved members, resolve the requests and
// send emails (positive or negative) to the requestors.
$user = geni_loadUser();
if (!isset($user) || is_null($user) || !$user->isActive()) {
    relative_redirect('home.php');
}
// Get the sa_url for accessing request information
if (!isset($sa_url)) {
    $sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
    if (!isset($sa_url) || is_null($sa_url) || $sa_url == '') {
        error_log("Found no Slice Authority Service");
    }
}
if (!isset($ma_url)) {
    $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
}
// error_log("REQUEST = " . print_r($_REQUEST, true));
if (!array_key_exists('project_id', $_REQUEST)) {
    // Error
    error_log("do-handle-project-request called without project_id");
    relative_redirect("home.php");
}
$project_id = $_REQUEST['project_id'];
unset($_REQUEST['project_id']);
if (array_key_exists('project_name', $_REQUEST)) {
    unset($_REQUEST['project_name']);
}
$selections = $_REQUEST;
// error_log("SELECTIONS = " . print_r($selections, true));
$project_details = lookup_project($sa_url, $user, $project_id);
Example #5
0
 function fetchMember($member_id)
 {
     if ($this->account_id == $member_id) {
         return $this;
     }
     $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
     $member = ma_lookup_member_by_id($ma_url, $this, $member_id);
     $user = new GeniUser();
     $user->init_from_member($member);
     return $user;
 }
Example #6
0
    Call create_sliver() in am_client.php and get a return code back.
    $retVal is non-null if successful, null if failed
*/
$retVal = create_sliver($am_urls, $user, $slice_users, $slice_credential, $slice_urn, $omni_invocation_dir, $slice['slice_id'], $bound_rspec, $stitch_rspec);
if ($retVal and $retVal != "Invalid AM URL" and $retVal != "Missing AM URL" and $retVal != "Missing slice credential") {
    // Really we want to come here if we spawned the process OK only
    // Set up link to results page
    $invoke_id = get_invocation_id_from_dir($omni_invocation_dir);
    $link = "sliceresource.php?invocation_user="******"&invocation_id={$invoke_id}&slice_id={$slice_id}";
    // if am_id specified, append it to link
    if (isset($am_id) && $am_id) {
        $link .= "&am_id={$am_id}";
    }
    $full_link = relative_url($link);
    // Write URL to 'Recent slice events' log
    $log_url = get_first_service_of_type(SR_SERVICE_TYPE::LOGGING_SERVICE);
    $project_attributes = get_attribute_for_context(CS_CONTEXT_TYPE::PROJECT, $slice['project_id']);
    $slice_attributes = get_attribute_for_context(CS_CONTEXT_TYPE::SLICE, $slice['slice_id']);
    $log_attributes = array_merge($project_attributes, $slice_attributes);
    if ($stitch_rspec) {
        log_event($log_url, $user, "Add resource request submitted for slice " . $slice_name . " from " . "stitching RSpec.<br><a href='{$full_link}'>Click here</a> for results.", $log_attributes);
    } else {
        log_event($log_url, $user, "Add resource request submitted for slice " . $slice_name . " at " . implode(", ", $am_names) . ".<br><a href='{$full_link}'>Click here</a> for results.", $log_attributes);
    }
    // Do redirection
    create_sliver_success($link, $full_link);
} else {
    $msg = "Failed to start an <tt>omni</tt> process.";
    if ($retVal == "Invalid AM URL" or $retVal == "Missing AM URL" or $retVal == "Missing slice credential") {
        $msg = $msg . " {$retVal}";
    }
Example #7
0
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Work.
//
// THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------
require_once 'util.php';
require_once 'cs_constants.php';
require_once 'cs_client.php';
require_once 'sr_constants.php';
require_once 'sr_client.php';
require_once 'user.php';
error_log("DB TEST\n");
// Get URL of Credential Store
$sr_url = get_sr_url();
$cs_url = get_first_service_of_type(SR_SERVICE_TYPE::CREDENTIAL_STORE);
$user = geni_loadUser();
$signer = null;
$principal_id = '3';
$result = create_assertion($cs_url, $user, $signer, $principal_id, CS_ATTRIBUTE_TYPE::ADMIN, CS_CONTEXT_TYPE::RESOURCE, null);
relative_redirect('debug');
Example #8
0
require_once "sr_constants.php";
require_once "pa_client.php";
require_once "pa_constants.php";
require_once 'rq_client.php';
require_once "sa_client.php";
require_once "cs_client.php";
require_once "proj_slice_member.php";
require_once "services.php";
require_once "user-preferences.php";
$user = geni_loadUser();
if (!isset($user) || is_null($user) || !$user->isActive()) {
    $msg = "Unable to load user record.";
    relative_redirect('error-text.php?error=' . urlencode($msg));
}
if (!$user->portalIsAuthorized()) {
    $km_url = get_first_service_of_type(SR_SERVICE_TYPE::KEY_MANAGER);
    $params['redirect'] = selfURL();
    $query = http_build_query($params);
    $km_url = $km_url . "?" . $query;
    print "<h2>Portal authorization</h2>";
    print "<p>";
    print "The GENI Portal is not authorized by you as a client tool. If you would like";
    print " the GENI Portal to help you manage your projects and slices, you can";
    print " <a href=\"{$km_url}\">authorize the portal</a> to do so.";
    print "</p>";
    return 0;
}
show_header('GENI Portal: Home', true, true);
include "tool-showmessage.php";
$tab_names_to_div_ids = array("Slices" => "#slices", "Projects" => "#projects", "Logs" => "#logs", "Map" => "#map");
$default_slice_tab = $tab_names_to_div_ids[get_preference($user->urn(), "homepage_tab")];
Example #9
0
function get_user_project_info($user_id, $name, $signer)
{
    $sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
    $projects = get_projects_for_member($sa_url, $signer, $user_id, true);
    $project_info = lookup_project_details($sa_url, $signer, $projects);
    $project_data = "<b style='text-decoration: underline;'>{$name}'s projects</b><br>";
    foreach ($project_info as $project_id => $project_details) {
        if ($project_details['expired'] != 1) {
            $project_data .= "<b>Project name: </b>" . $project_details[PA_PROJECT_TABLE_FIELDNAME::PROJECT_NAME] . "<br>";
            $project_data .= $project_details[PA_PROJECT_TABLE_FIELDNAME::LEAD_ID] == $user_id ? "<b>{$name} is lead on this project</b><br>" : "";
            $project_data .= "<button onclick='remove_from_project(\"{$user_id}\", \"{$project_id}\");'>Remove</button>";
            $project_data .= "<hr style='height: 1px; background-color: #5F584E; margin: 3px'>";
        }
    }
    if (count($project_info) == 0) {
        $project_data .= "<i>user has no projects</i>";
    }
    return $project_data;
}
Example #10
0
function get_jfed_strs($user)
{
    global $portal_jquery_url;
    global $portal_jqueryui_css_url;
    global $portal_jqueryui_js_url;
    $jfed_button_start = null;
    $jfed_script_text = '';
    $jfed_button_part2 = '';
    $certkey = '';
    $browser = getBrowser();
    if (strpos(strtolower($browser["name"]), "chrom") !== false and strpos(strtolower($browser["platform"]), "mac") === 0) {
        //error_log("User browser: " . $browser["name"] . " version " . $browser["version"] . " on " . $browser["platform"]);
        // While interesting, this message appears every time a Chrome on Mac user displays this page. Too much.
        //error_log("User running Chrome on Mac. Can't launch jFed. User should try Safari or Firefox.");
        $jfed_button_start = "<button type='button' onclick='alert(\"jFed cannot run in Chrome on a Mac. Try Safari or Firefox.\")'";
        return array($jfed_script_text, $jfed_button_start, '');
    }
    if (!isset($user)) {
        $user = geni_loadUser();
    }
    if (!isset($ma_url)) {
        $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
        if (!isset($ma_url) || is_null($ma_url) || $ma_url == '') {
            error_log("Found no MA in SR!'");
            return array('', null);
        }
    }
    // Code to set up jfed button
    $certresult = ma_lookup_certificate($ma_url, $user, $user->account_id);
    $expiration_key = 'expiration';
    $has_certificate = False;
    $has_key = False;
    $expired = False;
    $expiration = NULL;
    if (!is_null($certresult)) {
        $has_certificate = True;
        $has_key = array_key_exists(MA_ARGUMENT::PRIVATE_KEY, $certresult);
        if (array_key_exists($expiration_key, $certresult)) {
            $expiration = $certresult[$expiration_key];
            $now = new DateTime('now', new DateTimeZone("UTC"));
            $expired = $expiration < $now;
        }
    }
    if (!$has_certificate or $expired) {
        $jfed_button_start = "<button type='button' onclick='alert(\"Generate an SSL (Omni) key pair to use jFed.\")'";
        $jfed_button_part2 = '';
    } else {
        // Print the script tags needed
        $params = '';
        if ($has_key) {
            $certstring = $certresult[MA_ARGUMENT::PRIVATE_KEY] . "\n" . $certresult[MA_ARGUMENT::CERTIFICATE];
            $certkey = base64_encode($certstring);
            //      $params = ", params: {'login-certificate-string' : '" . base64_encode($certstring) . "' }";
        }
        $jfed_script_text = "\n        <script>\n        var config = {\n            java8_jnlp: 'http://jfed.iminds.be/jfed-geni-java8.jnlp',\n            java7_jnlp: 'http://jfed.iminds.be/jfed-geni-java7.jnlp'\n        };\n        var certkey = '{$certkey}';\n        //var slice_urn = 'urn:publicid:IDN+ch.geni.net:CHtest+slice+vm1';\n        var slice_urn = ''; // over-ridden in the onclick of the jFed button with the specific slice URN. launchjFed() uses this global. Tom says Gross!\n        </script>\n        <script src=\"//java.com/js/dtjava.js\"></script>\n        <script src='https://authority.ilabt.iminds.be/js/jfed_webstart_geni.js'></script>\n<div id='java7Dialog' title=\"Old Java version detected\" style=\"display: none\">\n<p>The latest version of jFed is only compatible with Java 8 or higher. We detected that you are using an older version.</p>\n<p>Please upgrade to Java 8 to get access to the newest version of jFed. Otherwise, you can use jFed 5.3.2, which is Java 7-compatible.</p>\n</div>\n\n<div id='noJavaDialog' title=\"No Java detected\" style=\"display: none\">\n<p>jFed requires Java to run. We however couldn't detect a Java installation in your browser.</p>\n<p>Please install the latest version of Java to continue.</p>\n</div>\n";
        // Brecht has id of 'start'
        $jfed_button_start = "<button id='jfed' type='button' onclick='";
        //launchjFed()'";
        $jfed_button_part2 = " launchjFed()'";
    }
    return array($jfed_script_text, $jfed_button_start, $jfed_button_part2);
}
Example #11
0
function add_project_slice_info($geni_user, &$projects, &$slices)
{
    $projects = array();
    $slices = array();
    $sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
    $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
    $retVal = get_project_slice_member_info($sa_url, $ma_url, $geni_user, True);
    $project_objects = $retVal[0];
    $slice_objects = $retVal[1];
    $member_objects = $retVal[2];
    $project_slice_map = $retVal[3];
    $project_activeslice_map = $retVal[4];
    foreach ($project_slice_map as $project_id => $proj_slices) {
        $proj = $project_objects[$project_id];
        $expired = $proj[PA_PROJECT_TABLE_FIELDNAME::EXPIRED];
        if ($expired == 't') {
            continue;
        }
        $pval = "{$project_id}";
        $pval .= "|" . $proj['project_name'];
        $projects[] = $pval;
        /* error_log("project $project_id: " . print_r($project_objects, true)); */
        foreach ($proj_slices as $slice_id) {
            //error_log("OpenID found slice $slice_id in project $project_id");
            $slice = $slice_objects[$slice_id];
            $expired = $slice[SA_SLICE_TABLE_FIELDNAME::EXPIRED];
            if ($expired == 't') {
                continue;
            }
            $sval = "{$slice_id}|{$project_id}";
            $sval .= "|" . $slice['slice_name'];
            $slices[] = $sval;
        }
    }
}
Example #12
0
function addToGroup($project_id, $group_name, $member_id, $user)
{
    if (!isset($project_id) || $project_id == "-1" || !uuid_is_valid($project_id)) {
        error_log("irods addToGroup: not a valid project ID. Nothing to do. {$project_id}");
        return -1;
    }
    if (!isset($group_name) || is_null($group_name) || $group_name === '') {
        error_log("irods addToGroup: not a valid group name. Nothing to do. {$project_id}, {$group_name}");
        return -1;
    }
    if (!isset($member_id) || $member_id == "-1" || !uuid_is_valid($member_id)) {
        error_log("irods addToGroup: not a valid member ID. Nothing to do. {$member_id}");
        return -1;
    }
    global $disable_irods;
    if (isset($disable_irods)) {
        error_log("irods addToGroup: disable_irods was set. Doing nothing.");
        return -1;
    }
    // must get member username
    $member = geni_load_user_by_member_id($member_id);
    // Bail early if the local attribute says the user does not yet have an account
    if (!isset($member->ma_member->irods_username)) {
        error_log("iRODS addToGroup local attribute says member {$member_id} does not yet have an iRODS account. Cannot add to group {$group_name}");
        return -1;
    }
    $username = base_username($member);
    error_log("iRODS addToGroup {$group_name} member {$member_id} with username {$username}");
    global $irods_url;
    global $default_zone;
    global $portal_irods_user;
    global $portal_irods_pw;
    global $irods_cert;
    $irods_info = array();
    $irods_info[IRODS_USER_NAME] = $username;
    $irods_info[IRODS_GROUP] = $group_name;
    $irods_info[IRODS_ZONE] = $default_zone;
    // Note: in PHP 5.4, use JSON_UNESCAPED_SLASHES.
    //   we have PHP 5.3, so we have to remove those manually.
    $irods_json = json_encode($irods_info);
    $irods_json = str_replace('\\/', '/', $irods_json);
    //  error_log("Trying to add member to iRODS group with values: " . $irods_json);
    ///* Sign the data with the portal certificate (Is that correct?) */
    //$irods_signed = smime_sign_message($irods_json, $portal_cert, $portal_key);
    ///* Encrypt the signed data for the iRODS SSL certificate */
    //$irods_blob = smime_encrypt($irods_signed, $irods_cert);
    $added = -1;
    // Was the user added to the group? -1=Error, 0=Success, 1=Member already in group
    try {
        $addstruct = doRESTCall($irods_url . IRODS_PUT_USER_GROUP_URI . IRODS_SEND_JSON, $portal_irods_user, $portal_irods_pw, "PUT", $irods_json, "application/json", $irods_cert);
        // look for (\r or \n or \r\n){2} and move past that
        preg_match("/(\r|\n|\r\n){2}([^\r\n].+)\$/", $addstruct, $m);
        if (!array_key_exists(2, $m)) {
            error_log("iRODS addToGroup Malformed PUT result to iRODS - error? Got: " . $addstruct);
            throw new Exception("Failed to add member to iRODS group - server error: " . $addstruct);
        }
        //    error_log("PUT result content: " . $m[2]);
        $addjson = json_decode($m[2], true);
        //    error_log("add user to group result: " . print_r($addjson, true));
        if (is_array($addjson)) {
            $status = null;
            $msg = null;
            $groupCmdStatus = null;
            if (array_key_exists("status", $addjson)) {
                $status = $addjson["status"];
                // Return 0 if added the user, 1 if user already in the group, -1 on error
                if ($status == IRODS_STATUS_ERROR) {
                    $added = -1;
                } elseif ($status == IRODS_STATUS_SUCCESS) {
                    $added = 0;
                }
            }
            if (array_key_exists("message", $addjson)) {
                $msg = $addjson["message"];
            }
            if (array_key_exists(IRODS_USER_GROUP_COMMAND_STATUS, $addjson)) {
                $groupCmdStatus = $addjson[IRODS_USER_GROUP_COMMAND_STATUS];
                if ($groupCmdStatus == IRODS_STATUS_DUPLICATE_USER) {
                    $added = 1;
                    error_log("iRODS user {$username} already in group {$group_name}");
                } elseif ($groupCmdStatus != IRODS_STATUS_SUCCESS) {
                    if ($groupCmdStatus === IRODS_STATUS_BAD_USER) {
                        error_log("iRODS: user {$username} has no iRODS account yet. Cannot add to group {$group_name}. ({$groupCmdStatus}: '{$msg}')");
                        // FIXME: Email someone?
                    } elseif ($groupCmdStatus === IRODS_STATUS_BAD_GROUP) {
                        // If it is INVALID_GROUP then we still need to do createGroup. I don't think that should happen. But in case...
                        error_log("iRODS: group {$group_name} doesn't exist yet, so cannot add user {$username}. Try to create the group... ({$groupCmdStatus}: '{$msg}')");
                        if (!isset($sa_url)) {
                            $sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
                            if (!isset($sa_url) || is_null($sa_url) || $sa_url == '') {
                                error_log("iRODS Found no SA in SR!'");
                            }
                        }
                        $project = lookup_project($sa_url, $user, $project_id);
                        $project_name = $project[PA_PROJECT_TABLE_FIELDNAME::PROJECT_NAME];
                        $groupCreated = irods_create_group($project_id, $project_name, $user);
                        if ($groupCreated != -1) {
                            $added = 0;
                        }
                    } else {
                        error_log("iRODS failed to add user {$username} to group {$group_name}: {$groupCmdStatus}: '{$msg}'");
                    }
                }
            } elseif ($added !== 0) {
                error_log("iRODS failed to add user {$username} to group {$group_name}: '{$msg}'");
            }
        } else {
            $added = -1;
            error_log("iRODS: malformed return from addUserToGroup: " . print_r($addjson, true));
        }
    } catch (Exception $e) {
        error_log("Error doing iRODS put to add member to group: " . $e->getMessage());
        $added = -1;
    }
    // Return 0 if added the user, 1 if user already in the group, -1 on error
    return $added;
}
Example #13
0
// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------
require_once "user.php";
require_once "header.php";
require_once "am_client.php";
require_once "ma_client.php";
require_once "sr_client.php";
require_once 'util.php';
$user = geni_loadUser();
if (!isset($user) || is_null($user) || !$user->isActive()) {
    relative_redirect('home.php');
}
$ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
$sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
$wimax_url = get_first_service_of_type(SR_SERVICE_TYPE::WIMAX_SITE);
// error_log("WIMAX_URL " . print_r($wimax_url, true));
show_header('GENI Portal: Wireless Account Setup');
include 'tool-breadcrumbs.php';
include "tool-showmessage.php";
if ($wimax_url == NULL) {
    echo "This Portal is not configured to enable or manage wireless-enabled projects.<br>";
    echo "See system administrator to enable management of wireless-enabled projects on this Portal.<br>";
    echo "<button onClick=\"history.back(-1)\">Back</button>\n";
    return;
}
?>

<script>

function set_error_text(responseTxt, project_id)
Example #14
0
function setup_jacks_slice_context()
{
    global $user;
    global $slice;
    global $slice_id;
    global $slice_name;
    global $ma_url;
    global $sa_url;
    global $all_ams;
    global $slice_ams;
    global $slice_urn;
    global $slice_expiration;
    // Set globals for variables used in slice jacks page later
    global $owner_email;
    global $slice_date_expiration;
    global $member_names;
    global $slice_creation;
    global $slice_desc;
    global $slice_owner_name;
    global $members;
    unset($slice);
    include "tool-lookupids.php";
    if (!isset($sa_url)) {
        $sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
    }
    if (!isset($ma_url)) {
        $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
    }
    if (isset($slice)) {
        $slice_name = $slice[SA_ARGUMENT::SLICE_NAME];
        //  error_log("SLICE  = " . print_r($slice, true));
        $slice_desc = $slice[SA_ARGUMENT::SLICE_DESCRIPTION];
        $slice_creation_db = $slice[SA_ARGUMENT::CREATION];
        $slice_creation = dateUIFormat($slice_creation_db);
        $slice_expiration_db = $slice[SA_ARGUMENT::EXPIRATION];
        $slice_expiration = dateUIFormat($slice_expiration_db);
        $slice_date_expiration = dateOnlyUIFormat($slice_expiration_db);
        $slice_urn = $slice[SA_ARGUMENT::SLICE_URN];
        $slice_owner_id = $slice[SA_ARGUMENT::OWNER_ID];
        $owner = $user->fetchMember($slice_owner_id);
        $slice_owner_name = $owner->prettyName();
        $owner_email = $owner->email();
        $project_name = $project[PA_PROJECT_TABLE_FIELDNAME::PROJECT_NAME];
        //error_log("slice project_name result: $project_name\n");
        // Fill in members of slice member table
        $members = get_slice_members($sa_url, $user, $slice_id);
        $member_names = lookup_member_names_for_rows($ma_url, $user, $members, SA_SLICE_MEMBER_TABLE_FIELDNAME::MEMBER_ID);
        //find only ams that slice has resources on
        $slivers = lookup_sliver_info_by_slice($sa_url, $user, $slice_urn);
        //find aggregates to be able to return just am_id
        $all_aggs = get_services_of_type(SR_SERVICE_TYPE::AGGREGATE_MANAGER);
        $aggs_with_resources = array();
        //do the comparison and find ams
        foreach ($slivers as $sliver) {
            foreach ($all_aggs as $agg) {
                if ($sliver[SA_SLIVER_INFO_TABLE_FIELDNAME::SLIVER_INFO_AGGREGATE_URN] == $agg[SR_TABLE_FIELDNAME::SERVICE_URN]) {
                    $aggs_with_resources[] = $agg[SR_TABLE_FIELDNAME::SERVICE_ID];
                    break;
                }
            }
        }
        //return unique ids
        $slice_ams = array_unique($aggs_with_resources, SORT_REGULAR);
        // Now restore the array to a numerically ordered array because
        // array_unique preserves keys, so it could turn into, in effect, a
        // dictionary.
        $slice_ams = array_values($slice_ams);
    } else {
        print "Unable to load slice<br/>\n";
        $_SESSION['lasterror'] = "Unable to load slice";
        relative_redirect("home.php");
        exit;
    }
    if (!isset($all_ams)) {
        $am_list = get_services_of_type(SR_SERVICE_TYPE::AGGREGATE_MANAGER);
        $all_ams = array();
        foreach ($am_list as $am) {
            $single_am = array();
            $service_id = $am[SR_TABLE_FIELDNAME::SERVICE_ID];
            $single_am['name'] = $am[SR_TABLE_FIELDNAME::SERVICE_NAME];
            $single_am['url'] = $am[SR_TABLE_FIELDNAME::SERVICE_URL];
            $single_am['urn'] = $am[SR_TABLE_FIELDNAME::SERVICE_URN];
            $all_ams[$service_id] = $single_am;
        }
    }
}
Example #15
0
function invoke_omni_function($am_urls, $user, $args, $slice_users = array(), $bound_rspec = 0, $stitch_rspec = 0, $fork = false, $omni_invocation_dir = NULL, $api_version = "2")
{
    global $portal_gcf_dir;
    /* $file_manager only holds on to non-critical files (i.e., those
       that can be deleted regardless of whether the call was successful
       or not). */
    $file_manager = new FileManager();
    //  error_log("INVOKE : " . print_r($am_urls, true));
    // If we get a single URL, make it an array (handle the general case)
    if ($am_urls && !is_array($am_urls)) {
        $am_urls = array($am_urls);
    }
    /* Does each given URL handle speaks-for?
            If one or more AM URLs are given, check the SR for whether SF is enabled.
            If no AM URL is given but it's for stitching, just assume for now
                that all AMs handle SpeaksFor and see what happens.
      */
    if ($am_urls) {
        $handles_speaks_for = True;
        foreach ($am_urls as $am_url) {
            $am_handles_speaks_for = lookup_attribute($am_url, SERVICE_ATTRIBUTE_SPEAKS_FOR) == 't';
            if (!$am_handles_speaks_for) {
                $handles_speaks_for = False;
                break;
            }
        }
    } else {
        $handles_speaks_for = True;
    }
    /*
     If an aggregate doesn't handle speaks-for, 
     we use the inside cert and key of the user
     If an aggregate DOES handle speaks-for and the
     user has a speaks-for credential, 
     portal's cert and key and pass along the geni_speaking_for option
    */
    $speaks_for_invocation = false;
    $cert = $user->insideCertificate();
    $private_key = $user->insidePrivateKey();
    $speaks_for_cred = $user->speaksForCred();
    if ($handles_speaks_for and $speaks_for_cred) {
        $speaks_for_invocation = true;
        $cert = $user->certificate();
        $private_key = $user->privateKey();
    }
    $username = $user->username;
    $urn = $user->urn();
    // Get the authority from the user's URN
    parse_urn($urn, $authority, $type, $name);
    $aggregates = "aggregates=";
    $first = True;
    // get AMs if non-stitchable
    if (!$stitch_rspec) {
        if (is_array($am_urls)) {
            if (count($am_urls) == 0) {
                error_log("am_client Got non stitching RSpec and 0 AM URLs");
                // Careful: Are all RSpecs that stitcher can handle marked as stitch_rspecs properly?
                // return("Invalid AM URL");
            }
            foreach ($am_urls as $single) {
                if (!isset($single) || is_null($single) || $single == '') {
                    error_log("am_client cannot invoke Omni with invalid AM URL");
                    return "Invalid AM URL";
                }
                if ($first) {
                    $first = False;
                } else {
                    $aggregates = $aggregates . ", ";
                }
                $aggregates = $aggregates . $single;
            }
            $aggregates = $aggregates . "\n";
        } elseif (!isset($am_url) || is_null($am_url) || $am_url == '') {
            error_log("am_client cannot invoke Omni without an AM URL");
            return "Missing AM URL";
        }
    }
    /* Create a directory to store all temp files, including logs and error
          messages *if one doesn't exist already*. Let the prefix be the username.
          An "omni invocation ID" is created.
       
          Returns something like: /tmp/omni-invoke-myuser-RKvQ1Z
       */
    if (is_null($omni_invocation_dir)) {
        $omni_invocation_dir = createTempDir($username);
    }
    /* Write key and credential files */
    $tmp_version_cache = "{$omni_invocation_dir}/omniVersionCache";
    $tmp_agg_cache = "{$omni_invocation_dir}/omniAggCache";
    $file_manager->add($tmp_version_cache);
    $file_manager->add($tmp_agg_cache);
    $cert_file = writeDataToTempDir($omni_invocation_dir, $cert, OMNI_INVOCATION_FILE::CERTIFICATE_FILE);
    $file_manager->add($cert_file);
    $key_file = writeDataToTempDir($omni_invocation_dir, $private_key, OMNI_INVOCATION_FILE::PRIVATE_KEY_FILE);
    $file_manager->add($key_file);
    $slice_users = $slice_users + array($user);
    $username_array = array();
    $all_ssh_key_files = array();
    $ssh_key_files_by_user = array();
    foreach ($slice_users as $slice_user) {
        $slice_urn = $slice_user->urn();
        $ssh_key_files = write_ssh_keys($slice_user, $user, $omni_invocation_dir);
        // Skip from omni_config any user with no public SSH keys
        if (count($ssh_key_files) == 0) {
            continue;
        }
        $all_ssh_key_files = array_merge($all_ssh_key_files, $ssh_key_files);
        $ssh_key_files_by_user[$slice_urn] = $ssh_key_files;
        $username_array[] = $slice_user->username;
    }
    /* Create OMNI config file */
    if (!isset($sa_url)) {
        $sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY);
    }
    if (!isset($ma_url)) {
        $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY);
    }
    $omni_config = "[omni]\n" . "default_cf = my_chapi\n" . "users = " . implode(", ", $username_array) . "\n";
    // As of omni 2.7, by default omni queries the CH to get slice members
    // We pass those in explicitly and don't want the extra query
    $omni_config .= "useslicemembers = False\n";
    // specify AM for non-stitchable RSpecs
    if (!$stitch_rspec) {
        if (is_array($am_urls)) {
            $omni_config = $omni_config . $aggregates . "\n";
        }
    }
    # Create the aggregate nickname cache file
    if (!write_agg_nick_cache($tmp_agg_cache)) {
        error_log("Failed to write the aggregate nickname cache.");
        // Now what? Continue?
    }
    // FIXME: Get the /CH URL from a portal/www/portal/settings.php entry?
    $omni_config = $omni_config . "[my_chapi]\n" . "type=chapi\n" . "authority={$authority}\n" . "ch=https://{$authority}:8444/CH\n" . "sa={$sa_url}\n" . "ma={$ma_url}\n" . "cert={$cert_file}\n" . "key={$key_file}\n";
    foreach ($slice_users as $slice_user) {
        $slice_username = $slice_user->username;
        $slice_urn = $slice_user->urn();
        if (!array_key_exists($slice_urn, $ssh_key_files_by_user)) {
            // This user had no SSH keys
            continue;
        }
        $all_key_files = implode(',', $ssh_key_files_by_user[$slice_urn]);
        $omni_config = $omni_config . "[{$slice_username}]\n" . "urn={$slice_urn}\n" . "keys={$all_key_files}\n";
    }
    foreach ($all_ssh_key_files as $ssh_key_file) {
        $file_manager->add($ssh_key_file);
    }
    $omni_file = writeDataToTempDir($omni_invocation_dir, $omni_config, OMNI_INVOCATION_FILE::OMNI_CONFIGURATION_FILE);
    $file_manager->add($omni_file);
    /* Call OMNI */
    $omni_log_file = "{$omni_invocation_dir}/" . OMNI_INVOCATION_FILE::DEBUG_LOG_FILE;
    $omni_stderr_file = "{$omni_invocation_dir}/" . OMNI_INVOCATION_FILE::ERROR_LOG_FILE;
    $omni_stdout_file = "{$omni_invocation_dir}/" . OMNI_INVOCATION_FILE::CALL_RESULTS_FILE;
    $omni_command_file = "{$omni_invocation_dir}/" . OMNI_INVOCATION_FILE::COMMAND_FILE;
    $omni_pid_file = "{$omni_invocation_dir}/" . OMNI_INVOCATION_FILE::PID_FILE;
    /*    $cmd_array = array($portal_gcf_dir . '/src/omni.py', */
    $cmd_array = array($portal_gcf_dir . '/src/stitcher_php.py', '-c', $omni_file, '-l', write_logger_configuration_file($omni_invocation_dir), '--logoutput', $omni_log_file, '--timeout', '45', '--api-version', $api_version, "--GetVersionCacheName", $tmp_version_cache, "--ForceUseAggNickCache", "--AggNickCacheName", $tmp_agg_cache);
    $descriptor_spec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", $omni_stderr_file, "a"));
    /* stitcher.py: specify fileDir */
    $cmd_array[] = '--fileDir';
    $cmd_array[] = $omni_invocation_dir;
    // specify AM for non-stitchable RSpecs
    if (!$stitch_rspec) {
        foreach ($am_urls as $am_url) {
            $cmd_array[] = '-a';
            $cmd_array[] = $am_url;
        }
    }
    if ($speaks_for_invocation) {
        $cmd_array[] = "--speaksfor=" . $user->urn;
        $speaks_for_cred_filename = writeDataToTempDir($omni_invocation_dir, $speaks_for_cred->credential(), OMNI_INVOCATION_FILE::SPEAKSFOR_CREDENTIAL_FILE);
        $file_manager->add($speaks_for_cred_filename);
        $cmd_array[] = "--cred=" . $speaks_for_cred_filename;
    }
    for ($i = 0; $i < count($args); $i++) {
        $cmd_array[] = $args[$i];
    }
    $command = implode(" ", $cmd_array);
    // save command that was run
    $cmd_file = fopen($omni_command_file, "a");
    fwrite($cmd_file, $command);
    fclose($cmd_file);
    /* forked omni call */
    if ($fork) {
        // define how to handle streams
        $stdout_redirect = " > " . $omni_stdout_file;
        $stderr_redirect = " 2> " . $omni_stderr_file;
        $stdin_redirect = " < /dev/null";
        // set up call via nohup and grab its PID
        $fork_call = 'nohup ' . $command . $stdout_redirect . $stderr_redirect . $stdin_redirect . ' & echo $!';
        error_log("am_client invoke_omni_function COMMAND = " . $fork_call);
        exec($fork_call, $op);
        // assuming success, $op will be a non-empty array
        if ($op) {
            // nohup should return an array with one line containing the PID
            $pid = $op[0];
            // write PID to a file
            $pid_file = fopen($omni_pid_file, "a");
            fwrite($pid_file, $pid);
            fclose($pid_file);
            // FIXME: Should we wait around to do 'ps -p <pid>' to make sure
            // process didn't quickly die?
            return $pid;
        } else {
            return NULL;
        }
    } else {
        error_log("am_client invoke_omni_function COMMAND = " . $command);
        $handle = proc_open($command, $descriptor_spec, $pipes);
        stream_set_blocking($pipes[1], 0);
        // 1 MB
        $bufsiz = 1024 * 1024;
        $output = '';
        $outchunk = null;
        //time to terminate omni process
        $now = time();
        $kill_time = $now + AM_CLIENT_OMNI_KILL_TIME;
        while ($outchunk !== FALSE && !feof($pipes[1]) && $now < $kill_time) {
            $outchunk = fread($pipes[1], $bufsiz);
            if ($outchunk != null && $outchunk !== FALSE) {
                $output = $output . $outchunk;
                $usleep = 0;
            } else {
                // 0.25 seconds
                $usleep = 250000;
            }
            // If we got data, don't sleep, see if there's more ($usleep = 0)
            // If no data, sleep for a little while then check again.
            usleep($usleep);
            $now = time();
        }
        // Catch any final output after timeout
        $outchunk = fread($pipes[1], $bufsiz);
        if ($outchunk != null && $outchunk !== FALSE) {
            $output = $output . $outchunk;
        }
        //fclose($pipes[0]);
        //fclose($pipes[1]);
        //proc_close($handle);
        $status = proc_get_status($handle);
        if (!$status['running']) {
            fclose($pipes[0]);
            fclose($pipes[1]);
            $return_value = $status['exitcode'];
            proc_close($handle);
        } else {
            // Still running, terminate it.
            // See https://bugs.php.net/bug.php?id=39992, for problems
            // terminating child processes and a workaround involving posix_setpgid()
            fclose($pipes[0]);
            fclose($pipes[1]);
            $term_result = proc_terminate($handle);
            // Omni is taking too long to respond so
            // assign Timeout error message to output and this message may show up in UI
            //msg constant defined above
            $output = AM_CLIENT_TIMED_OUT_MSG;
        }
        /*
        unlink($cert_file);
        unlink($key_file);
        unlink($omni_file);
        unlink($tmp_version_cache);
        unlink($tmp_agg_cache);
        foreach ($all_ssh_key_files as $tmpfile) {
          unlink($tmpfile);
        }
        if ($speaks_for_invocation) {
          unlink($speaks_for_cred_filename);
        }
        */
        // Good for debugging but verbose
        //     error_log("am_client output " .  print_r($output, True));
        // FIXME: Write stdout's contents to omni_stdout_file for now to capture
        //  stitcher output. This will be changed when assigning descriptor_spec
        //  to send to a file rather than a pipe.
        $stdout_file = fopen($omni_stdout_file, "a");
        fwrite($stdout_file, $output);
        fclose($stdout_file);
        $output2 = json_decode($output, True);
        if (is_null($output2)) {
            // this is probably a traceback from python
            // return it as a string
            // but see if omni-stderr exists, and pass back its information
            // in addition to output to get a better traceback
            $error_file = fopen($omni_stderr_file, "r");
            // only try to read if fopen was successful and if the error file
            // contains something (i.e. more than 0 bytes)
            if ($error_file && filesize($omni_stderr_file)) {
                $error_file_contents = fread($error_file, filesize($omni_stderr_file));
                if ($error_file_contents) {
                    $substr = $error_file_contents;
                    if (strlen($substr) > 120) {
                        // Pull out just the interesting bits: match on either OmniError or StitchingError
                        $substr = trim(preg_replace("/Traceback(.*)OmniError\\:/s", "", $substr, -1));
                        $substr = trim(preg_replace("/Traceback(.*)StitchingError\\:/s", "", $substr, -1));
                        $substr = "..." . $substr;
                    }
                    error_log("am_client invoke_omni_function: " . "stderr file non-empty: '" . $substr . "'. Check " . $omni_stderr_file . " for more information");
                    // uncomment the next line to append stderr contents to what
                    // users will see. But this has been fixed elsewhere under ticket 1086.
                    //$output .= $error_file_contents;
                }
                fclose($error_file);
            }
            error_log("am_client invoke_omni_function:" . "JSON result is not parseable: \"{$output}\"");
            return $output;
        }
        /* Clean out $file_manager's directory 
              This does NOT include log/error files or any additional files that
              stitching requests may make.
           */
        $file_manager->destruct();
        /* Delete the remaining temp files only if the decoded output is an array
             and its length is 2 and the second value (index 1) is boolean true
             (not null or empty string).
           */
        if (is_array($output2) && count($output2) == 2 && $output2[1]) {
            clean_directory($omni_invocation_dir);
            rmdir($omni_invocation_dir);
            //unlink($omni_log_file);
            //unlink($omni_stderr_file);
        }
        //error_log("Returning output2 : " . print_r($output2, True));
        return $output2;
    }
}