private void reenterLabClient()
        {
            if (Session["UserID"] == null)
            {
                Response.Redirect("login.aspx");
            }
            BrokerDB brokerDB = new BrokerDB();
            StringBuilder message = new StringBuilder("Message: clientID = ");
            int[] labIds = new int[1];
            message.Append(btnReenter.CommandArgument + " ");
            iLabParser parser = new iLabParser();
            long expid = Convert.ToInt64(btnReenter.CommandArgument);
            LabClient client = AdministrativeAPI.GetLabClient(Convert.ToInt32(Session["ClientID"]));
            if (client.clientID > 0)
            {
                if (client.clientType == LabClient.INTERACTIVE_HTML_REDIRECT)
                {
                    iLabProperties properties = new iLabProperties();
                    properties.Add("sb",ProcessAgentDB.ServiceAgent);
                    long[] coupIDs = InternalDataDB.RetrieveExperimentCouponIDs(expid);
                    Coupon coupon = brokerDB.GetIssuedCoupon(coupIDs[0]);
                    if(coupon != null)
                        properties.Add("op", coupon);
                    // construct the redirect query
                    ProcessAgentInfo lsInfo = getLabServer(client.clientID,effectiveGroupID);
                    if(lsInfo != null)
                        properties.Add("ls",lsInfo);

                    StringBuilder url = new StringBuilder(client.loaderScript.Trim());
                    // Add the return url to the redirect
                    if (url.ToString().IndexOf("?") == -1)
                        url.Append('?');
                    else
                        url.Append('&');
                    url.Append("sb_url=");
                    url.Append(Utilities.ExportUrlPath(Request.Url));
                    string targetURL = parser.Parse(url,properties,true);
                    // Now open the lab within the current Window/frame
                    Response.Redirect(targetURL, true);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Should handle all requests to launch a lab, produces a releative URL or error message 
        /// and a status code which are returned in the IntTag. This does not make use of the 'Context'.
        /// This should only be called after the original request has been authorized since the
        /// user is assummed to have been authenticated and authorized.
        /// </summary>
        /// <param name="opCoupon">An initial operationCoupon</param>
        /// <param name="clientID"></param>
        /// <param name="labServerID"></param>
        /// <param name="groupID">specified by SCO, may not be the users group</param>
        /// <param name="userID"></param>
        /// <returns>A negative value for errrors or a bitmapped value indicating what should be done with the result.tag</returns>
        public IntTag ProcessLaunchClientRequest(Coupon opCoupon, int clientID, int labServerID,
            int groupID, int userID, int userTZ //, string authorityUrl, long duration, int autoStart
            )
        {
            int effectiveGroupID = -1;
            int userGroupID = -1;
            string groupName = null;
            string effectiveGroupName = null;
            string userName = null;
            DateTime startExecution =DateTime.MinValue;
            long duration = -1L;

            ProcessAgentInfo labServer = null;
            StringBuilder buf = new StringBuilder();
            LabClient client = AdministrativeAPI.GetLabClient(clientID);
            iLabParser parser = new iLabParser();
            IntTag result = new IntTag(-1, "Access Denied");

            if (client == null)
            {
               result.tag = "LabClient was not found";
               return result;
            }
            userName = AdministrativeAPI.GetUserName(userID);
            if(String.IsNullOrEmpty(userName)){
                result.tag = "User was not found";
                return result;
            }
            // Check if user is a member of the specified group
            List<int> allGroups = new List<int>(AdministrativeAPI.ListGroupIDsForUserRecursively(userID));
            if(!allGroups.Contains(groupID)){
                result.tag = "User does not have access to the specified group";
                return result;
            }
            //TODO
            int qualID = AuthorizationAPI.GetQualifierID(clientID, Qualifier.labClientQualifierTypeID);
            int[] clientGroups = AuthorizationAPI.FindGrants(-1, Function.useLabClientFunctionType, qualID);
            // Find the users actual group and run as that group

            List<int> userGroups = new List<int>(AdministrativeAPI.ListGroupIDsForUser(userID));
            if (userGroups.Count == 1)
            {
                groupName = AdministrativeAPI.GetGroupName(userGroups[0]);
            }
            else if (userGroups.Count > 1)
            {

            }
            //TODO This does not seem to be working
            effectiveGroupID = AuthorizationAPI.GetEffectiveGroupID(groupID, clientID,
               Qualifier.labClientQualifierTypeID, Function.useLabClientFunctionType);
            if (effectiveGroupID == groupID)
            {
                effectiveGroupName = groupName;
            }
            else if (effectiveGroupID > 0)
            {
                effectiveGroupName = AdministrativeAPI.GetGroupName(effectiveGroupID);
            }

            ProcessAgentInfo[] paInfos = AdministrativeAPI.GetLabServersForClient(clientID);
            if (paInfos != null && paInfos.Length > 0)
            {
                labServer = paInfos[0];
            }

            if (client.needsScheduling)
            {
                  Ticket allowExperimentExecutionTicket = null;
                        if (opCoupon != null)
                        {
                            // First check for an Allow Execution Ticket
                            allowExperimentExecutionTicket = RetrieveTicket(
                                opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION);
                        }
                        if (allowExperimentExecutionTicket == null)
                        {
                            // Try for a reservation
                            int ussId = FindProcessAgentIdForClient(client.clientID, ProcessAgentType.SCHEDULING_SERVER);
                            if (ussId > 0)
                            {
                                ProcessAgent uss = GetProcessAgent(ussId);
                                // check for current reservation

                                //create a collection & redeemTicket
                                string redeemPayload = TicketLoadFactory.Instance().createRedeemReservationPayload(DateTime.UtcNow,
                                    DateTime.UtcNow, userName, userID,
                                    groupName, client.clientGuid);

                                 Coupon redeemCoupon = CreateCoupon();

                                AddTicket(redeemCoupon, TicketTypes.REDEEM_RESERVATION, uss.agentGuid,
                                    ProcessAgentDB.ServiceGuid, 600, redeemPayload);

                                UserSchedulingProxy ussProxy = new UserSchedulingProxy();
                                OperationAuthHeader op = new OperationAuthHeader();
                                op.coupon = redeemCoupon;
                                ussProxy.Url = uss.webServiceUrl;
                                ussProxy.OperationAuthHeaderValue = op;
                                Reservation reservation = ussProxy.RedeemReservation(ProcessAgentDB.ServiceGuid,
                                    userName, labServer.agentGuid, client.clientGuid);
                                if (reservation != null)
                                {

                                    // create the allowExecution Ticket
                                    DateTime start = reservation.Start;
                                    duration = reservation.Duration;
                                    string payload = TicketLoadFactory.Instance().createAllowExperimentExecutionPayload(
                                        start, duration, effectiveGroupName,client.clientGuid);
                                    DateTime tmpTime = start.AddTicks(duration * TimeSpan.TicksPerSecond);
                                    DateTime utcNow = DateTime.UtcNow;
                                    long ticketDuration = (tmpTime.Ticks - utcNow.Ticks) / TimeSpan.TicksPerSecond;
                                    allowExperimentExecutionTicket = AddTicket(opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION,
                                            ProcessAgentDB.ServiceGuid, ProcessAgentDB.ServiceGuid, ticketDuration, payload);
                                }
                            }
                        }
                        if (allowExperimentExecutionTicket != null)
                        {
                            XmlDocument payload = new XmlDocument();
                            payload.LoadXml(allowExperimentExecutionTicket.payload);
                            startExecution = DateUtil.ParseUtc(payload.GetElementsByTagName("startExecution")[0].InnerText);
                            duration = Int64.Parse(payload.GetElementsByTagName("duration")[0].InnerText);
                        }
                        else{ // No current scheduled reservations
                            result.id = -8;
                            result.tag = "Go to USS";
                            return result;
                        }

            }
            else // Not Scheduled
            {
            }
                ///////////////////////////

                if (labServer != null)
                {
                    if (client.IsReentrant)
                    {
                        long[] ids = InternalDataDB.RetrieveActiveExperimentIDs(userID,
                                       effectiveGroupID, labServer.agentId,client.clientID);
                        foreach (long id in ids)
                        {
                            InternalDataDB.CloseExperiment(id, StorageStatus.CLOSED_USER);
                        }
                    }
                    TicketLoadFactory factory = TicketLoadFactory.Instance();
                    // 1. Create Coupon for ExperimentCollection
                    Coupon expCoupon = CreateCoupon();

                    iLabProperties properties = new iLabProperties();
                    properties.Add("sb", ProcessAgentDB.ServiceAgent);
                    properties.Add("ls", labServer);
                    properties.Add("op", expCoupon);

                    DateTime start = DateTime.UtcNow;
                    duration = 7L * 24L * 60L * 60L; // default is one week
                     RecipeExecutor executor = null;
                    string redirectURL = null;

                    //Create a redeemSession ticket for the experiment
                    //payload includes username and current group name & client id.
                    string sessionPayload = factory.createRedeemSessionPayload(userID, groupID,
                               clientID, userName, groupName);
                    // SB is the redeemer, ticket type : session_identifcation, no expiration time, payload,SB as sponsor ID, redeemer(SB) coupon
                    AddTicket(expCoupon, TicketTypes.REDEEM_SESSION, ProcessAgentDB.ServiceGuid,
                                  ProcessAgentDB.ServiceGuid, duration, sessionPayload);

                   // AdministrativeAPI.ModifyUserSession(Convert.ToInt64(Session["SessionID"]), groupID, clientID, Session.SessionID);

                    if (client.clientType == LabClient.INTERACTIVE_HTML_REDIRECT)
                    {
                        // execute the "interactive experiment execution recipe
                        executor = RecipeExecutor.Instance();

                        // loaderScript not parsed in Recipe
                        redirectURL = executor.ExecuteExperimentExecutionRecipe(expCoupon, labServer, client,
                         start, duration, userTZ, userID,
                         effectiveGroupID, effectiveGroupName);
                        //Do not add the returnURL

                        // Parse & check that the default auth tokens are added
                        result.tag = parser.Parse(redirectURL, properties, true);
                        result.id = LabClient.INTERACTIVE_BIT | LabClient.REDIRECT_BIT;
                    }

                    else if (client.clientType == LabClient.INTERACTIVE_APPLET)
                    {
                          // execute the "interactive experiment execution recipe
                        executor = RecipeExecutor.Instance();

                        // loaderScript not parsed in Recipe
                        redirectURL = executor.ExecuteExperimentExecutionRecipe(expCoupon, labServer, client,
                         start, duration, userTZ, userID,
                         effectiveGroupID, effectiveGroupName);
                        // Applets do not use default query string parameters, parameters must be in the loader script
                        result.tag = parser.Parse(redirectURL, properties);
                        result.id = LabClient.INTERACTIVE_BIT | LabClient.APPLET_BIT;

                        //string jScript = @"<script language='javascript'>parent.theapplet.location.href = '"
                        //    + "applet.aspx" + @"'</script>";
                        //Page.RegisterStartupScript("ReloadFrame", jScript);
                    }

                    // Support for Batch 6.1 Lab Clients
                    else if (client.clientType == LabClient.BATCH_HTML_REDIRECT)
                    {
                        // use the Loader script for Batch experiments, for now check for default properties
                        result.tag = parser.Parse(client.loaderScript, properties,true);
                        result.id = LabClient.BATCH_BIT | LabClient.REDIRECT_BIT;
                    }
                    // use the Loader script for Batch experiments
                    else if (client.clientType == LabClient.BATCH_APPLET)
                    {
                        // Do not append defaults
                        result.tag = parser.Parse(client.loaderScript, properties);
                        result.id = LabClient.BATCH_BIT | LabClient.APPLET_BIT;
                    }
                } // labserver != null
                else
                {
                    buf.Append(" LabServer = null");
                }

            Logger.WriteLine(buf.ToString());

            ////////////////
            return result;
        }
        private void launchLabClient(int c_id)
        {
            if (Session["UserID"] == null)
            {
                Response.Redirect("login.aspx");
            }
            int userID = Convert.ToInt32(Session["UserID"]);
            StringBuilder message = new StringBuilder("Message: clientID = ");
            message.Append(btnLaunchLab.CommandArgument + " ");
            LabClient client = AdministrativeAPI.GetLabClient(c_id);
            iLabParser parser = new iLabParser();
            if (client != null)
            {
                // [GeneralTicketing] get lab servers metadata from lab server ids
                ProcessAgentInfo labServer = getLabServer(client.clientID, effectiveGroupID);
                if (labServer != null)
                {
                    if (client.IsReentrant)
                    {
                        long[] ids = InternalDataDB.RetrieveActiveExperimentIDs(Convert.ToInt32(Session["UserID"]),
                                       effectiveGroupID, labServer.agentId, lc.clientID);
                        foreach (long id in ids)
                        {
                            InternalDataDB.CloseExperiment(id, StorageStatus.CLOSED_USER);
                        }
                    }
                    TicketLoadFactory factory = TicketLoadFactory.Instance();
                    // 1. Create Coupon for ExperimentCollection
                    Coupon coupon = issuer.CreateCoupon();

                    iLabProperties properties = new iLabProperties();
                    properties.Add("sb", ProcessAgentDB.ServiceAgent);
                    properties.Add("ls", labServer);
                    properties.Add("op", coupon);

                    Session["ClientID"] = client.clientID;

                    DateTime start = DateTime.UtcNow;
                    long duration = 7L * 24L * 60L * 60L; // default is one week

                    //Check for Scheduling:
                    //The scheduling Ticket should exist and been parsed into the session
                    if (lc.needsScheduling)
                    {
                        start = DateUtil.ParseUtc(Session["StartExecution"].ToString());
                        duration = Convert.ToInt64(Session["Duration"]);
                    }

                    //payload includes username and current group name & client id.
                    string sessionPayload = factory.createRedeemSessionPayload(userID, Convert.ToInt32(Session["GroupID"]),
                               Convert.ToInt32(Session["ClientID"]), (string)Session["UserName"], (string)Session["GroupName"]);
                    // SB is the redeemer, ticket type : session_identifcation, no expiration time, payload,SB as sponsor ID, redeemer(SB) coupon
                    issuer.AddTicket(coupon, TicketTypes.REDEEM_SESSION, ProcessAgentDB.ServiceGuid,
                                 ProcessAgentDB.ServiceGuid, duration, sessionPayload);

                    AdministrativeAPI.ModifyUserSession(Convert.ToInt64(Session["SessionID"]), Convert.ToInt32(Session["GroupID"]), client.clientID, Session.SessionID);

                    if (client.clientType == LabClient.INTERACTIVE_HTML_REDIRECT)
                    {
                        // execute the "experiment execution recipe
                        RecipeExecutor executor = RecipeExecutor.Instance();
                        string redirectURL = null;

                        // loaderScript not parsed in Recipe
                        redirectURL = executor.ExecuteExperimentExecutionRecipe(coupon, labServer, client,
                         start, duration, Convert.ToInt32(Session["UserTZ"]), userID,
                         effectiveGroupID, effectiveGroupName);

                        // Add the return url to the redirect
                        if (redirectURL.IndexOf("?") == -1)
                            redirectURL += "?";
                        else
                            redirectURL += "&";
                        redirectURL += "sb_url=" + Utilities.ExportUrlPath(Request.Url);
                        // Parse & check that the default auth tokens are added
                        string tmpUrl = parser.Parse(redirectURL, properties, true);

                        // Now open the lab within the current Window/frame
                        Response.Redirect(tmpUrl, true);
                    }

                    else if (client.clientType == LabClient.INTERACTIVE_APPLET)
                    {

                        // Note: Currently Interactive applets
                        // use the Loader script for Batch experiments
                        // Applets do not use default query string parameters, parametes must be in the loader script

                        Session["LoaderScript"] = parser.Parse(client.loaderScript, properties);
                        Session.Remove("RedirectURL");

                        string jScript = @"<script language='javascript'>parent.theapplet.location.href = '"
                            + "applet.aspx" + @"'</script>";
                        Page.RegisterStartupScript("ReloadFrame", jScript);
                    }

                    // Support for Batch 6.1 Lab Clients
                    else if (client.clientType == LabClient.BATCH_HTML_REDIRECT)
                    {
                        // use the Loader script for Batch experiments

                        //use ticketing & redirect to url in loader script

                        // [GeneralTicketing] retrieve static process agent corresponding to the first
                        // association lab server */

                        // New comments: The HTML Client is not a static process agent, so we don't search for that at the moment.
                        // Presumably when the interactive SB is merged with the batched, this should check for a static process agent.
                        // - CV, 7/22/05
                        {
                            Session.Remove("LoaderScript");

                            /* This is the original batch-redirect using a pop-up */
                            // check that the default auth tokens are added
                            string jScript = @"<script language='javascript'> window.open ('" + parser.Parse(client.loaderScript, properties, true) + "')</script>";
                            Page.RegisterStartupScript("HTML Client", jScript);

                            /* This is the batch-redirect with a simple redirect, this may not work as we need to preserve session-state */
                            //string redirectURL = lc.loaderScript + "?couponID=" + coupon.couponId + "&passkey=" + coupon.passkey;
                            //Response.Redirect(redirectURL,true);
                        }
                    }
                    // use the Loader script for Batch experiments
                    else if (client.clientType == LabClient.BATCH_APPLET)
                    {
                        // Do not append defaults
                        Session["LoaderScript"] = parser.Parse(client.loaderScript, properties);
                        Session.Remove("RedirectURL");

                        string jScript = @"<script language='javascript'>parent.theapplet.location.href = '"
                            + ProcessAgentDB.ServiceAgent.codeBaseUrl + @"/applet.aspx" + @"'</script>";
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "ReloadFrame", jScript);
                    }
                } // labserver != null
            }
            else
            {
                message.Append(" LabServer = null");
            }
            //lblDebug.Text = message.ToString();
            Logger.WriteLine(message.ToString());
        }