/// <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; }
protected int removeSchedulingInfo(int clientId, int serverId, int ussId, int lssId, ref StringBuilder message) { int status = 1; int result = 1; DateTime start = DateTime.UtcNow; DateTime end = DateTime.MaxValue; ProcessAgent ls = ticketing.GetProcessAgent(serverId); ProcessAgentInfo lss = ticketing.GetProcessAgentInfo(lssId); ProcessAgentInfo uss = ticketing.GetProcessAgentInfo(ussId); if (ls == null) { message.AppendLine("LabServer is not specified!<br/>"); status = 0; } if (lss == null) { message.AppendLine("LSS is not specified!<br/>"); status = 0; } if (uss == null) { message.AppendLine("USS is not specified!<br/>"); status = 0; } if (status < 1) { return status; } TicketLoadFactory tlf = TicketLoadFactory.Instance(); string payload = tlf.createRevokeReservationPayload("ISB"); Coupon coupon = ticketing.CreateTicket(TicketTypes.REVOKE_RESERVATION, lss.agentGuid, ProcessAgentDB.ServiceGuid, 300L, payload); ticketing.AddTicket(coupon, TicketTypes.REVOKE_RESERVATION, uss.agentGuid, ProcessAgentDB.ServiceGuid, 300L, payload); LabSchedulingProxy lssProxy = new LabSchedulingProxy(); AgentAuthHeader agentHeader = new AgentAuthHeader(); agentHeader.agentGuid = ProcessAgentDB.ServiceGuid; agentHeader.coupon = lss.identOut; lssProxy.AgentAuthHeaderValue = agentHeader; OperationAuthHeader opHeader = new OperationAuthHeader(); opHeader.coupon = coupon; lssProxy.OperationAuthHeaderValue = opHeader; lssProxy.Url = lss.webServiceUrl; int count = lssProxy.RemoveReservation(ProcessAgentDB.ServiceGuid, "", uss.agentGuid, ls.agentGuid, labClient.clientGuid, start, end); result = lssProxy.RemoveExperimentInfo(ls.agentGuid, labClient.clientGuid); if (result > 0) { status = Math.Min(status, result); } UserSchedulingProxy ussProxy = new UserSchedulingProxy(); AgentAuthHeader header = new AgentAuthHeader(); header.agentGuid = ProcessAgentDB.ServiceGuid; header.coupon = uss.identOut; ussProxy.AgentAuthHeaderValue = header; OperationAuthHeader op2Header = new OperationAuthHeader(); op2Header.coupon = coupon; ussProxy.OperationAuthHeaderValue = op2Header; ussProxy.Url = uss.webServiceUrl; int num = ussProxy.RevokeReservation(ProcessAgentDB.ServiceGuid, "", ls.agentGuid, labClient.clientGuid, start, end, "The USS is being removed from this lab client!"); result = ussProxy.RemoveExperimentInfo(ls.agentGuid, labClient.clientGuid, lss.agentGuid); if (result > 0) { status = Math.Min(status, result); } return status; }
protected int dissociateUSS(int ussID, ref StringBuilder message) { ProcessAgentInfo lss = null; ProcessAgentInfo uss = null; int status = 1; int result = 1; int labServerID = Convert.ToInt32(hdnLabServerID.Value); try { if (labClientID <= 0) { message.AppendLine("Please save the Lab Client information before attempting to dissociate it from a resource<br/>"); status = 0; } if (labServerID <= 0) { message.AppendLine("The labserver is currently not set.<br/>"); status = 0; } if (ussID <= 0) { message.AppendLine("Please select a desired USS to be dissociated from the client.<br/>"); status = 0; } if (status < 1) { return status; } // Check if USS & LSS are assigned int uss_Id = ResourceMapManager.FindResourceProcessAgentID(ResourceMappingTypes.CLIENT, labClientID, ProcessAgentType.SCHEDULING_SERVER); if (ussID != uss_Id) { message.AppendLine("The uss_Id and currently assigned resource do not match!<br/>"); return -1; } int ussMapId = ResourceMapManager.FindMapID(ResourceMappingTypes.CLIENT, labClientID, ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.SCHEDULING_SERVER); int lssId = ResourceMapManager.FindResourceProcessAgentID(ResourceMappingTypes.PROCESS_AGENT, Convert.ToInt32(hdnLabServerID.Value), ProcessAgentType.LAB_SCHEDULING_SERVER); if (ussID > 0 || lssId > 0) { //remove ExperimentInfo result = removeSchedulingInfo(labClientID, labServerID, ussID, lssId, ref message); status = Math.Min(status, result); } //LabClient lc = new LabClient(); //lc = labClients[ddlLabClient.SelectedIndex - 1]; UserSchedulingProxy ussProxy = new UserSchedulingProxy(); ticketing.DeleteResourceMapping(ussMapId); btnRegisterUSS.Text = "Register"; btnRegisterUSS.Visible = true; hdnUssID.Value = zero; message.AppendLine("User-side Scheduling Server \"" + ddlAssociatedUSS.SelectedItem.Text + "\" succesfully " + "dissociated from client \"" + ddlLabClient.SelectedItem.Text + "\"."); ddlAssociatedUSS.Visible = true; ddlAssociatedUSS.SelectedIndex = 0; txtAssociatedUSS.Visible = false; status = 1; } catch { throw; } return status; }
/// <summary> /// Method that does the actual make reservation for the user. /// makes the basis of the parameters from the message and the application database /// </summary> /// <param name="userName"> the user who is scheduling for the lab; must be registered with the service broker</param> /// <param name="groupName">the group name authorized to do a lab</param> /// <param name="labServerGuid">lab server which holds the lab that does the actual scheduling</param> /// <param name="clientGuid">Guid of the lab being registered for</param> /// <param name="start">Start time of a particular period scheduled for</param> /// <param name="end">End time of a particular period being scheduled for</param> /// <returns>returns a message string that the application bases on for to give the feedback to the user</returns> public static string MakeReservation(string userName, string groupName, string labServerGuid, string clientGuid, DateTime start, DateTime end) { string lsGuid = null; int status = -1; string message = null; if (ProcessAgentDB.ServiceAgent != null && ProcessAgentDB.ServiceAgent.domainGuid != null) { ProcessAgentDB paDb = new ProcessAgentDB(); ProcessAgentInfo domainServer = paDb.GetProcessAgentInfo(ProcessAgentDB.ServiceAgent.domainGuid); InteractiveSBProxy isbProxy = new InteractiveSBProxy(); isbProxy.AgentAuthHeaderValue = new AgentAuthHeader(); isbProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; isbProxy.AgentAuthHeaderValue.coupon = domainServer.identOut; isbProxy.Url = domainServer.ServiceUrl; string[] types = new string[] { TicketTypes.SCHEDULE_SESSION }; Coupon opCoupon = isbProxy.RequestAuthorization(types, 600, userName, groupName, labServerGuid, clientGuid); if (opCoupon != null) { TicketIssuerProxy ticketProxy = new TicketIssuerProxy(); ticketProxy.AgentAuthHeaderValue = new AgentAuthHeader(); ticketProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; ticketProxy.AgentAuthHeaderValue.coupon = domainServer.identOut; ticketProxy.Url = domainServer.ServiceUrl; //the method call below is one which does not returns a null value //in otherwards the ticket value is not created. Ticket ticketSMS = ticketProxy.RedeemTicket(opCoupon, TicketTypes.SCHEDULE_SESSION, ProcessAgentDB.ServiceGuid); if (ticketSMS != null) { if (ticketSMS.payload != null || ticketSMS.payload.Length > 0) { XmlQueryDoc xdoc = new XmlQueryDoc(ticketSMS.payload); string ussURL = xdoc.Query("ScheduleSessionPayload/ussURL"); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); ussProxy.OperationAuthHeaderValue = new OperationAuthHeader(); ussProxy.OperationAuthHeaderValue.coupon = opCoupon; ussProxy.Url = ussURL; TimePeriod[] times = ussProxy.RetrieveAvailableTimePeriods(ProcessAgentDB.ServiceAgent.domainGuid, groupName, labServerGuid, clientGuid, start, end); // Logic to check for final time DateTime resStart = start; DateTime resEnd = end; message = ussProxy.AddReservation(ProcessAgentDB.ServiceAgent.domainGuid, userName, groupName, labServerGuid, clientGuid, resStart, resEnd); } } } else { message = "coupon is null"; } } else { message = "This service is not part of a domain, please contact the administrator!"; } return message; }
protected int registerUSS(int ussID, ref StringBuilder message) { int status = 1; ProcessAgentInfo uss = null; try { if (labClientID <= 0) { message.AppendLine("Please save the Lab Client information before attempting to associate it with a resource."); status = 0; } if (ddlAssociatedUSS.SelectedIndex == 0) { message.AppendLine("Please select a desired USS to be associated with the client."); status = 0; } if (status < 1) return status; if (ussID > 0) { uss = ticketing.GetProcessAgentInfo(ussID); if (uss != null) { if (uss.retired) { message.AppendLine("The specified USS is retired.<br/>"); return 0; } TicketLoadFactory factory = TicketLoadFactory.Instance(); //this should be in a loop int[] labServerIDs = AdministrativeAPI.GetLabServerIDsForClient(labClientID); if (labServerIDs != null && labServerIDs.Length > 0) { for (int i = 0; i < labServerIDs.Length; i++) { if (labServerIDs[i] > 0) { ProcessAgentInfo labServer = ticketing.GetProcessAgentInfo(labServerIDs[i]); if (labServer.retired) { message.AppendLine("The lab server: " + labServer.agentName + " is retired!<br/>"); } int lssId = ticketing.FindProcessAgentIdForAgent(labServerIDs[i], ProcessAgentType.LAB_SCHEDULING_SERVER); if (lssId > 0) { ProcessAgentInfo lss = ticketing.GetProcessAgentInfo(lssId); if (lss != null) { if (lss.retired) { message.AppendLine("The LSS: " + lss.agentName + " is retired!<br/>"); return 0; } LabSchedulingProxy lssProxy = new LabSchedulingProxy(); lssProxy.Url = lss.webServiceUrl; lssProxy.AgentAuthHeaderValue = new AgentAuthHeader(); lssProxy.AgentAuthHeaderValue.coupon = lss.identOut; lssProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; // Is this in the domain or cross-domain //if (lss.domainGuid.Equals(ProcessAgentDB.ServiceGuid)) // { lssProxy.AddExperimentInfo(labServer.agentGuid, labServer.agentName, labClient.clientGuid, labClient.clientName, labClient.version, labClient.contactEmail); //} // check for existing REVOKE_RESERVATION tickets bool needUssRevoke = true; bool needLssRevoke = true; Coupon ussRevokeCoupon = null; Coupon lssRevokeCoupon = null; Ticket ussRevoke = null; Ticket lssRevoke = null; Ticket[] ussRevokeTickets = ticketing.RetrieveIssuedTickets(-1L, TicketTypes.REVOKE_RESERVATION, uss.agentGuid, lss.agentGuid); if (ussRevokeTickets != null && ussRevokeTickets.Length > 0) { ussRevoke = ussRevokeTickets[0]; needUssRevoke = false; } Ticket[] lssRevokeTickets = ticketing.RetrieveIssuedTickets(-1L, TicketTypes.REVOKE_RESERVATION, lss.agentGuid, uss.agentGuid); if (lssRevokeTickets != null && lssRevokeTickets.Length > 0) { lssRevoke = lssRevokeTickets[0]; needLssRevoke = false; } if (ussRevoke == null && lssRevoke == null) { ussRevokeCoupon = ticketing.CreateCoupon(); lssRevokeCoupon = ussRevokeCoupon; } if (needUssRevoke) { string ussRevokePayload = factory.createRevokeReservationPayload("LSS"); if (ussRevokeCoupon == null) { ussRevokeCoupon = ticketing.CreateTicket(TicketTypes.REVOKE_RESERVATION, uss.agentGuid, lss.agentGuid, -1L, ussRevokePayload); } else { ticketing.AddTicket(ussRevokeCoupon, TicketTypes.REVOKE_RESERVATION, uss.agentGuid, lss.agentGuid, -1L, ussRevokePayload); } // Is this in the domain or cross-domain if (lss.domainGuid.Equals(ProcessAgentDB.ServiceGuid)) { // this domain //Add USS on LSS int ussAdded = lssProxy.AddUSSInfo(uss.agentGuid, uss.agentName, uss.webServiceUrl, ussRevokeCoupon); status = 1; } else { // cross-domain // send consumerInfo to remote SB int remoteSbId = ticketing.GetProcessAgentID(lss.domainGuid); message.AppendLine(RegistrationSupport.RegisterClientUSS(remoteSbId, null, lss.agentId, null, labServer.agentId, ussRevokeCoupon, uss.agentId, null, labClient.clientID)); } } UserSchedulingProxy ussProxy = new UserSchedulingProxy(); ussProxy.Url = uss.webServiceUrl; ussProxy.AgentAuthHeaderValue = new AgentAuthHeader(); ussProxy.AgentAuthHeaderValue.coupon = uss.identOut; ussProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; if (needLssRevoke) { //ADD LSS on USS string ussPayload = factory.createAdministerUSSPayload(Convert.ToInt32(Session["UserTZ"])); string lssRevokePayload = factory.createRevokeReservationPayload("USS"); if (lssRevokeCoupon == null) { lssRevokeCoupon = ticketing.CreateTicket(TicketTypes.REVOKE_RESERVATION, lss.agentGuid, uss.agentGuid, -1L, lssRevokePayload); } else { ticketing.AddTicket(lssRevokeCoupon, TicketTypes.REVOKE_RESERVATION, lss.agentGuid, uss.agentGuid, -1L, lssRevokePayload); } int lssAdded = ussProxy.AddLSSInfo(lss.agentGuid, lss.agentName, lss.webServiceUrl, lssRevokeCoupon); } //Add Experiment Information on USS int expInfoAdded = ussProxy.AddExperimentInfo(labServer.agentGuid, labServer.agentName, labClient.clientGuid, labClient.clientName, labClient.version, labClient.contactEmail, lss.agentGuid); //Ceate resource Map ResourceMappingKey key = new ResourceMappingKey(ResourceMappingTypes.CLIENT, labClientID); List<ResourceMappingValue> valuesList = new List<ResourceMappingValue>(); valuesList.Add(new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.SCHEDULING_SERVER)); valuesList.Add(new ResourceMappingValue(ResourceMappingTypes.PROCESS_AGENT, ussID)); valuesList.Add(new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE, TicketTypes.GetTicketType(TicketTypes.SCHEDULE_SESSION))); // Add the mapping to the database & cache ResourceMapping newMapping = ticketing.AddResourceMapping(key, valuesList.ToArray()); // add mapping to qualifier list int qualifierType = Qualifier.resourceMappingQualifierTypeID; string name = ticketing.ResourceMappingToString(newMapping); int qualifierID = AuthorizationAPI.AddQualifier(newMapping.MappingID, qualifierType, name, Qualifier.ROOT); // Group Credentials MOVED TO THE MANAGE LAB GROUPS PAGE } else { message.AppendLine("The specified LSS was not found!<br/>"); return 0; } } else { message.AppendLine("You must assign a LSS to the lab server before you may assign a USS!<br/>"); return 0; } } } } else { message.AppendLine("You must assign a Lab Server before assigning a USS!<br/>"); return 0; } btnRegisterUSS.Visible = true; btnRegisterUSS.Text = "Dissociate"; ddlAssociatedUSS.Visible = false; txtAssociatedUSS.Visible = true; txtAssociatedUSS.Text = ddlAssociatedUSS.SelectedItem.Text; hdnUssID.Value = ussID.ToString(); message.AppendLine("User-side Scheduling Server \"" + ddlAssociatedUSS.SelectedItem.Text + "\" succesfully " + "associated with client \"" + ddlLabClient.SelectedItem.Text + "\"."); } } else { message.AppendLine("USS was not found!<br/>"); return 0; } } catch (Exception e) { message.AppendLine("Exception: " + e.Message); return -1; } return status; }
void JunkCode() { string revoked = "revoke"; int count = 0; DateTime startDate = DateTime.MinValue; int startHours = -1; int startMinutes = -1; DateTime endDate = DateTime.MinValue; int endHours = -1; int endMinutes = -1; // input error check try { if (txtStartMin.Text.Length > 0) startMinutes = int.Parse(txtStartMin.Text); if (startMinutes >= 60 || startMinutes < 0) { string msg = "Please input right form of minute in the start time "; lblErrorMessage.Text = Utilities.FormatWarningMessage(msg); lblErrorMessage.Visible = true; } if (txtEndMin.Text.Length > 0) endMinutes = int.Parse(txtEndMin.Text); if (endMinutes > 60 || endMinutes < 0) { string msg = "Please input right form of minute in the end time "; lblErrorMessage.Text = Utilities.FormatWarningMessage(msg); lblErrorMessage.Visible = true; } if (txtEndDate.Text.Length == 0 || txtEndDate.Text.CompareTo(culture.DateTimeFormat.ShortDatePattern) == 0) { lblErrorMessage.Text = Utilities.FormatWarningMessage("You must enter the end date of the time block."); lblErrorMessage.Visible = true; return; } endDate = DateTime.Parse(txtEndDate.Text, culture); if (txtStartDate.Text.Length == 0 || txtStartDate.Text.CompareTo(culture.DateTimeFormat.ShortDatePattern) == 0) { lblErrorMessage.Text = Utilities.FormatWarningMessage("You must enter the end date of the time block."); lblErrorMessage.Visible = true; return; } startDate = DateTime.Parse(txtStartDate.Text, culture); if (endDate < startDate) { lblErrorMessage.Text = Utilities.FormatWarningMessage("The end date must be greater than or equal to the start date."); lblErrorMessage.Visible = true; return; } } catch (Exception ex) { string msg = ex.Message; lblErrorMessage.Text = Utilities.FormatErrorMessage(msg); lblErrorMessage.Visible = true; } startHours = int.Parse(ddlStartHour.SelectedItem.Text); endHours = int.Parse(ddlEndHour.SelectedItem.Text); DateTime startTime = new DateTime(startDate.Year, startDate.Month, startDate.Day, startHours, startMinutes, 0, DateTimeKind.Utc); startTime.AddMinutes(userTZ); DateTime endTime = new DateTime(endDate.Year, endDate.Month, endDate.Day, endHours, endMinutes, 0, DateTimeKind.Utc); endTime.AddMinutes(userTZ); //Ticket ticketforRevo = ticketRetrieval.RetrieveAndVerify(coupon, TicketTypes.REVOKE_RESERVATION); // the removed reservations on LSS ArrayList removedRes = new ArrayList(); ArrayList ussGuids = new ArrayList(); if (startTime > endTime) { string msg = "the start time should be earlier than the end time"; lblErrorMessage.Text = Utilities.FormatWarningMessage(msg); lblErrorMessage.Visible = true; return; } try { //the reservations going to be removed int[] resIDs = dbManager.ListReservationInfoIDsByLabServer(Session["lsGuid"].ToString(), startTime, endTime); if (resIDs != null && resIDs.Length > 0) { count = dbManager.RevokeReservations(resIDs, txtMessage.Text); lblErrorMessage.Text = Utilities.FormatConfirmationMessage("For the time period " + DateUtil.ToUserTime(startTime, culture, userTZ) + " to " + DateUtil.ToUserTime(endTime, culture, userTZ) + ", " + count + " out of " + resIDs.Length + " reservations have been revoked successfully."); lblErrorMessage.Visible = true; } } catch (Exception ex) { lblErrorMessage.Text = Utilities.FormatErrorMessage("The related reservations have not been revoked successfully." + ex.Message); lblErrorMessage.Visible = true; // rollback foreach (ReservationInfo resInfo in removedRes) { dbManager.AddReservationInfo(resInfo.startTime, resInfo.endTime, resInfo.credentialSetId, resInfo.experimentInfoId, resInfo.resourceId, resInfo.ussId, resInfo.statusCode); } return; } try { foreach (string uGuid in ussGuids) { int uInfoID = dbManager.ListUSSInfoID(uGuid); USSInfo[] ussArray = dbManager.GetUSSInfos(new int[] { uInfoID }); if (ussArray.Length > 0) { Coupon revokeCoupon = dbManager.GetCoupon(ussArray[0].revokeCouponId, ussArray[0].domainGuid); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); ussProxy.Url = ussArray[0].ussUrl; //assign the coupon from ticket to the soap header; OperationAuthHeader opHeader = new OperationAuthHeader(); opHeader.coupon = revokeCoupon; ussProxy.OperationAuthHeaderValue = opHeader; //if (ussProxy.RevokeReservation(Session["lsGuid"].ToString(), startTime, endTime)) //{ // lblErrorMessage.Text = Utilities.FormatConfirmationMessage(" The related reservations have been revoked successfully !"); // lblErrorMessage.Visible = true; //} } } } catch (Exception ex) { lblErrorMessage.Text = Utilities.FormatErrorMessage("The related reservation have not been revoked successfully." + ex.Message); lblErrorMessage.Visible = true; // rollback foreach (ReservationInfo resInfo in removedRes) { dbManager.AddReservationInfo(resInfo.startTime, resInfo.endTime, resInfo.credentialSetId, resInfo.experimentInfoId, resInfo.resourceId, resInfo.ussId, resInfo.statusCode); } } }
public static int RevokeReservation(ReservationInfo ri) { int count = 0; LssCredentialSet[] sets = DBManager.GetCredentialSets(new int[] { ri.credentialSetId }); LssExperimentInfo[] exps = DBManager.GetExperimentInfos(new int[] { ri.experimentInfoId }); if (sets != null && sets.Length > 0 && exps != null && exps.Length > 0) { USSInfo uss = DBManager.GetUSSInfo(sets[0].ussGuid); if (uss != null) { ProcessAgentDB paDB = new ProcessAgentDB(); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); OperationAuthHeader header = new OperationAuthHeader(); header.coupon = paDB.GetCoupon(uss.couponId, uss.domainGuid); ussProxy.OperationAuthHeaderValue = header; ussProxy.Url = uss.ussUrl; int num = ussProxy.RevokeReservation(sets[0].serviceBrokerGuid, sets[0].groupName, exps[0].labServerGuid, exps[0].labClientGuid, ri.Start, ri.End, "The reservation time assigned to this reservation is being removed"); if (num > 0) { LSSSchedulingAPI.RemoveReservationInfoByIDs(new int[] { ri.reservationInfoId }); count += num; } } } return count; }
protected void Page_Load(object sender, System.EventArgs e) { int groupID = 0; string groupName = null; lc = wrapper.GetLabClientsWrapper(new int[] { Convert.ToInt32(Session["ClientID"]) })[0]; if (Session["GroupID"] != null && Session["GroupID"].ToString().Length > 0) { groupID = Convert.ToInt32(Session["GroupID"]); } if (Session["GroupName"] != null && Session["GroupName"].ToString().Length > 0) { groupName = Session["GroupName"].ToString(); lblGroupNameTitle.Text = groupName; lblBackToLabs.Text = groupName; if (Convert.ToInt32(Session["ClientCount"]) == 1) lblGroupNameSystemMessage.Text = "Messages for " + groupName; else lblGroupNameSystemMessage.Text = "Messages for " + lc.clientName; } if (!IsPostBack) { auto = Request.QueryString["auto"]; if (auto!= null && auto.Length > 0) { if (auto.ToLower().Contains("t")) { autoLaunch = true; } } if (lc.clientType == LabClient.INTERACTIVE_APPLET || lc.clientType == LabClient.INTERACTIVE_HTML_REDIRECT) { // retrieve parameters from URL couponId = Request.QueryString["coupon_id"]; passkey = Request.QueryString["passkey"]; issuerGuid = Request.QueryString["issuer_guid"]; if (lc.needsScheduling) { Coupon opCoupon = null; if (couponId != null && passkey != null && issuerGuid != null) { opCoupon = new Coupon(issuerGuid, Int64.Parse(couponId), passkey); // First check for an Allow Execution Ticket Ticket allowExperimentExecutionTicket = issuer.RetrieveTicket( opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION); if (allowExperimentExecutionTicket == null) { // Try for a reservation int ussId = issuer.FindProcessAgentIdForClient(lc.clientID, ProcessAgentType.SCHEDULING_SERVER); if (ussId > 0) { ProcessAgent uss = issuer.GetProcessAgent(ussId); ProcessAgent ls = issuer.GetProcessAgent(lc.labServerIDs[0]); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); OperationAuthHeader op = new OperationAuthHeader(); op.coupon = opCoupon; ussProxy.Url = uss.webServiceUrl; ussProxy.OperationAuthHeaderValue = op; Reservation reservation = ussProxy.RedeemReservation(ProcessAgentDB.ServiceGuid, Session["UserName"].ToString(), ls.agentGuid, lc.clientGuid); if (reservation != null) { // Find efective group string effectiveGroupName = null; int effectiveGroupID = AuthorizationAPI.GetEffectiveGroupID(groupID, lc.clientID, Qualifier.labClientQualifierTypeID, Function.useLabClientFunctionType); if (effectiveGroupID == groupID) { if (Session["groupName"] != null) { effectiveGroupName = Session["groupName"].ToString(); } else { effectiveGroupName = AdministrativeAPI.GetGroupName(groupID); Session["groupName"] = effectiveGroupName; } } else if (effectiveGroupID > 0) { effectiveGroupName = AdministrativeAPI.GetGroupName(effectiveGroupID); } // create the allowExecution Ticket DateTime start = reservation.Start; long duration = reservation.Duration; string payload = TicketLoadFactory.Instance().createAllowExperimentExecutionPayload( start, duration, effectiveGroupName); DateTime tmpTime = start.AddTicks(duration * TimeSpan.TicksPerSecond); DateTime utcNow = DateTime.UtcNow; long ticketDuration = (tmpTime.Ticks - utcNow.Ticks) / TimeSpan.TicksPerSecond; allowExperimentExecutionTicket = issuer.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); Session["StartExecution"] = DateUtil.ToUtcString(startExecution); Session["Duration"] = duration; //groupId = payload.GetElementsByTagName("groupID")[0].InnerText; // Display reenter button if experiment is reentrant & a current experiment exists if (lc.IsReentrant) { long[] ids = InternalDataDB.RetrieveActiveExperimentIDs(Convert.ToInt32(Session["UserID"]), Convert.ToInt32(Session["GroupID"]), lc.labServerIDs[0], lc.clientID); if (ids.Length > 0) { btnLaunchLab.Text = "Launch New Experiment"; btnLaunchLab.Visible = true; pReenter.Visible = true; btnReenter.Visible = true; btnReenter.CommandArgument = ids[0].ToString(); } else { pReenter.Visible = false; btnReenter.Visible = false; btnLaunchLab.Text = "Launch Lab"; if (autoLaunch) { launchLabClient(lc.clientID); } else { btnLaunchLab.Visible = true; } } } else { if (autoLaunch) { launchLabClient(lc.clientID); } else { btnLaunchLab.Visible = true; } } } else { btnLaunchLab.Visible = false; } } } else { if (autoLaunch) { launchLabClient(lc.clientID); } else { btnLaunchLab.Visible = true; } } } else if (lc.clientType == LabClient.BATCH_APPLET || lc.clientType == LabClient.BATCH_HTML_REDIRECT) { if (autoLaunch) { launchLabClient(lc.clientID); } else { btnLaunchLab.Visible = true; } } } btnSchedule.Visible = lc.needsScheduling; //Session["LoaderScript"] = lc.loaderScript; lblClientName.Text = lc.clientName; lblVersion.Text = lc.version; lblLongDescription.Text = lc.clientLongDescription; lblNotes.Text = lc.notes; string emailCmd = "mailto:" + lc.contactEmail; lblEmail.Text = "<a href=" + emailCmd + ">" + lc.contactEmail + "</a>"; btnLaunchLab.Command += new CommandEventHandler(this.btnLaunchLab_Click); btnLaunchLab.CommandArgument = lc.clientID.ToString(); int count = 0; if (lc.clientInfos != null) { foreach (ClientInfo ci in lc.clientInfos) { if (ci.infoURLName.CompareTo("Documentation") != 0) { System.Web.UI.WebControls.Button b = new System.Web.UI.WebControls.Button(); b.Visible = true; b.CssClass = "button"; b.Text = ci.infoURLName; b.CommandArgument = ci.infoURL; b.CommandName = ci.infoURLName; b.ToolTip = ci.description; b.Command += new CommandEventHandler(this.HelpButton_Click); repClientInfos.Controls.AddAt(count, b); repClientInfos.Controls.AddAt(count + 1, new LiteralControl(" ")); count += 2; } } } List<SystemMessage> messagesList = new List<SystemMessage>(); SystemMessage[] groupMessages = null; if (Session["ClientCount"] != null && Convert.ToInt32(Session["ClientCount"]) == 1) { groupMessages = wrapper.GetSystemMessagesWrapper(SystemMessage.GROUP, Convert.ToInt32(Session["GroupID"]), 0, 0); if (groupMessages != null) messagesList.AddRange(groupMessages); } foreach (int labServerID in lc.labServerIDs) { SystemMessage[] labMessages = wrapper.GetSystemMessagesWrapper(SystemMessage.LAB, 0, 0, labServerID); if (labMessages != null) messagesList.AddRange(labMessages); } if (messagesList != null && messagesList.Count > 0) { messagesList.Sort(SystemMessage.CompareDateDesc); //messagesList.Reverse(); repSystemMessage.DataSource = messagesList; repSystemMessage.DataBind(); } else { lblGroupNameSystemMessage.Text += "</h3><p>No Messages at this time</p><h3>"; } }
protected int revokeReservations(int resourceId, int expId, int credId, DateTime start, DateTime end, ref StringBuilder message) { int status = 0; int count = 0; Dictionary<int, List<ReservationData>> reservations = new Dictionary<int, List<ReservationData>>(); try{ ReservationData[] data = dbManager.RetrieveReservationData(resourceId, expId, credId, start, end); if (data != null && data.Length > 0) { // get list for each USS foreach (ReservationData rd in data) { if (!reservations.ContainsKey(rd.ussId)) { List<ReservationData> lst = new List<ReservationData>(); reservations.Add(rd.ussId, lst); } reservations[rd.ussId].Add(rd); } foreach (int uid in reservations.Keys) { if (uid > 0) { USSInfo uss = dbManager.GetUSSInfo(uid); if (uss != null) { UserSchedulingProxy ussProxy = new UserSchedulingProxy(); OperationAuthHeader header = new OperationAuthHeader(); header.coupon = dbManager.GetCoupon(uss.revokeCouponId, uss.domainGuid); ussProxy.OperationAuthHeaderValue = header; ussProxy.Url = uss.ussUrl; foreach (ReservationData res in reservations[uid]) { int num = ussProxy.RevokeReservation(res.sbGuid, res.groupName, res.labServerGuid, res.clientGuid, res.Start, res.End, txtMessage.Text); //if (num > 0) //{ dbManager.RemoveReservationInfoByIDs(new int[] { res.reservationID }); count += 1; //} status = 1; } } } else { foreach (ReservationData res in reservations[uid]) { dbManager.RemoveReservationInfoByIDs(new int[] { res.reservationID }); status = 1; count += 1; } } } message.AppendLine( count.ToString() + " reservations were revoked!"); } } catch(Exception e){ status = -1; message.AppendLine(e.Message); return status; } return count; }
protected void launchLab(int userID, int groupID, int clientID) { // Currently there is not a good solution for checking for an AllowExperiment ticket, will check the USS for reservation StringBuilder buf = new StringBuilder("~/myClient.aspx?auto=t"); string userName = null; Coupon opCoupon = null; Ticket allowTicket = null; int effectiveGroupID = 0; if (Session["UserName"] != null && Session["UserName"].ToString().Length > 0) { userName = Session["UserName"].ToString(); } else { userName = AdministrativeAPI.GetUserName(userID); } LabClient client = AdministrativeAPI.GetLabClient(clientID); if (client.clientID > 0) // It's a structure need to test for valid value { DateTime start = DateTime.UtcNow; long duration = 36000L; // default is ten hours ProcessAgentInfo labServer = null; if (client.labServerIDs.Length > 0) { labServer = issuer.GetProcessAgentInfo(client.labServerIDs[0]); } else { throw new Exception("The lab server is not specified for lab client " + client.clientName + " version: " + client.version); } // Find efective group string effectiveGroupName = null; effectiveGroupID = AuthorizationAPI.GetEffectiveGroupID(groupID, clientID, Qualifier.labClientQualifierTypeID, Function.useLabClientFunctionType); if (effectiveGroupID == groupID) { if (Session["groupName"] != null) { effectiveGroupName = Session["groupName"].ToString(); } else { effectiveGroupName = AdministrativeAPI.GetGroupName(groupID); Session["groupName"] = effectiveGroupName; } } else if (effectiveGroupID > 0) { effectiveGroupName = AdministrativeAPI.GetGroupName(effectiveGroupID); } //Check for Scheduling: if (client.needsScheduling) { int ussId = issuer.FindProcessAgentIdForClient(client.clientID, ProcessAgentType.SCHEDULING_SERVER); if (ussId > 0) { ProcessAgent uss = issuer.GetProcessAgent(ussId); int lssId = issuer.FindProcessAgentIdForAgent(client.labServerIDs[0], ProcessAgentType.LAB_SCHEDULING_SERVER); ProcessAgent lss = issuer.GetProcessAgent(lssId); // check for current reservation //create a collection & redeemTicket string redeemPayload = TicketLoadFactory.Instance().createRedeemReservationPayload(DateTime.UtcNow, DateTime.UtcNow); opCoupon = issuer.CreateTicket(TicketTypes.REDEEM_RESERVATION, uss.agentGuid, ProcessAgentDB.ServiceGuid, 600, redeemPayload); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); OperationAuthHeader op = new OperationAuthHeader(); op.coupon = opCoupon; 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 start = reservation.Start; duration = reservation.Duration; string payload = TicketLoadFactory.Instance().createAllowExperimentExecutionPayload( start, duration, effectiveGroupName); DateTime tmpTime = start.AddTicks(duration * TimeSpan.TicksPerSecond); DateTime utcNow = DateTime.UtcNow; long ticketDuration = (tmpTime.Ticks - utcNow.Ticks) / TimeSpan.TicksPerSecond; allowTicket = issuer.AddTicket(opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION, ProcessAgentDB.ServiceGuid, ProcessAgentDB.ServiceGuid, ticketDuration, payload); // Append op coupon to url buf.Append("&coupon_id=" + opCoupon.couponId); buf.Append("&passkey=" + opCoupon.passkey); buf.Append("&issuer_guid=" + opCoupon.issuerGuid); } //else //{ // string schedulingUrl = RecipeExecutor.Instance().ExecuteExerimentSchedulingRecipe(uss.agentGuid, lss.agentGuid, userName, groupName, // labServer.agentGuid, client.clientGuid, client.clientName, client.version, // Convert.ToInt64(ConfigurationSettings.AppSettings["scheduleSessionTicketDuration"]), Convert.ToInt32(Session["UserTZ"])); // schedulingUrl += "&sb_url=" + ProcessAgentDB.ServiceAgent.codeBaseUrl + "/myClient.aspx"; // Response.Redirect(schedulingUrl, true); //} } else{ // USS Not Found } } // End needsScheduling //Response.Redirect(Global.FormatRegularURL(Request, "myClient.aspx"), true); Response.Redirect(buf.ToString(), true); } // End if valid client else{ throw new Exception("The specified lab client could not be found"); } }
protected void launchLabXX(int userID, int groupID, int clientID) { // Currently there is not a good solution for checking for an AllowExperiment ticket, will check the USS for reservation Coupon allowExecutionCoupon = null; StringBuilder message = new StringBuilder("Message: clientID = " + clientID); LabClient client = AdministrativeAPI.GetLabClient(clientID); string userName = null; Coupon opCoupon = null; Ticket allowTicket = null; if (Session["UserID"] != null) { if (userID == Convert.ToInt32(Session["UserID"])) { userName = Session["UserName"].ToString(); } else { userName = AdministrativeAPI.GetUserName(userID); Session["UserID"] = userID; Session["UserName"] = userName; } string groupName = AdministrativeAPI.GetGroupName(groupID); if (client.clientID > 0) // It's a structure need to test for valid value { // create the RecipeExecutor string redirectURL = null; DateTime start = DateTime.UtcNow; long duration = 36000L; // default is ten hours ProcessAgentInfo labServer = null; if (client.labServerIDs.Length > 0) { labServer = issuer.GetProcessAgentInfo(client.labServerIDs[0]); } else { throw new Exception("The lab server is not specified for lab client " + client.clientName + " version: " + client.version); } //Check for Scheduling: if (client.needsScheduling) { int ussId = issuer.FindProcessAgentIdForClient(client.clientID, ProcessAgentType.SCHEDULING_SERVER); if (ussId > 0) { ProcessAgent uss = issuer.GetProcessAgent(ussId); //// Find efective group //string effectiveGroupName = null; //int effectiveGroupID = AuthorizationAPI.GetEffectiveGroupID(groupID, clientID, // Qualifier.labClientQualifierTypeID, Function.useLabClientFunctionType); //if (effectiveGroupID == groupID) //{ // if(Session["groupName"] != null){ // effectiveGroupName = Session["groupName"].ToString(); // } // else{ // effectiveGroupName = AdministrativeAPI.GetGroupName(groupID); // Session["groupName"] = effectiveGroupName; // } //} //else if (effectiveGroupID > 0) //{ // effectiveGroupName = AdministrativeAPI.GetGroupName(effectiveGroupID ); //} int lssId = issuer.FindProcessAgentIdForAgent(client.labServerIDs[0], ProcessAgentType.LAB_SCHEDULING_SERVER); ProcessAgent lss = issuer.GetProcessAgent(lssId); // check for current reservation string redeemPayload = TicketLoadFactory.Instance().createRedeemReservationPayload(DateTime.UtcNow, DateTime.UtcNow); opCoupon = issuer.CreateTicket(TicketTypes.REDEEM_RESERVATION, uss.agentGuid, ProcessAgentDB.ServiceGuid, 600, redeemPayload); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); OperationAuthHeader op = new OperationAuthHeader(); op.coupon = opCoupon; ussProxy.Url = uss.webServiceUrl; ussProxy.OperationAuthHeaderValue = op; Reservation reservation = ussProxy.RedeemReservation(ProcessAgentDB.ServiceGuid, userName, labServer.agentGuid, client.clientGuid); if (reservation != null) { start = reservation.Start; duration = reservation.Duration; string payload = TicketLoadFactory.Instance().createAllowExperimentExecutionPayload( start, duration, groupName); DateTime tmpTime = start.AddTicks(duration * TimeSpan.TicksPerSecond); DateTime utcNow = DateTime.UtcNow; long ticketDuration = (tmpTime.Ticks - utcNow.Ticks) / TimeSpan.TicksPerSecond; allowTicket = issuer.AddTicket(opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION, ProcessAgentDB.ServiceGuid, ProcessAgentDB.ServiceGuid, ticketDuration, payload); } else { string schedulingUrl = RecipeExecutor.Instance().ExecuteExerimentSchedulingRecipe(uss.agentGuid, lss.agentGuid, userName, groupName, labServer.agentGuid, client.clientGuid, client.clientName, client.version, Convert.ToInt64(ConfigurationSettings.AppSettings["scheduleSessionTicketDuration"]), Convert.ToInt32(Session["UserTZ"])); schedulingUrl += "&sb_url=" + ProcessAgentDB.ServiceAgent.codeBaseUrl + "/myClient.aspx"; Response.Redirect(schedulingUrl, true); } } } if (client.clientType == LabClient.INTERACTIVE_HTML_REDIRECT) { if (client.IsReentrant) // check for an existing active experiment { long[] ids = InternalDataDB.RetrieveActiveExperimentIDs(userID, groupID, client.labServerIDs[0], client.clientID); if (ids.Length > 0) { long[] coupIDs = InternalDataDB.RetrieveExperimentCouponIDs(ids[0]); Coupon coupon = issuer.GetIssuedCoupon(coupIDs[0]); // construct the redirect query StringBuilder url = new StringBuilder(client.loaderScript.Trim()); if (url.ToString().IndexOf("?") == -1) url.Append('?'); else url.Append('&'); url.Append("coupon_id=" + coupon.couponId + "&passkey=" + coupon.passkey + "&issuer_guid=" + issuer.GetIssuerGuid()); // Add the return url to the redirect url.Append("&sb_url="); url.Append(ProcessAgentDB.ServiceAgent.codeBaseUrl +"/myClient.aspx"); // Now open the lab within the current Window/frame Response.Redirect(url.ToString(), true); } } //Check for Scheduling: if (client.needsScheduling) { //The scheduling Ticket should exist and been parsed into the session if (allowTicket == null) { throw new Exception(" Unable to confirm a reservation for this client."); } } // execute the "experiment execution recipe redirectURL = RecipeExecutor.Instance().ExecuteExperimentExecutionRecipe(labServer, client, start, duration, Convert.ToInt32(Session["UserTZ"]), userID, groupID, (string)Session["GroupName"]); // Add the return url to the redirect redirectURL += "&sb_url=" + ProcessAgentDB.ServiceAgent.codeBaseUrl +"/myClient.aspx"; // Now open the lab within the current Window/frame Response.Redirect(redirectURL, true); } else if (client.clientType == LabClient.INTERACTIVE_APPLET) { // Note: Currently not supporting Interactive applets // use the Loader script for Batch experiments // This assumes that the client will request the experiment creation Session["LoaderScript"] = client.loaderScript; 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) { Session["ClientID"] = client.clientID; AdministrativeAPI.SetSessionClient(Convert.ToInt64(Session["SessionID"]), client.clientID); // 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"); //payload includes username and effective group name & client id. //ideally this should be encoded in xml - CV, 7/27/2005 TicketLoadFactory factory = TicketLoadFactory.Instance(); string uName = (string)Session["UserName"]; string gName = (string)Session["GroupName"]; string sessionPayload = factory.createRedeemSessionPayload(userID, groupID, clientID, uName, gName); // SB is the redeemer, ticket type : session_identifcation, no expiration time, payload,SB as sponsor ID, redeemer(SB) coupon Coupon coupon = issuer.CreateTicket(TicketTypes.REDEEM_SESSION, ProcessAgentDB.ServiceGuid, ProcessAgentDB.ServiceGuid, -1, sessionPayload); string jScript = @"<script language='javascript'> window.open ('" + client.loaderScript + "?couponID=" + coupon.couponId + "&passkey=" + coupon.passkey + "')</script>"; Page.RegisterStartupScript("HTML Client", jScript); } } // use the Loader script for Batch experiments else if (client.clientType == LabClient.BATCH_APPLET) { Session["ClientID"] = client.clientID; AdministrativeAPI.SetSessionClient(Convert.ToInt64(Session["SessionID"]), client.clientID); Session["LoaderScript"] = client.loaderScript; Session.Remove("RedirectURL"); string jScript = @"<script language='javascript'>parent.theapplet.location.href = '" + ProcessAgentDB.ServiceAgent.codeBaseUrl + @"/applet.aspx" + @"'</script>"; ClientScript.RegisterClientScriptBlock(this.GetType(), "ReloadFrame", jScript); } } else { message.Append(" LabServer = null"); } //lblDebug.Text = message.ToString(); Utilities.WriteLog(message.ToString()); }
/* TO DO */ public int RevokeReservation(ReservationInfo ri, string message) { int count = 0; LssCredentialSet[] sets = GetCredentialSets(new int[] { ri.credentialSetId }); LssExperimentInfo[] exps = GetExperimentInfos(new int[] { ri.experimentInfoId }); if (sets != null && sets.Length > 0 && exps != null && exps.Length > 0) { USSInfo uss = GetUSSInfo(ri.ussId); if (uss != null) { UserSchedulingProxy ussProxy = new UserSchedulingProxy(); OperationAuthHeader header = new OperationAuthHeader(); header.coupon = GetCoupon(uss.revokeCouponId, uss.domainGuid); ussProxy.OperationAuthHeaderValue = header; ussProxy.Url = uss.ussUrl; int num = ussProxy.RevokeReservation(sets[0].serviceBrokerGuid, sets[0].groupName, exps[0].labServerGuid, exps[0].labClientGuid, ri.Start, ri.End, message); if (num > 0) { RemoveReservationInfoByIDs(new int[] { ri.reservationInfoId }); count += num; } } } return count; }
// Error recovery must be added to this method protected void btnSaveChange_Click(object sender, EventArgs e) { int id = int.Parse(ddlLabClient.SelectedValue); if (id > 0) { LabClient[] clients = wrapper.GetLabClientsWrapper(new int[] { id }); if (clients.Length > 0 && clients[0].clientID > 0) { theClient = clients[0]; } } // objects used in try block may be required for recovery if errors bool noError = true; ProcessAgentInfo labServer = null; ProcessAgentInfo uss = null; ProcessAgentInfo lss = null; long rmUss = 0; lblResponse.Visible = false; lblResponse.Text = ""; try { if (ddlUserGroup.SelectedIndex <= 0) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatWarningMessage("Please select a user group from the corresponding drop-down list."); return; } int groupID = Convert.ToInt32(ddlUserGroup.SelectedValue); if (groupID <= 0) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatWarningMessage("The user group is invalid."); return; } //Get the user Group Name to be displayed in the repeater Group[] userGroup = wrapper.GetGroupsWrapper(new int[] { groupID }); string userGroupName = userGroup[0].GroupName; if (theClient.labServerIDs != null && theClient.labServerIDs.Length > 0) { labServer = issuer.GetProcessAgentInfo(theClient.labServerIDs[0]); } if (labServer == null) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatWarningMessage("Lab Client should first be associated with a Lab Server"); return; } if (theClient.needsScheduling) { if (ddlAdminGroup.SelectedIndex <= 0 || ddlUserGroup.SelectedIndex <= 0) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatWarningMessage("Please select a user and management group from the corresponding drop-down lists."); return; } int manageID = Convert.ToInt32(ddlAdminGroup.SelectedValue); if (manageID <= 0) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatWarningMessage("The management group is invalid."); return; } int ussId = issuer.FindProcessAgentIdForClient(theClient.clientID, ProcessAgentType.SCHEDULING_SERVER); if (ussId <= 0) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatWarningMessage("Lab Client should first be associated with a USS"); return; } int lssId = issuer.FindProcessAgentIdForAgent(theClient.labServerIDs[0], ProcessAgentType.LAB_SCHEDULING_SERVER); if (lssId <= 0) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatWarningMessage("Lab Server should first be associated with an LSS"); return; } else { uss = issuer.GetProcessAgentInfo(ussId); if (uss.retired) { throw new Exception("The USS is retired"); } lss = issuer.GetProcessAgentInfo(lssId); if (lss.retired) { throw new Exception("The LSS is retired"); } //Object keyObj = groupID; //string keyType = ResourceMappingTypes.GROUP; ResourceMappingKey key = new ResourceMappingKey(ResourceMappingTypes.GROUP, groupID); ResourceMappingValue[] values = new ResourceMappingValue[3]; values[0] = new ResourceMappingValue(ResourceMappingTypes.CLIENT, theClient.clientID); values[1] = new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE, TicketTypes.GetTicketType(TicketTypes.MANAGE_USS_GROUP)); values[2] = new ResourceMappingValue(ResourceMappingTypes.GROUP,manageID); //values[0] = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.SCHEDULING_SERVER); //values[1] = new ResourceMappingValue(ResourceMappingTypes.PROCESS_AGENT, ussId); ResourceMapping newMapping = issuer.AddResourceMapping(key, values); rmUss = newMapping.MappingID; // add mapping to qualifier list int qualifierType = Qualifier.resourceMappingQualifierTypeID; string name = issuer.ResourceMappingToString(newMapping); int qualifierID = AuthorizationAPI.AddQualifier(newMapping.MappingID, qualifierType, name, Qualifier.ROOT); //Give the Manager Group a Grant "MANAGE_USS_GROUP" on the created resource mapping string function = Function.manageUSSGroup; int grantID = wrapper.AddGrantWrapper(manageID, function, qualifierID); //Get the management Group Name to be displayed in the repeater Group[] adminGroup = wrapper.GetGroupsWrapper(new int[] { manageID }); string adminGroupName = adminGroup[0].GroupName; //Create the Map between user and management group GroupManagerUserMap groupMap = new GroupManagerUserMap(adminGroupName, userGroupName, grantID, newMapping.MappingID); TicketLoadFactory factory = TicketLoadFactory.Instance(); //long duration = 60; // Get this SB's domain Guid string domainGuid = ProcessAgentDB.ServiceGuid; string sbName = ProcessAgentDB.ServiceAgent.agentName; //Add Credential set on the USS //string ussPayload = factory.createAdministerUSSPayload(Convert.ToInt32(Session["userTZ"])); //Coupon ussCoupon = issuer.CreateTicket(TicketTypes.ADMINISTER_USS, uss.agentGuid, // issuer.GetIssuerGuid(), duration, ussPayload); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); ussProxy.Url = uss.webServiceUrl; ussProxy.AgentAuthHeaderValue = new AgentAuthHeader(); ussProxy.AgentAuthHeaderValue.coupon = uss.identOut; ussProxy.AgentAuthHeaderValue.agentGuid = domainGuid; ussProxy.AddCredentialSet(domainGuid, sbName, userGroupName); // Check for existing RevokeReservation ticket redeemer = USS, sponsor = LSS Coupon[] revokeCoupons = issuer.RetrieveIssuedTicketCoupon( TicketTypes.REVOKE_RESERVATION, uss.agentGuid, lss.agentGuid); Coupon revokeCoupon = null; if (revokeCoupons != null && revokeCoupons.Length > 0) { revokeCoupon = revokeCoupons[0]; } else { // Create RevokeReservation ticket revokeCoupon = issuer.CreateTicket(TicketTypes.REVOKE_RESERVATION, uss.agentGuid, lss.agentGuid, -1L, factory.createRevokeReservationPayload()); } //Add Credential set on the LSS // check if this domain if (ProcessAgentDB.ServiceGuid.Equals(lss.domainGuid)) { LabSchedulingProxy lssProxy = new LabSchedulingProxy(); lssProxy.Url = lss.webServiceUrl; lssProxy.AgentAuthHeaderValue = new AgentAuthHeader(); lssProxy.AgentAuthHeaderValue.coupon = lss.identOut; lssProxy.AgentAuthHeaderValue.agentGuid = domainGuid; // Add the USS to the LSS, this may be called multiple times with duplicate data lssProxy.AddUSSInfo(uss.AgentGuid, uss.agentName, uss.webServiceUrl, revokeCoupon); int credentialSetAdded = lssProxy.AddCredentialSet(domainGuid, sbName, userGroupName, uss.agentGuid); } else { // Cross-Domain Registration needed ProcessAgentInfo remoteSB = issuer.GetProcessAgentInfo(lss.domainGuid); if(remoteSB.retired){ throw new Exception("The remote service broker is retired"); } ResourceDescriptorFactory resourceFactory = ResourceDescriptorFactory.Instance(); string ussDescriptor = resourceFactory.CreateProcessAgentDescriptor(ussId); string lssDescriptor = resourceFactory.CreateProcessAgentDescriptor(lssId); string groupDescriptor = resourceFactory.CreateGroupCredentialDescriptor(domainGuid, sbName, userGroupName, uss.agentGuid, lss.agentGuid); ServiceDescription[] info = new ServiceDescription[3]; info[0] = new ServiceDescription(null, revokeCoupon, ussDescriptor); info[1] = new ServiceDescription(null, null, lssDescriptor); info[2] = new ServiceDescription(null, null, groupDescriptor); ProcessAgentProxy sbProxy = new ProcessAgentProxy(); sbProxy.AgentAuthHeaderValue = new AgentAuthHeader(); sbProxy.AgentAuthHeaderValue.agentGuid = domainGuid; sbProxy.AgentAuthHeaderValue.coupon = remoteSB.identOut; sbProxy.Url = remoteSB.webServiceUrl; sbProxy.Register(Utilities.MakeGuid(), info); } } } /*Update Lab Client grants*/ //Get qualifier for labclient int lcQualifierID = AuthorizationAPI.GetQualifierID(theClient.clientID, Qualifier.labClientQualifierTypeID); //Get all "uselabclient" grants for this labclient int[] lcGrantIDs = wrapper.FindGrantsWrapper(-1, Function.useLabClientFunctionType, lcQualifierID); Grant[] lcGrants = wrapper.GetGrantsWrapper(lcGrantIDs); //Get list of agents that can use labclient ArrayList lcAgents = new ArrayList(); foreach (Grant g in lcGrants) lcAgents.Add(g.agentID); //if that agent doesn't already have the uselabclient permission if (!lcAgents.Contains(groupID)) //add lab client grant wrapper.AddGrantWrapper(groupID, Function.useLabClientFunctionType, lcQualifierID); /*Update Lab Servers grant*/ //Update grants for each of the associated lab servers foreach (int lsID in theClient.labServerIDs) { //Get qualifier for labserver int lsQualifierID = AuthorizationAPI.GetQualifierID(lsID, Qualifier.labServerQualifierTypeID); //Get all "uselabserver" grants for this labserver int[] lsGrantIDs = wrapper.FindGrantsWrapper(-1, Function.useLabServerFunctionType, lsQualifierID); Grant[] lsGrants = wrapper.GetGrantsWrapper(lsGrantIDs); //Get list of agents that can use labserver ArrayList lsAgents = new ArrayList(); foreach (Grant g in lsGrants) lsAgents.Add(g.agentID); //int groupID = Convert.ToInt32(ddlUserGroup.SelectedValue); //if that agent doesn't already have the uselabclient permission if (!lsAgents.Contains(groupID)) //add lab server grant wrapper.AddGrantWrapper(groupID, Function.useLabServerFunctionType, lsQualifierID); } //Refresh the repeater RefreshAdminUserGroupsRepeater(); LoadListBoxes(); lblResponse.Visible = true; lblResponse.Text = Utilities.FormatConfirmationMessage("Lab client (& corresponding lab servers) successfully updated. "); } catch (Exception ex) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatErrorMessage("Cannot update Lab Client. " + ex.GetBaseException()); } }
protected void btnRegisterUSS_Click(object sender, EventArgs e) { lblResponse.Visible = false; lblResponse.Text = ""; StringBuilder message = new StringBuilder(); try { if (ddlLabClient.SelectedIndex == 0) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatErrorMessage("Please save the Lab Client information before attempting to dissociate it from a resource"); return; } if (ddlAssociatedUSS.SelectedIndex == 0) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatErrorMessage("Please select a desired USS to be associated with the client."); return; } LabClient lc = new LabClient(); lc = labClients[ddlLabClient.SelectedIndex - 1]; Object keyObj = int.Parse(ddlLabClient.SelectedValue); string keyType = ResourceMappingTypes.CLIENT; ArrayList valuesList = new ArrayList(); Object valueObj = null; ResourceMappingValue value = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.SCHEDULING_SERVER); valuesList.Add(value); int ussId = int.Parse(ddlAssociatedUSS.SelectedValue); if (ussId > 0) { value = new ResourceMappingValue(ResourceMappingTypes.PROCESS_AGENT, ussId); valuesList.Add(value); value = new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE, TicketTypes.GetTicketType(TicketTypes.SCHEDULE_SESSION)); valuesList.Add(value); ResourceMappingKey key = new ResourceMappingKey(keyType, keyObj); ResourceMappingValue[] values = (ResourceMappingValue[])valuesList.ToArray((new ResourceMappingValue()).GetType()); // Add the mapping to the database & cache ResourceMapping newMapping = ticketing.AddResourceMapping(key, values); // add mapping to qualifier list int qualifierType = Qualifier.resourceMappingQualifierTypeID; string name = ticketing.ResourceMappingToString(newMapping); int qualifierID = AuthorizationAPI.AddQualifier(newMapping.MappingID, qualifierType, name, Qualifier.ROOT); // Moved to ManageLabGroups //Give the Manager Group a Grant "MANAGE_USS_GROUP" on the created resource mapping //int agentID = Convert.ToInt32(ddlAdminGroup.SelectedValue); //string function = Function.manageUSSGroup; //int grantID = wrapper.AddGrantWrapper(agentID, function, qualifierID); Session["ClientUssMappingID"] = newMapping.MappingID; btnRegisterUSS.Visible = false; btnDissociateUSS.Visible = true; ddlAssociatedUSS.Enabled = false; message.AppendLine("User-side Scheduling Server \"" + ddlAssociatedUSS.SelectedItem.Text + "\" succesfully " + "associated with client \"" + ddlLabClient.SelectedItem.Text + "\"."); //wrapper.ModifyLabClientWrapper(lc.clientID, lc.clientName, lc.version, lc.clientShortDescription, // lc.clientLongDescription, lc.notes, lc.loaderScript, lc.clientType, // lc.labServerIDs, lc.contactEmail, lc.contactFirstName, lc.contactLastName, // lc.needsScheduling, lc.needsESS, lc.IsReentrant, lc.clientInfos); TicketLoadFactory factory = TicketLoadFactory.Instance(); ProcessAgentInfo uss = ticketing.GetProcessAgentInfo(ussId); if (uss.retired) { throw new Exception("The specified USS is retired"); } //this should be in a loop for(int i = 0;i<lc.labServerIDs.Length;i++){ if (lc.labServerIDs[i] > 0) { ProcessAgentInfo labServer = ticketing.GetProcessAgentInfo(lc.labServerIDs[i]); if (labServer.retired) { throw new Exception("The lab server is retired"); } int lssId = ticketing.FindProcessAgentIdForAgent(lc.labServerIDs[i], ProcessAgentType.LAB_SCHEDULING_SERVER); if (lssId > 0) { ProcessAgentInfo lss = ticketing.GetProcessAgentInfo(lssId); if (lss.retired) { throw new Exception("The LSS is retired"); } // The REVOKE_RESERVATION ticket string revokePayload = factory.createRevokeReservationPayload(); Coupon ussCoupon = ticketing.CreateTicket(TicketTypes.REVOKE_RESERVATION, uss.agentGuid, lss.agentGuid, -1L, revokePayload); // Is this in the domain or cross-domain if (lss.domainGuid.Equals(ProcessAgentDB.ServiceGuid)) { // this domain //Add USS on LSS //string lssPayload = factory.createAdministerLSSPayload(Convert.ToInt32(Session["UserTZ"])); //long duration = 60; //seconds for the LSS to redeem the ticket of this coupon and Add LSS Info //ticketing.AddTicket(lssCoupon, TicketTypes.ADMINISTER_LSS, lss.agentGuid, // ticketing.ServiceGuid(), duration, lssPayload); LabSchedulingProxy lssProxy = new LabSchedulingProxy(); lssProxy.Url = lss.webServiceUrl; lssProxy.AgentAuthHeaderValue = new AgentAuthHeader(); lssProxy.AgentAuthHeaderValue.coupon = lss.identOut; lssProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; int ussAdded = lssProxy.AddUSSInfo(uss.agentGuid, uss.agentName, uss.webServiceUrl, ussCoupon); lssProxy.AddExperimentInfo(labServer.agentGuid, labServer.agentName, lc.clientGuid, lc.clientName, lc.version, lc.contactEmail); } else { // cross-domain // send consumerInfo to remote SB int remoteSbId = ticketing.GetProcessAgentID(lss.domainGuid); message.AppendLine(RegistrationSupport.RegisterClientUSS(remoteSbId, null, lss.agentId, null, labServer.agentId, ussCoupon, uss.agentId, null, lc.clientID)); } //ADD LSS on USS string ussPayload = factory.createAdministerUSSPayload(Convert.ToInt32(Session["UserTZ"])); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); ussProxy.Url = uss.webServiceUrl; ussProxy.AgentAuthHeaderValue = new AgentAuthHeader(); ussProxy.AgentAuthHeaderValue.coupon = uss.identOut; ussProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; int lssAdded = ussProxy.AddLSSInfo(lss.agentGuid, lss.agentName, lss.webServiceUrl); //Add Experiment Information on USS int expInfoAdded = ussProxy.AddExperimentInfo(labServer.agentGuid, labServer.agentName, lc.clientGuid, lc.clientName, lc.version, lc.contactEmail, lss.agentGuid); // Group Credentials MOVED TO THE MANAGE LAB GROUPS PAGE } } } } } catch { throw; } lblResponse.Visible = true; lblResponse.Text = Utilities.FormatConfirmationMessage(message.ToString()); }
protected void Page_Load(object sender, System.EventArgs e) { int groupID = 0; int authID = -1; Coupon opCoupon = null; string groupName = null; lblResponse.Visible = false; userTZ = Convert.ToInt32(Session["UserTZ"]); culture = DateUtil.ParseCulture(Request.Headers["Accept-Language"]); lc = null; if (!IsPostBack) { // retrieve parameters from URL couponId = Request.QueryString["coupon_id"]; passkey = Request.QueryString["passkey"]; issuerGuid = Request.QueryString["issuer_guid"]; if (couponId != null && passkey != null && issuerGuid != null) { opCoupon = new Coupon(issuerGuid, Int64.Parse(couponId), passkey); Ticket authExperimentTicket = issuer.RetrieveTicket(opCoupon, TicketTypes.CREATE_EXPERIMENT, ProcessAgentDB.ServiceGuid); if (authExperimentTicket != null) { XmlQueryDoc authDoc = new XmlQueryDoc(authExperimentTicket.payload); string auth = authDoc.Query("CreateExperimentPayload/authID"); if (auth != null && auth.Length > 0) { authID = Int32.Parse(auth); } string grpName = authDoc.Query("CreateExperimentPayload/groupName"); if (grpName != null && groupName.Length > 0) { Session["GroupName"] = grpName; int grpID = AdministrativeAPI.GetGroupID(grpName); if (grpID > 0) Session["GroupID"] = groupID; } string userName = authDoc.Query("CreateExperimentPayload/userName"); if (userName != null && userName.Length > 0) { Session["UserName"] = userName; int userID = AdministrativeAPI.GetUserID(userName,authID); if (userID > 0) Session["UserID"] = userID; } string clientGuid = authDoc.Query("CreateExperimentPayload/clientGuid"); if (clientGuid != null && clientGuid.Length > 0) { Session["ClientGuid"] = clientGuid; int clientID = AdministrativeAPI.GetLabClientID(clientGuid); if (clientID > 0) Session["ClientID"] = clientID; } } } pReenter.Visible = false; btnReenter.Visible = false; auto = Request.QueryString["auto"]; if (auto != null && auto.Length > 0) { if (auto.ToLower().Contains("t")) { autoLaunch = true; } } } if (Session["ClientID"] != null && Session["ClientID"].ToString().Length > 0) { lc = wrapper.GetLabClientsWrapper(new int[] { Convert.ToInt32(Session["ClientID"]) })[0]; } if (Session["GroupID"] != null && Session["GroupID"].ToString().Length > 0) { groupID = Convert.ToInt32(Session["GroupID"]); } if (groupID > 0 && lc != null) { setEffectiveGroup(groupID, lc.clientID); } if (Session["GroupName"] != null && Session["GroupName"].ToString().Length > 0) { groupName = Session["GroupName"].ToString(); lblGroupNameTitle.Text = groupName; } if (lc != null) { labServer = getLabServer(lc.clientID, effectiveGroupID); clientInfos = AdministrativeAPI.ListClientInfos(lc.clientID); if (lc.clientType == LabClient.INTERACTIVE_APPLET || lc.clientType == LabClient.INTERACTIVE_HTML_REDIRECT) { if (lc.needsScheduling) { Ticket allowExperimentExecutionTicket = null; if (opCoupon != null) { // First check for an Allow Execution Ticket allowExperimentExecutionTicket = issuer.RetrieveTicket( opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION); } if (allowExperimentExecutionTicket == null) { // Try for a reservation int ussId = issuer.FindProcessAgentIdForClient(lc.clientID, ProcessAgentType.SCHEDULING_SERVER); if (ussId > 0) { ProcessAgent uss = issuer.GetProcessAgent(ussId); // check for current reservation //create a collection & redeemTicket string redeemPayload = TicketLoadFactory.Instance().createRedeemReservationPayload(DateTime.UtcNow, DateTime.UtcNow, Session["UserName"].ToString(), Convert.ToInt32(Session["UserID"]), groupName, lc.clientGuid); if (opCoupon == null) opCoupon = issuer.CreateCoupon(); issuer.AddTicket(opCoupon, TicketTypes.REDEEM_RESERVATION, uss.agentGuid, ProcessAgentDB.ServiceGuid, 600, redeemPayload); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); OperationAuthHeader op = new OperationAuthHeader(); op.coupon = opCoupon; ussProxy.Url = uss.webServiceUrl; ussProxy.OperationAuthHeaderValue = op; Reservation reservation = ussProxy.RedeemReservation(ProcessAgentDB.ServiceGuid, Session["UserName"].ToString(), labServer.agentGuid, lc.clientGuid); if (reservation != null) { // Find efective group setEffectiveGroup(groupID, lc.clientID); // create the allowExecution Ticket DateTime start = reservation.Start; long duration = reservation.Duration; string payload = TicketLoadFactory.Instance().createAllowExperimentExecutionPayload( start, duration, effectiveGroupName,lc.clientGuid); DateTime tmpTime = start.AddTicks(duration * TimeSpan.TicksPerSecond); DateTime utcNow = DateTime.UtcNow; long ticketDuration = (tmpTime.Ticks - utcNow.Ticks) / TimeSpan.TicksPerSecond; allowExperimentExecutionTicket = issuer.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); Session["StartExecution"] = DateUtil.ToUtcString(startExecution); Session["Duration"] = duration; // Display reenter button if experiment is reentrant & a current experiment exists if (lc.IsReentrant) { long[] ids = InternalDataDB.RetrieveActiveExperimentIDs(Convert.ToInt32(Session["UserID"]), effectiveGroupID, labServer.agentId, lc.clientID); if (ids.Length > 0) { btnLaunchLab.Text = "Launch New Experiment"; btnLaunchLab.OnClientClick = "javascript:return confirm('Are you sure you want to start a new experiment?\\n If you proceed the currently running experimnent will be closed.');"; btnLaunchLab.Visible = true; pLaunch.Visible = true; pReenter.Visible = true; btnReenter.Visible = true; btnReenter.CommandArgument = ids[0].ToString(); } else { //pReenter.Visible = false; //btnReenter.Visible = false; btnLaunchLab.Text = "Launch Lab"; btnLaunchLab.OnClientClick=""; if (autoLaunch) { launchLabClient(lc.clientID); } else { pLaunch.Visible = true; btnLaunchLab.Visible = true; } } } else { pLaunch.Visible = true; btnLaunchLab.Visible = true; btnLaunchLab.OnClientClick = ""; if (autoLaunch) { launchLabClient(lc.clientID); } } } else { pLaunch.Visible = false; btnLaunchLab.Visible = false; } } else { pLaunch.Visible = true; btnLaunchLab.Visible = true; if (autoLaunch) { launchLabClient(lc.clientID); } } } else if (lc.clientType == LabClient.BATCH_APPLET || lc.clientType == LabClient.BATCH_HTML_REDIRECT) { pLaunch.Visible = true; btnLaunchLab.Visible = true; if (autoLaunch) { launchLabClient(lc.clientID); } } btnSchedule.Visible = lc.needsScheduling; lblClientName.Text = lc.clientName; lblVersion.Text = lc.version; lblLongDescription.Text = lc.clientLongDescription; if (lc.notes != null && lc.notes.Length > 0) { pNotes.Visible = true; lblNotes.Text = lc.notes; } else { pNotes.Visible = false; lblNotes.Text = null; } if (lc.contactEmail != null && lc.contactEmail.Length > 0) { pEmail.Visible = true; string emailCmd = "mailto:" + lc.contactEmail; lblEmail.Text = "<a href=" + emailCmd + ">" + lc.contactEmail + "</a>"; } else { pEmail.Visible = false; lblEmail.Text = null; } if (lc.documentationURL != null && lc.documentationURL.Length > 0) { pDocURL.Visible = true; lblDocURL.Text = "<a href=" + lc.documentationURL + ">" + lc.documentationURL + "</a>"; } else { pDocURL.Visible = false; lblDocURL.Text = null; } btnLaunchLab.Command += new CommandEventHandler(this.btnLaunchLab_Click); btnLaunchLab.CommandArgument = lc.clientID.ToString(); int count = 0; if (clientInfos != null && clientInfos.Length > 0) { //repClientInfos.DataSource = clientInfos; //repClientInfos.DataBind(); foreach (ClientInfo ci in clientInfos) { System.Web.UI.WebControls.Button b = new System.Web.UI.WebControls.Button(); b.Visible = true; b.CssClass = "button"; b.Text = ci.infoURLName; b.CommandArgument = ci.infoURL; b.CommandName = ci.infoURLName; b.ToolTip = ci.description; b.Command += new CommandEventHandler(this.HelpButton_Click); repClientInfos.Controls.Add(b); repClientInfos.Controls.Add(new LiteralControl(" ")); } } } else { // No LabClient btnSchedule.Visible = false; pLaunch.Visible = false; btnLaunchLab.Visible = false; string msg = "There are no labs assigned to group: " + Session["GroupName"].ToString() + "!"; lblResponse.Text = Utilities.FormatErrorMessage(msg); lblResponse.Visible = true; } // System_Messages block SystemMessage[] groupMessages = null; SystemMessage[] serverMessages = null; groupMessages = AdministrativeAPI.SelectSystemMessagesForGroup(Convert.ToInt32(Session["GroupID"])); if (lc != null && labServer != null && labServer.agentId > 0) { serverMessages = wrapper.GetSystemMessagesWrapper(SystemMessage.LAB, 0, 0, labServer.agentId); } if ((groupMessages == null || groupMessages.Length == 0) && (serverMessages == null || serverMessages.Length == 0)) { lblGroupNameSystemMessage.Text = "No Messages at this time!"; lblGroupNameSystemMessage.Visible = true; lblServerSystemMessage.Visible = false; } else { if (groupMessages != null && groupMessages.Length > 0) { lblGroupNameSystemMessage.Text = "Group Messages:"; lblGroupNameSystemMessage.Visible = true; repGroupMessage.DataSource = groupMessages; repGroupMessage.DataBind(); } else { lblGroupNameSystemMessage.Visible = false; } if (serverMessages != null && serverMessages.Length > 0) { lblServerSystemMessage.Text = "Client/Server Messages:"; lblServerSystemMessage.Visible = true; repServerMessage.DataSource = serverMessages; repServerMessage.DataBind(); } else { lblServerSystemMessage.Visible = false; } } }
///// <summary> ///// Save Button. ///// </summary> ///// <param name="sender"></param> ///// <param name="e"></param> //protected void btnSaveChanges_Click(object sender, System.EventArgs e) //{ // try // { // //Get the labClient ID from the dropdown // int lcID = Convert.ToInt32(ddlLabClient.SelectedValue); // //Get lab client information // LabClient[] clients = wrapper.GetLabClientsWrapper(new int[]{lcID}); // /*Update Lab Client grants*/ // //Get qualifier for labclient // int lcQualifierID = AuthorizationAPI.GetQualifierID(lcID,Qualifier.labClientQualifierTypeID); // //Get all "uselabclient" grants for this labclient // int[] lcGrantIDs = wrapper.FindGrantsWrapper(-1,Function.useLabClientFunctionType,lcQualifierID); // Grant[] lcGrants = wrapper.GetGrantsWrapper(lcGrantIDs); // //Get list of agents that can use labclient // ArrayList lcAgents = new ArrayList(); // foreach (Grant g in lcGrants) // lcAgents.Add(g.agentID); // foreach (ListItem li in lbxAssociated.Items) // { // int groupID = Convert.ToInt32(li.Value); // //if that agent doesn't already have the uselabclient permission // if (!lcAgents.Contains(groupID)) // //add lab client grant // wrapper.AddGrantWrapper(groupID, Function.useLabClientFunctionType, lcQualifierID); // else // //otherwise just remove it from the set of agents that we need to keep track of // lcAgents.Remove(groupID); // } // //Need to delete the grant for remaining agents (since they've been removed by user!) // ArrayList grantsToBeRemoved = new ArrayList(); // foreach (Grant g in lcGrants) // if (lcAgents.Contains(g.agentID)) // grantsToBeRemoved.Add(g.grantID); // /*Update Lab Servers grant*/ // //Update grants for each of the associated lab servers // foreach (int lsID in clients[0].labServerIDs) // { // //Get qualifier for labserver // int lsQualifierID = AuthorizationAPI.GetQualifierID(lsID,Qualifier.labServerQualifierTypeID); // //Get all "uselabserver" grants for this labserver // int[] lsGrantIDs = wrapper.FindGrantsWrapper(-1,Function.useLabServerFunctionType,lsQualifierID); // Grant[] lsGrants = wrapper.GetGrantsWrapper(lsGrantIDs); // //Get list of agents that can use labserver // ArrayList lsAgents = new ArrayList(); // foreach (Grant g in lsGrants) // lsAgents.Add(g.agentID); // foreach (ListItem li in lbxAssociated.Items) // { // int groupID = Convert.ToInt32(li.Value); // //if that agent doesn't already have the uselabclient permission // if (!lsAgents.Contains(groupID)) // //add lab server grant // wrapper.AddGrantWrapper(groupID, Function.useLabServerFunctionType, lsQualifierID); // else // //otherwise just remove it from the set of agents that we need to keep track of // lsAgents.Remove(groupID); // } // //Need to delete the grant for remaining agents (since they've been removed by user!) // foreach (Grant g in lsGrants) // if (lsAgents.Contains(g.agentID)) // grantsToBeRemoved.Add(g.grantID); // } // //Delete All Grants that neeed to be removed // wrapper.RemoveGrantsWrapper(Utilities.ArrayListToIntArray(grantsToBeRemoved)); // LoadListBoxes(); // lblResponse.Visible = true; // lblResponse.Text = Utilities.FormatConfirmationMessage("Lab client (& corresponding lab servers) successfully updated. "); // } // catch (Exception ex) // { // lblResponse.Visible = true; // lblResponse.Text = Utilities.FormatErrorMessage("Cannot update Lab Client. " + ex.GetBaseException()); // } //} // Save Button protected void repAdminUserGroups_ItemCommand(object source, RepeaterCommandEventArgs e) { //RefreshAdminUserGroupsRepeater(); //adminGroupUserList = GetGroupManagerUserMaps(); int labServerID = 0; try{ if (e.CommandName.Equals("Remove")) { //example:issuer.DeleteAdminURL(Int32.Parse(e.CommandArgument.ToString())) GroupManagerUserMap gm = GroupManagerUserMap.Parse(e.CommandArgument.ToString()); int userGroupID = wrapper.GetGroupIDWrapper(gm.UserGroupName); string clientFunction = Function.useLabClientFunctionType; string labFunction = Function.useLabServerFunctionType; if (theClient.clientID > 0) { if (theClient.needsScheduling) { ProcessAgentInfo[] labServers = AdministrativeAPI.GetLabServersForClient(theClient.clientID); if (labServers != null && labServers.Length > 0 && labServers[0].agentId > 0) { int lssID = ResourceMapManager.FindResourceProcessAgentID(ResourceMappingTypes.PROCESS_AGENT, labServers[0].agentId, ProcessAgentType.LAB_SCHEDULING_SERVER); ProcessAgentInfo lss = issuer.GetProcessAgentInfo(lssID); int ussID = ResourceMapManager.FindResourceProcessAgentID(ResourceMappingTypes.CLIENT, theClient.clientID, ProcessAgentType.SCHEDULING_SERVER); if (ussID > 0) { ProcessAgentInfo uss = issuer.GetProcessAgentInfo(ussID); string payload = TicketLoadFactory.Instance().createRevokeReservationPayload("ISB"); Coupon revokeCoupon = issuer.CreateTicket(TicketTypes.REVOKE_RESERVATION, uss.agentGuid, ProcessAgentDB.ServiceGuid, 600, payload); string payload2 = TicketLoadFactory.Instance().createRevokeReservationPayload("ISB"); issuer.AddTicket(revokeCoupon, TicketTypes.REVOKE_RESERVATION, lss.AgentGuid, uss.agentGuid, 600, payload2); UserSchedulingProxy ussProxy = new UserSchedulingProxy(); ussProxy.OperationAuthHeaderValue = new OperationAuthHeader(); ussProxy.OperationAuthHeaderValue.coupon = revokeCoupon; ussProxy.Url = uss.webServiceUrl; int status = ussProxy.RevokeReservation(ProcessAgentDB.ServiceGuid, gm.UserGroupName, labServers[0].AgentGuid, theClient.clientGuid, DateTime.UtcNow, DateTime.MaxValue,"Your group no longer has permission to use the experiment!"); } } } //If there is a USS Manager Group if(gm.GrantID > 0 && gm.ResourceMappingID >0){ wrapper.RemoveGrantsWrapper(new int[] { gm.GrantID }); //delete Resource Mapping [User Group] <-> [USS] issuer.DeleteResourceMapping(gm.ResourceMappingID); } // End is a USS Manager Group //delete the Grant [User Group] -> USE LAB CLIENT -> lab client int clientQualifierID = AuthorizationAPI.GetQualifierID(theClient.clientID, Qualifier.labClientQualifierTypeID); if (clientQualifierID > 0) { int [] clientGrants = wrapper.FindGrantsWrapper(userGroupID, clientFunction, clientQualifierID); if((clientGrants != null) && (clientGrants.Length >0) && (clientGrants[0] > 0)){ wrapper.RemoveGrantsWrapper(new int[] { clientGrants[0] }); } int[] labServerIDs = AdministrativeAPI.GetLabServerIDsForClient(theClient.clientID); if ((labServerIDs != null) && (labServerIDs.Length > 0) && (labServerIDs[0] > 0)) { labServerID = labServerIDs[0]; int remainingClients = AdministrativeAPI.CountServerClients(userGroupID, labServerID); if (remainingClients == 0) { //delete the Grant [User Group] -> USE LAB SERVER -> lab Server int labQualifierID = AuthorizationAPI.GetQualifierID(labServerID, Qualifier.labServerQualifierTypeID); if (labQualifierID > 0) { int [] labGrants = (wrapper.FindGrantsWrapper(userGroupID, labFunction, labQualifierID)); if((labGrants != null) && (labGrants.Length >0) && (labGrants[0] > 0)) wrapper.RemoveGrantsWrapper(new int[] { labGrants[0] }); } } } } } RefreshAdminUserGroupsRepeater(); LoadListBoxes(); } } catch (Exception exc) { lblResponse.Visible = true; lblResponse.Text = Utilities.FormatErrorMessage("Cannot Remove User Group. " + exc.GetBaseException()); Logger.WriteLine(exc.Message); } }