예제 #1
0
        /// <summary>
        /// Parses the appInfo and experiment ticket, inserts the task into the database and
        /// creates a dataManager and dataSources defined in the appInfo.
        /// </summary>
        /// <param name="appInfo"></param>
        /// <param name="expCoupon"></param>
        /// <param name="expTicket"></param>
        /// <returns></returns>
        public virtual LabTask CreateLabTask(LabAppInfo appInfo, Coupon expCoupon, Ticket expTicket)
        {
            LabTask labTask = CreateLabTask(appInfo, expTicket);

            if (((labTask.storage != null) && (labTask.storage.Length > 0)))
            {
                // Create DataSourceManager to manage dataSources
                DataSourceManager dsManager = new DataSourceManager();

                // set up an experiment storage handler
                ExperimentStorageProxy ess = new ExperimentStorageProxy();
                ess.OperationAuthHeaderValue = new OperationAuthHeader();
                ess.OperationAuthHeaderValue.coupon = expCoupon;
                ess.Url = labTask.storage;
                dsManager.essProxy = ess;
                dsManager.ExperimentID = labTask.experimentID;
                dsManager.AppKey = appInfo.appKey;
                // Note these dataSources are written to by the application and sent to the ESS
                if ((appInfo.dataSources != null) && (appInfo.dataSources.Length > 0))
                {
                    string[] sources = appInfo.dataSources.Split(',');
                    // Use the experimentID as the storage parameter
                    foreach (string s in sources)
                    {
                       // dsManager.AddDataSource(createDataSource(s));
                    }
                }
                TaskProcessor.Instance.AddDataManager(labTask.taskID, dsManager);
            }
            TaskProcessor.Instance.Add(labTask);
            return labTask;
        }
 /// <summary>
 /// Deletes a single experiment, checks for ESS, deletes from the ESS if needed, deletes Qualifier and the experiment administrative info.
 /// This does not check for authorization the experiment ID should be authorized for deletion before this is called.
 /// </summary>
 /// <param name="experimentID"></param>
 /// <returns></returns>
 public static bool DeleteExperiment(long experimentID)
 {
     bool deleted = false;
      ExperimentSummary summary = InternalDataDB.SelectExperimentSummary(experimentID);
      if (summary.HasEss)
      {
          ProcessAgentDB ticketing = new ProcessAgentDB();
          // Retrieve the ESS Status info and update as needed
          //This uses a generic ReadRecords ticket created for the ESS
          ProcessAgentInfo ess = ticketing.GetProcessAgentInfo(summary.essGuid);
          if ((ess != null) && !ess.retired)
          {
              ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
              essProxy.Url = ess.webServiceUrl;
              essProxy.AgentAuthHeaderValue = new AgentAuthHeader();
              essProxy.AgentAuthHeaderValue.coupon = ess.identOut;
              essProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
              essProxy.DeleteExperiment(experimentID);
          }
      }
     int qualID = Authorization.AuthorizationAPI.GetQualifierID((int)experimentID, Qualifier.experimentQualifierTypeID);
     if (qualID > 0)
         Authorization.AuthorizationAPI.RemoveQualifiers(new int[] { qualID });
     deleted = InternalDataDB.DeleteExperiment(experimentID);
     return deleted;
 }
예제 #3
0
        // Create DataSourceManager to manage dataSources
        public DataSourceManager CreateDataSourceManager(LabTask task, Coupon expCoupon)
        {
            DataSourceManager dsManager = new DataSourceManager();

                // set up an experiment storage handler
                ExperimentStorageProxy ess = new ExperimentStorageProxy();
                ess.OperationAuthHeaderValue = new OperationAuthHeader();
                ess.OperationAuthHeaderValue.coupon = expCoupon;
                ess.Url = task.storage;
                dsManager.essProxy = ess;
                dsManager.ExperimentID = task.experimentID;
                //dsManager.AppKey = task.labAppID.;
                return dsManager;
        }
        protected void goButton_Click(object sender, System.EventArgs e)
        {
            LabDB labDB = new LabDB();

            // Update Task data for graph page. Note XmlQueryDocs are read-only
            LabTask task = labDB.GetTask(Convert.ToInt64(hdnExpId.Value), Session["opIssuer"].ToString());
            if (task != null)
            {
                Coupon opCoupon = new Coupon(task.issuerGUID, task.couponID, Session["opPasscode"].ToString());
               ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
               essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
               essProxy.OperationAuthHeaderValue.coupon = opCoupon;
               essProxy.Url = task.storage;
               essProxy.AddRecord(task.experimentID, "BEElab", "profile", false, hdnProfile.Value, null);
               essProxy.AddRecord(task.experimentID, "BEElab", "climateProfile", false, hdnClimateProfile.Value, null);
               essProxy.AddRecord(task.experimentID, "BEElab", "sunLamp", false, hdnSunLamp.Value, null);

               // send The CR1000 programs
               sendProfile(ConfigurationManager.AppSettings["climateController"],
                   hdnProfile.Value, hdnSunProfile, ConfigurationManager.AppSettings["climateServer"]);
               sendFile(ConfigurationManager.AppSettings["chamberController"],
                  ConfigurationManager.AppSettings["chamberFile"],
                  ConfigurationManager.AppSettings["chamberServer"]);
                StringBuilder buf = new StringBuilder("BEEgraph.aspx?expid=");

                sendEwsCientProfile(hdnClientProfile.Value,hdnExpLength.Value);
                buf.Append(task.experimentID);
                task.Status = LabTask.eStatus.Running;
                TaskProcessor.Instance.Modify(task);
                labDB.SetTaskStatus(task.taskID, (int) LabTask.eStatus.Running);
                Session["opCouponID"] = hdnCoupon.Value;
                Session["opIssuer"] = hdnIssuer.Value;
                Session["opPasscode"] = hdnPasscode.Value;
                Response.Redirect(buf.ToString(), true);
            }
            else
            {
                throw new Exception("Task was not found.");
            }
        }
 public DataSourceManager(LabTask task)
     : this()
 {
     taskID = task.taskID;
     experimentID = task.experimentID;
     if (task.storage != null && task.storage.Length > 0)
     {
         LabDB labDB = new LabDB();
         Coupon expCoupon = labDB.GetCoupon(task.couponID, task.issuerGUID);
         if (expCoupon != null)
         {
             essProxy = new ExperimentStorageProxy();
             essProxy.Url = task.storage;
             essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
             essProxy.OperationAuthHeaderValue.coupon = expCoupon;
         }
         else
             throw new Exception("ExpCoupon not found");
     }
     else
      throw new Exception("ESS is not specified");
 }
예제 #6
0
        /// <summary>
        /// Retrieves an experiment's ResultReport from the ESS
        /// </summary>
        /// <param name="experimentID"></param>
        /// <param name="roles"></param>
        /// <returns>THe ResultStatus or an empty report with status set, when the experiment has not terminated that have not</returns>
        public static ResultReport GetResultReport(int experimentID)
        {
            ResultReport report = null;
            BrokerDB brokerDB = new BrokerDB();
            try
            {
                ExperimentAdminInfo expInfo = InternalDataDB.SelectExperimentAdminInfo(experimentID);
                if (expInfo == null || expInfo.experimentID <= 0)
                {
                    //experiment does not exist
                    throw new SoapException("Invalid experiment ID. ", SoapException.ServerFaultCode);
                }
                else
                {
                    ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo(expInfo.essID);
                    if(ess.retired){
                        throw new Exception("The requested ESS has been retired");
                    }
                    ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                    essProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                    essProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                    essProxy.AgentAuthHeaderValue.coupon = ess.identOut;
                    essProxy.Url = ess.webServiceUrl;

                    Coupon opCoupon = brokerDB.GetEssOpCoupon(expInfo.experimentID, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid);
                    OperationAuthHeader opHeader = new OperationAuthHeader();
                    opHeader.coupon = opCoupon;
                    essProxy.OperationAuthHeaderValue = opHeader;
                    if ((expInfo.status & StorageStatus.CLOSED) == 0)
                    {
                        ProcessAgentInfo lsInfo = brokerDB.GetProcessAgentInfo(expInfo.agentID);
                        if (lsInfo != null)
                        {
                            if(lsInfo.retired){
                                throw new Exception("The requested batch LabServer has ben retired.");
                            }
                            BatchLSProxy batchLS_Proxy = new BatchLSProxy();
                            batchLS_Proxy.AuthHeaderValue = new AuthHeader();
                            batchLS_Proxy.AuthHeaderValue.identifier = ProcessAgentDB.ServiceGuid;
                            batchLS_Proxy.AuthHeaderValue.passKey = lsInfo.identOut.passkey;
                            batchLS_Proxy.Url = lsInfo.webServiceUrl;
                            // retrieve resultReport from labServer

                            LabExperimentStatus expStatus = batchLS_Proxy.GetExperimentStatus(experimentID);
                            if (expStatus != null)
                            {
                                if ((expStatus.statusReport.statusCode >= 3) && (expStatus.statusReport.statusCode != 6))
                                {
                                    report = batchLS_Proxy.RetrieveResult(experimentID);
                                        if (report != null)
                                        {
                                            ExperimentRecord theRecord = null;
                                            List<ExperimentRecord> recordList = new List<ExperimentRecord>();
                                            if (report.experimentResults != null && report.experimentResults.Length > 0)
                                            {
                                                theRecord = new ExperimentRecord();
                                                theRecord.submitter = lsInfo.agentGuid;
                                                theRecord.type = BatchRecordType.RESULT;
                                                theRecord.contents = report.experimentResults;
                                                theRecord.xmlSearchable = false;
                                                recordList.Add(theRecord);
                                            }
                                            if (report.errorMessage != null && report.errorMessage.Length > 0)
                                            {
                                                theRecord = new ExperimentRecord();
                                                theRecord.submitter = lsInfo.agentGuid;
                                                theRecord.type = BatchRecordType.EXECUTION_ERROR;
                                                theRecord.contents = report.errorMessage;
                                                theRecord.xmlSearchable = false;
                                                recordList.Add(theRecord);
                                            }
                                            if (report.warningMessages != null && report.warningMessages.Length > 0)
                                            {
                                                foreach (string s in report.warningMessages)
                                                {
                                                    if (s.Length > 0)
                                                    {
                                                        theRecord = new ExperimentRecord();
                                                        theRecord.submitter = lsInfo.agentGuid;
                                                        theRecord.type = BatchRecordType.EXECUTION_WARNING;
                                                        theRecord.contents = s;
                                                        theRecord.xmlSearchable = false;
                                                        recordList.Add(theRecord);
                                                    }
                                                }
                                            }
                                            if (report.xmlResultExtension != null && report.xmlResultExtension.Length > 0)
                                            {
                                                theRecord = new ExperimentRecord();
                                                theRecord.submitter = lsInfo.agentGuid;
                                                theRecord.type = BatchRecordType.RESULT_EXTENSION;
                                                theRecord.contents = report.xmlResultExtension;
                                                theRecord.xmlSearchable = true;
                                                recordList.Add(theRecord);
                                            }
                                            if (report.xmlBlobExtension != null && report.xmlBlobExtension.Length > 0)
                                            {
                                                theRecord = new ExperimentRecord();
                                                theRecord.submitter = lsInfo.agentGuid;
                                                theRecord.type = BatchRecordType.BLOB_EXTENSION;
                                                theRecord.contents = report.xmlBlobExtension;
                                                theRecord.xmlSearchable = true;
                                                recordList.Add(theRecord);
                                            }
                                            if (recordList.Count > 0)
                                            {
                                                essProxy.AddRecords(experimentID, recordList.ToArray());
                                            }
                                            StorageStatus sStatus = essProxy.SetExperimentStatus(experimentID, report.statusCode | StorageStatus.CLOSED);
                                            DataStorageAPI.UpdateExperimentStatus(sStatus);
                                        }
                                    }
                                }

                        }
                    }
                    else
                    {
                        report = new ResultReport();
                        ExperimentRecord[] records = essProxy.GetRecords(experimentID, null);
                        if (records != null)
                        {
                            List<String> execWarnings = new List<String>();
                            foreach (ExperimentRecord rec in records)
                            {
                                if (rec.type.CompareTo(BatchRecordType.EXECUTION_ERROR) == 0)
                                {
                                    report.errorMessage = rec.contents;
                                }

                                else if (rec.type.CompareTo(BatchRecordType.BLOB_EXTENSION) == 0)
                                {
                                    report.xmlBlobExtension = rec.contents;
                                }
                                else if (rec.type.CompareTo(BatchRecordType.RESULT_EXTENSION) == 0)
                                {
                                    report.xmlResultExtension = rec.contents;
                                }
                                else if (rec.type.CompareTo(BatchRecordType.EXECUTION_WARNING) == 0)
                                {
                                    execWarnings.Add(rec.contents);
                                }
                                else if (rec.type.CompareTo(BatchRecordType.RESULT) == 0)
                                {
                                    report.experimentResults = rec.contents;
                                }

                            }
                            if (execWarnings.Count > 0)
                            {
                                report.warningMessages = execWarnings.ToArray();
                            }
                        }
                        report.statusCode = expInfo.status & StorageStatus.BATCH_MASK;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SoapException(ex.Message + ". " + ex.GetBaseException(), SoapException.ServerFaultCode, ex);
            }
            return report;
        }
		protected void lbxSelectExperiment_SelectedIndexChanged(object sender, System.EventArgs e)
		{

            clearExperimentDisplay();
			try
			{
				ExperimentSummary[] expInfo = wrapper.GetExperimentSummaryWrapper (new long[] {Int64.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value)});
			
				if(expInfo[0] != null)
				{
                    if( expInfo[0].essGuid != null){
                        int expStatus = expInfo[0].status;
                        if ((expStatus == StorageStatus.UNKNOWN || expStatus == StorageStatus.INITIALIZED
                        || expStatus == StorageStatus.OPEN || expStatus == StorageStatus.REOPENED
                        || expStatus == StorageStatus.RUNNING
                        || expStatus == StorageStatus.BATCH_QUEUED || expStatus == StorageStatus.BATCH_RUNNING
                        || expStatus == StorageStatus.BATCH_TERMINATED || expStatus == StorageStatus.BATCH_TERMINATED_ERROR))
                        {

                            // This operation should happen within the Wrapper
                            BrokerDB ticketIssuer = new BrokerDB();
                            ProcessAgentInfo ess = ticketIssuer.GetProcessAgentInfo(expInfo[0].essGuid);
                            if (ess.retired)
                            {
                                throw new Exception("The experiments ESS has been retired");
                            }
                            Coupon opCoupon = ticketIssuer.GetEssOpCoupon(expInfo[0].experimentId, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid);
                            if (opCoupon != null)
                            {

                                ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                                OperationAuthHeader header = new OperationAuthHeader();
                                header.coupon = opCoupon;
                                essProxy.Url = ess.webServiceUrl;
                                essProxy.OperationAuthHeaderValue = header;

                                StorageStatus curStatus = essProxy.GetExperimentStatus(expInfo[0].experimentId);
                                if (expInfo[0].status != curStatus.status || expInfo[0].recordCount != curStatus.recordCount
                                    || expInfo[0].closeTime != curStatus.closeTime)
                                {
                                    DataStorageAPI.UpdateExperimentStatus(curStatus);
                                    expInfo[0].status = curStatus.status;
                                    expInfo[0].recordCount = curStatus.recordCount;
                                    expInfo[0].closeTime = curStatus.closeTime;

                                }
                            }
                        }

                    }
					txtExperimentID.Text = expInfo[0].experimentId.ToString () ;
					txtUserName1.Text = expInfo[0].userName ;
					txtLabServerName.Text =expInfo[0].labServerName;
                    txtClientName.Text = expInfo[0].clientName;
					txtGroupName1.Text = expInfo[0].groupName;

                    txtStatus.Text = DataStorageAPI.getStatusString(expInfo[0].status);
					txtSubmissionTime.Text = DateUtil.ToUserTime(expInfo[0].creationTime,culture,userTZ);
                    if ((expInfo[0].closeTime != null) && (expInfo[0].closeTime != DateTime.MinValue))
                        txtCompletionTime.Text = DateUtil.ToUserTime(expInfo[0].closeTime, culture, userTZ);
                    else
                        txtCompletionTime.Text = "Not Closed!";
                    txtRecordCount.Text = expInfo[0].recordCount.ToString();
			
					txtAnnotation.Text = expInfo[0].annotation;
                    txtAnnotation.ReadOnly = false;

                    trShowExperiment.Visible = (expInfo[0].recordCount >0);
                    trSaveAnnotation.Visible = true;
                    trDeleteExperiment.Visible = true;

				}
			
				//txtExperimentSpecification.Text = wrapper.RetrieveExperimentSpecificationWrapper (Int32.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value));
				//txtExperimentResult.Text = wrapper.RetrieveExperimentResultWrapper (Int32.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value));
				//txtLabconfig.Text = wrapper.RetrieveLabConfigurationWrapper (Int32.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value));
			
			}
			catch(Exception ex)
			{
				lblResponse.Text ="<div class=errormessage><p>Exception: Error retrieving experiment information. "+ex.Message+"</p></div>";
				lblResponse.Visible=true;
			}
		}
예제 #8
0
        protected void lbxSelectExperiment_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            clearExperimentDisplay();
            long experimentID = Int64.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value);
            try
            {
                ExperimentSummary[] expInfo = wrapper.GetExperimentSummaryWrapper (new long[] {experimentID});
                if(expInfo[0] != null)
                {
                    txtExperimentID.Text = expInfo[0].experimentId.ToString();
                    txtUsername.Text = expInfo[0].userName ;
                    txtGroupName.Text = expInfo[0].groupName;
                    txtLabServerName.Text = expInfo[0].labServerName;
                    txtClientName.Text = expInfo[0].clientName;
                    //Check if update needed from the ESS if one is used
                    if( expInfo[0].essGuid != null){
                        int expStatus = expInfo[0].status;
                        if((expStatus == StorageStatus.UNKNOWN || expStatus == StorageStatus.INITIALIZED
                        || expStatus == StorageStatus.OPEN || expStatus == StorageStatus.REOPENED
                        ||expStatus == StorageStatus.RUNNING
                        ||expStatus == StorageStatus.BATCH_QUEUED ||expStatus == StorageStatus.BATCH_RUNNING
                        ||expStatus == StorageStatus.BATCH_TERMINATED ||expStatus == StorageStatus.BATCH_TERMINATED_ERROR))
                        {

                        // This operation should happen within the Wrapper
                        BrokerDB ticketIssuer = new BrokerDB();
                        ProcessAgentInfo ess = ticketIssuer.GetProcessAgentInfo(expInfo[0].essGuid);
                        if (ess == null || ess.retired)
                        {
                            throw new Exception("The ESS is not registered or is retired");
                        }
                        Coupon opCoupon = ticketIssuer.GetEssOpCoupon(expInfo[0].experimentId, TicketTypes.RETRIEVE_RECORDS,60,ess.agentGuid);
                        if (opCoupon != null)
                        {
                            ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                            OperationAuthHeader header = new OperationAuthHeader();
                            header.coupon = opCoupon;
                            essProxy.Url = ess.webServiceUrl;
                            essProxy.OperationAuthHeaderValue = header;

                            StorageStatus curStatus = essProxy.GetExperimentStatus(expInfo[0].experimentId);
                            if (expInfo[0].status != curStatus.status || expInfo[0].recordCount != curStatus.recordCount
                                || expInfo[0].closeTime != curStatus.closeTime)
                            {
                                DataStorageAPI.UpdateExperimentStatus(curStatus);
                                expInfo[0].status = curStatus.status;
                                expInfo[0].recordCount = curStatus.recordCount;
                                expInfo[0].closeTime = curStatus.closeTime;
                            }
                        }
                        }

                    }
                    txtStatus.Text =  DataStorageAPI.getStatusString(expInfo[0].status);
                    txtSubmissionTime.Text = DateUtil.ToUserTime(expInfo[0].creationTime,culture,userTZ);
                    if ((expInfo[0].closeTime != null) && (expInfo[0].closeTime != DateTime.MinValue))
                    {
                        txtCompletionTime.Text = DateUtil.ToUserTime(expInfo[0].closeTime, culture, userTZ);
                    }
                    else{
                        txtCompletionTime.Text = "Experiment Not Closed!";
                    }
                    txtRecordCount.Text = expInfo[0].recordCount.ToString("    0");
                    txtAnnotation.Text = expInfo[0].annotation;
                    trSaveAnnotation.Visible = true;
                    trDeleteExperiment.Visible = true;
                    trShowExperiment.Visible = (expInfo[0].recordCount > 0);
                }
            }
            catch(Exception ex)
            {
                lblResponse.Text = Utilities.FormatErrorMessage("Error retrieving experiment information. " + ex.Message);
                lblResponse.Visible = true;
            }
        }
예제 #9
0
        /// <summary>
        /// Retrive records from the experiment. It is assummed that read permissons have been checked and passed.
        /// A new coupon is created for this request.
        /// </summary>
        /// <param name="experimentID"></param>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public ExperimentRecord[] RetrieveExperimentRecords(long experimentID, Criterion[] criteria)
        {
            ExperimentRecord[] records = null;
            ProcessAgentInfo ess = GetExperimentESS(experimentID);
            if (ess != null)
            {
                ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                Coupon opCoupon = CreateCoupon();

                string payload = TicketLoadFactory.Instance().RetrieveRecordsPayload(experimentID, ess.webServiceUrl);
                opCoupon = CreateTicket(TicketTypes.RETRIEVE_RECORDS, ess.agentGuid, ProcessAgentDB.ServiceGuid,
                     60, payload);

                essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                essProxy.OperationAuthHeaderValue.coupon = opCoupon;
                essProxy.Url = ess.webServiceUrl;
                records = essProxy.GetRecords(experimentID, criteria);
            }
            return records;
        }
        public LabTask CreateLabTask(LabAppInfo appInfo, Coupon expCoupon, Ticket expTicket)
        {
            // set defaults
            DateTime startTime = DateTime.UtcNow;
            long duration = -1L;
            long experimentID = 0;
            int status = -1;

            string statusViName = null;
            string statusTemplate = null;
            string templatePath = null;
            LabDB dbManager = new LabDB();
            string qualName = null;
            string fullName = null;  // set defaults
            string viName = null;

            //CHeck that a labVIEW interface revision is set
            //if (appInfo.rev == null || appInfo.rev.Length < 2)
            //{
            //    appInfo.rev = ConfigurationManager.AppSettings["LabViewVersion"];
            //}

            ////Parse experiment payload, only get what is needed
            string payload = expTicket.payload;
            XmlQueryDoc expDoc = new XmlQueryDoc(payload);
            string essService = expDoc.Query("ExecuteExperimentPayload/essWebAddress");
            string startStr = expDoc.Query("ExecuteExperimentPayload/startExecution");
            string durationStr = expDoc.Query("ExecuteExperimentPayload/duration");
            string groupName = expDoc.Query("ExecuteExperimentPayload/groupName");
            string userName = expDoc.Query("ExecuteExperimentPayload/userName");
            string expIDstr = expDoc.Query("ExecuteExperimentPayload/experimentID");

            if ((startStr != null) && (startStr.Length > 0))
            {
                startTime = DateUtil.ParseUtc(startStr);
            }
            if ((durationStr != null) && (durationStr.Length > 0) && !(durationStr.CompareTo("-1") == 0))
            {
                duration = Convert.ToInt64(durationStr);
            }
            if ((expIDstr != null) && (expIDstr.Length > 0))
            {
                experimentID = Convert.ToInt64(expIDstr);
            }

            if (appInfo.extraInfo != null && appInfo.extraInfo.Length > 0)
            {
                // Note should have either statusVI or template pair
                // Add Option for VNCserver access
                try
                {
                    XmlQueryDoc viDoc = new XmlQueryDoc(appInfo.extraInfo);
                    statusViName = viDoc.Query("extra/status");
                    statusTemplate = viDoc.Query("extra/statusTemplate");
                    templatePath = viDoc.Query("extra/templatePath");
                }
                catch (Exception e)
                {
                    string err = e.Message;
                }
            }

            // log the experiment for debugging

            Logger.WriteLine("Experiment: " + experimentID + " Start: " + DateUtil.ToUtcString(startTime) + " \tduration: " + duration);
            long statusSpan = DateUtil.SecondsRemaining(startTime, duration);

            if (!IsLoaded(appInfo.application))
            {
                viName = LoadVI(appInfo.path, appInfo.application);
                if (false) // Check for controls first
                {
                    string[] names = new string[4];
                    object[] values = new object[4];
                    names[0] = "CouponId";
                    values[0] = expCoupon.couponId;
                    names[1] = "Passcode";
                    values[1] = expCoupon.passkey;
                    names[2] = "IssuerGuid";
                    values[2] = expCoupon.issuerGuid;
                    names[3] = "ExperimentId";
                    values[3] = experimentID;
                    SetControlValues(viName, names, values);
                }
                OpenFrontPanel(viName, true, LabViewTypes.eFPState.eVisible);
            }
            else
            {
                viName = LoadVI(appInfo.path, appInfo.application);
            }
            if (viName == null)
            {
                status = -1;
                string err = "Unable to Find: " + appInfo.path + @"\" + appInfo.application;
                Logger.WriteLine(err);
                throw new Exception(err);
            }
            // Get qualifiedName
            qualName = qualifiedName(viName);
            fullName = appInfo.path + @"\" + appInfo.application;

            status = GetVIStatus(viName);

            Logger.WriteLine("CreateLabTask - " + qualName + ": VIstatus: " + status);
            switch (status)
            {
                case -10:
                    throw new Exception("Error GetVIStatus: " + status);
                    break;
                case -1:
                    // VI not in memory
                    throw new Exception("Error GetVIStatus: " + status);

                    break;
                case 0: // eBad == 0
                    break;
                case 1: // eIdle == 1 vi in memory but not running
                    //LabViewTypes.eFPState fpState = GetFPStatus(viName);
                   //if (fpState != LabViewTypes.eFPState.eVisible)
                    //{
                        OpenFrontPanel(viName, true, LabViewTypes.eFPState.eVisible);
                    //}
                    ResetVI(viName);
                    break;
                case 2: // eRunTopLevel: this should be the LabVIEW application
                    break;
                case 3: // eRunning
                    //Unless the Experiment is reentrant it should be stopped and be reset.
                    if (!appInfo.reentrant)
                    {
                        int stopStatus = StopVI(viName);
                        if (stopStatus != 0)
                        {
                            AbortVI(viName);
                        }
                        ResetVI(viName);
                    }
                    break;
                default:
                    throw new Exception("Error GetVIStatus: unknown status: " + status);
                    break;
            }
            try
            {
                SetBounds(viName, 0, 0, appInfo.width, appInfo.height);
                Logger.WriteLine("SetBounds: " + appInfo.application);
            }
            catch (Exception sbe)
            {
                Logger.WriteLine("SetBounds exception: " + Utilities.DumpException(sbe));
            }
            SubmitAction("unlockvi", qualifiedName(viName));
            Logger.WriteLine("unlockvi Called: ");

            // Create the labTask & store in database;
            LabViewTask task = new LabViewTask();
            task.labAppID = appInfo.appID;
            task.experimentID = experimentID;
            task.groupName = groupName;
            task.startTime = startTime;
            if (duration > 0)
                task.endTime = startTime.AddTicks(duration * TimeSpan.TicksPerSecond);
            else
                task.endTime = DateTime.MinValue;
            task.Status = LabTask.eStatus.Scheduled;
            task.couponID = expTicket.couponId;
            task.storage = essService;
            task.data = task.constructTaskXml(appInfo.appID, fullName, appInfo.rev, statusViName, essService);
            long taskID = dbManager.InsertTaskLong(task);
            task.taskID = taskID;

            if ((statusTemplate != null) && (statusTemplate.Length > 0))
            {
                statusViName = CreateFromTemplate(templatePath, statusTemplate, task.taskID.ToString());
            }

            if (((essService != null) && (essService.Length > 0)))
            {
                // Create DataSourceManager to manage dataSocket connections
                DataSourceManager dsManager = new DataSourceManager();

                // set up an experiment storage handler
                ExperimentStorageProxy ess = new ExperimentStorageProxy();
                ess.OperationAuthHeaderValue = new OperationAuthHeader();
                ess.OperationAuthHeaderValue.coupon = expCoupon;
                ess.Url = essService;
                dsManager.essProxy = ess;
                dsManager.ExperimentID = experimentID;
                dsManager.AppKey = qualName;
                // Note these dataSources are written to by the application and sent to the ESS
                if ((appInfo.dataSources != null) && (appInfo.dataSources.Length > 0))
                {
                    string[] sockets = appInfo.dataSources.Split(',');
                    // Use the experimentID as the storage parameter
                    foreach (string s in sockets)
                    {
                        LVDataSocket reader = new LVDataSocket();
                        dsManager.AddDataSource(reader);
                        if (s.Contains("="))
                        {
                            string[] nv = s.Split('=');
                            reader.Type = nv[1];
                            reader.Connect(nv[0], LabDataSource.READ_AUTOUPDATE);

                        }
                        else
                        {
                            reader.Connect(s, LabDataSource.READ_AUTOUPDATE);
                        }
                    }
                }
                TaskProcessor.Instance.AddDataManager(task.taskID, dsManager);
            }

            TaskProcessor.Instance.Add(task);
            return task;
        }
예제 #11
0
        protected void displayRecords(long experimentId, string essGuid)
        {
            BrokerDB ticketIssuer = new BrokerDB();
            ProcessAgentInfo ess = ticketIssuer.GetProcessAgentInfo(essGuid);
            if (ess == null || ess.retired)
            {
                throw new Exception("The ESS is not registered or is retired");
            }
            Coupon opCoupon = ticketIssuer.GetEssOpCoupon(experimentId, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid);
            if (opCoupon != null)
            {

                ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                OperationAuthHeader header = new OperationAuthHeader();
                header.coupon = opCoupon;
                essProxy.Url = ess.webServiceUrl;
                essProxy.OperationAuthHeaderValue = header;

                ExperimentRecord[] records = essProxy.GetRecords(experimentId,null);
                if (records != null)
                {

                    StringBuilder buf = null;
                    if (cbxContents.Checked)
                    {
                        buf = new StringBuilder();
                        foreach (ExperimentRecord rec in records)
                        {
                            buf.AppendLine(rec.contents);
                        }
                        txtExperimentRecords.Text = buf.ToString();
                        txtExperimentRecords.Visible = true;
                        grvExperimentRecords.Visible = false;
                    }
                    else
                    {
                        dtRecords = new DataTable();
                        dtRecords.Columns.Add("Seq_Num", typeof(System.Int32));
                        dtRecords.Columns.Add("Record Type", typeof(System.String));
                        dtRecords.Columns.Add("Contents", typeof(System.String));
                        foreach (ExperimentRecord rec in records)
                        {
                            DataRow recTmp = dtRecords.NewRow();
                            recTmp["Seq_Num"] = rec.sequenceNum;
                            recTmp["Record Type"] = rec.type;
                            recTmp["Contents"] = rec.contents;
                            dtRecords.Rows.InsertAt(recTmp, dtRecords.Rows.Count);
                        }
                        grvExperimentRecords.DataSource = dtRecords;

                        grvExperimentRecords.DataBind();
                        grvExperimentRecords.Visible = true;
                        txtExperimentRecords.Visible = false;

                    }

                    divRecords.Visible = true;
                }
                Blob[] blobs = essProxy.GetBlobs(experimentId);
                if (blobs != null)
                {

                    dtBlobs = new DataTable();
                    dtBlobs.Columns.Add("Blob_ID", typeof(System.Int64));
                    dtBlobs.Columns.Add("Seq_Num", typeof(System.Int32));
                    dtBlobs.Columns.Add("MimeType", typeof(System.String));
                    dtBlobs.Columns.Add("Description", typeof(System.String));
                    foreach (Blob b in blobs)
                    {
                        DataRow blobTmp = dtBlobs.NewRow();
                        blobTmp["Blob_ID"] = b.blobId;
                        blobTmp["Seq_Num"] = b.recordNumber;
                        blobTmp["MimeType"] = b.mimeType;
                        blobTmp["Description"] = b.description;
                        dtBlobs.Rows.InsertAt(blobTmp, dtBlobs.Rows.Count);
                    }
                    grvBlobs.DataSource = dtBlobs;
                    grvBlobs.DataBind();
                    divBlobs.Visible = true;

                }
            }
        }
        public StorageStatus OpenExperiment(long experimentId, long duration)
        {
            StorageStatus status = null;
            if (brokerDB.AuthenticateAgentHeader(agentAuthHeader))
            {
                Ticket essTicket = brokerDB.RetrieveTicket(opHeader.coupon, TicketTypes.ADMINISTER_EXPERIMENT);
                // Check for ESS use
                if (essTicket != null)
                {
                    XmlDocument payload = new XmlDocument();
                    payload.LoadXml(essTicket.payload);
                    string essURL = payload.GetElementsByTagName("essURL")[0].InnerText;

                    long sbExperimentId = Int64.Parse(payload.GetElementsByTagName("experimentID")[0].InnerText);
                    //

                    ExperimentAdminInfo expInfo = InternalDataDB.SelectExperimentAdminInfo(experimentId);

                    if ( expInfo.essID > 0)
                    {

                        // Retrieve the ESS Status info and update as needed
                        ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo( expInfo.essID);
                        if (ess.retired)
                        {
                            throw new Exception("The ESS is retired");
                        }
                        ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                        essProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                        essProxy.AgentAuthHeaderValue.coupon = ess.identOut;
                        essProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                        essProxy.Url = essURL;
                        status = essProxy.OpenExperiment(sbExperimentId, duration);
                    }

                    // Note: store and retrieve tickets are not cancelled.
                }
            }
            if (status != null)
            {
                DataStorageAPI.UpdateExperimentStatus(status);
            }
            return status;
        }
        public Experiment RetrieveExperiment(long experimentID)
        {
            Experiment experiment = null;
            BrokerDB brokerDB = new BrokerDB();
            int roles = 0;
            int userID = 0;
            int groupID = 0;
            //long[] expIDs = null;
            Ticket expTicket = brokerDB.RetrieveTicket(opHeader.coupon, TicketTypes.REDEEM_SESSION);
            if (expTicket != null && !expTicket.IsExpired())
            {
                //Parse payload, only get what is needed

                XmlQueryDoc expDoc = new XmlQueryDoc(expTicket.payload);
                //long expID = -1;

                string userStr = expDoc.Query("RedeemSessionPayload/userID");
                if ((userStr != null) && (userStr.Length > 0))
                    userID = Convert.ToInt32(userStr);
                string groupStr = expDoc.Query("RedeemSessionPayload/groupID");
                if ((groupStr != null) && (groupStr.Length > 0))
                    groupID = Convert.ToInt32(groupStr);

                if (userID > 0)
                {

                    AuthorizationWrapperClass wrapper = new AuthorizationWrapperClass();
                    roles = wrapper.GetExperimentAuthorizationWrapper(experimentID, userID, groupID);
                }
                if ((roles | ExperimentAccess.READ) == ExperimentAccess.READ)
                {
                    experiment = new Experiment();
                    experiment.experimentId = experimentID;
                    experiment.issuerGuid = ProcessAgentDB.ServiceGuid;
                    ProcessAgentInfo ess = brokerDB.GetExperimentESS(experimentID);
                    if (ess != null)
                    {
                        ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                        Coupon opCoupon = brokerDB.GetEssOpCoupon(experimentID, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid);
                        if (opCoupon == null)
                        {
                            string payload = TicketLoadFactory.Instance().RetrieveRecordsPayload(experimentID, ess.webServiceUrl);
                            opCoupon = brokerDB.CreateTicket(TicketTypes.RETRIEVE_RECORDS, ess.agentGuid, ProcessAgentDB.ServiceGuid,
                                60, payload);
                        }
                        essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                        essProxy.OperationAuthHeaderValue.coupon = opCoupon;
                        essProxy.Url = ess.webServiceUrl;
                        essProxy.GetRecords(experimentID, null);
                    }

                }
                else
                {
                    throw new AccessDeniedException("You do not have permission to read this experiment");
                }
            }
            return experiment;
        }
        public StorageStatus ClientCloseExperiment(long experimentId)
        {
            StorageStatus status = null;
            bool experimentClosed = false;

            //Coupon opCoupon = new Coupon(opHeader.coupon.issuerGuid, opHeader.coupon.couponId,
            //     opHeader.coupon.passkey);
            if (brokerDB.AuthenticateIssuedCoupon(opHeader.coupon))
            {
                Ticket expTicket = brokerDB.RetrieveTicket(opHeader.coupon, TicketTypes.EXECUTE_EXPERIMENT);
                if (expTicket != null)
                {
                    // Check for ESS use
                    Ticket essTicket = brokerDB.RetrieveTicket(opHeader.coupon, TicketTypes.ADMINISTER_EXPERIMENT);
                    if (essTicket != null)
                    {
                        ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo(essTicket.redeemerGuid);
                        if (ess != null)
                        {
                            if (ess.retired)
                            {
                                throw new Exception("The ProcessAgent is retired");
                            }
                            ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                            essProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                            essProxy.AgentAuthHeaderValue.coupon = ess.identOut;
                            essProxy.Url = ess.webServiceUrl;
                            status = essProxy.CloseExperiment(experimentId);
                            DataStorageAPI.UpdateExperimentStatus(status);
                        }
                        brokerDB.CancelIssuedTicket(opHeader.coupon, essTicket);
                    }
                    else
                    {
                        // Close the local Experiment records
                        // Note: store and retrieve tickets are not cancelled.
                        experimentClosed = DataStorageAPI.CloseExperiment(experimentId, StorageStatus.CLOSED_USER);
                        status = DataStorageAPI.RetrieveExperimentStatus(experimentId);
                    }

                }
            }
            return status;
        }
        public StorageStatus AgentCloseExperiment(Coupon coupon, long experimentId)
        {
            StorageStatus status = null;
            bool experimentClosed = false;

            if (brokerDB.AuthenticateAgentHeader(agentAuthHeader))
            {
                if (coupon.issuerGuid == ProcessAgentDB.ServiceGuid)
                {

                    // Check for ESS use
                    Ticket essTicket = brokerDB.RetrieveTicket(coupon, TicketTypes.ADMINISTER_EXPERIMENT);
                    if (essTicket != null)
                    {
                        ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo(essTicket.redeemerGuid);
                        if (ess != null)
                        {
                            if (ess.retired)
                            {
                                throw new Exception("The ProcessAgent is retired");
                            }
                            ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                            essProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                            essProxy.AgentAuthHeaderValue.coupon = ess.identOut;
                            essProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                            essProxy.Url = ess.webServiceUrl;
                            status = essProxy.CloseExperiment(experimentId);
                            DataStorageAPI.UpdateExperimentStatus(status);
                        }
                        brokerDB.CancelIssuedTicket(coupon, essTicket);
                    }
                    else
                    {
                        // Close the local Experiment records
                        // Note: store and retrieve tickets are not cancelled.
                        experimentClosed = DataStorageAPI.CloseExperiment(experimentId, StorageStatus.CLOSED_USER);
                        status = DataStorageAPI.RetrieveExperimentStatus(experimentId);
                    }

                }
                else
                {
                    ProcessAgentInfo paInfo = brokerDB.GetProcessAgentInfo(coupon.issuerGuid);
                    if (paInfo != null)
                    {
                        if (paInfo.retired)
                        {
                            throw new Exception("The ProcessAgent is retired");
                        }
                        InteractiveSBProxy ticketProxy = new InteractiveSBProxy();
                        AgentAuthHeader authHeader = new AgentAuthHeader();
                        authHeader.coupon = paInfo.identOut;
                        authHeader.agentGuid = ProcessAgentDB.ServiceGuid;
                        ticketProxy.AgentAuthHeaderValue = authHeader;
                        ticketProxy.Url = paInfo.webServiceUrl;
                        status = ticketProxy.AgentCloseExperiment(coupon, experimentId);
                    }
                    else
                    {
                        throw new Exception("Unknown TicketIssuerDB in RedeemTicket Request");
                    }
                }

            }
            return status;
        }
예제 #16
0
        public ClientSubmissionReport Submit(string labServerID, string experimentSpecification, int priorityHint, bool emailNotification)
        {
            // Default to 24 hours duration
            long duration = TimeSpan.TicksPerDay/TimeSpan.TicksPerSecond;
            int seqNo = 0;
            ClientSubmissionReport clientSReport = null;
            try{

                // Checking if user has permission to use the lab server. The method will set headers for lab server calls
                //if authorization is successful.
                CheckAndSetLSAuthorization(labServerID);

                //Retrieve variables from session
                int userID = Convert.ToInt32(Session["UserID"]);
                int effectiveGroupID = Convert.ToInt32(Session["GroupID"]);
                int clientID = 0;
                if (Session["ClientID"] != null )
                    clientID = Convert.ToInt32(Session["ClientID"]);
                string effectiveGroup = Session["GroupName"].ToString();

                ProcessAgentInfo infoLS = dbTicketing.GetProcessAgentInfo(labServerID);
                if (infoLS.retired)
                {
                    throw new Exception("The Batch Lab Server is retired");
                }
                // get qualifier ID of labServer
                int qualifierID = AuthorizationAPI.GetQualifierID(infoLS.agentId, Qualifier.labServerQualifierTypeID);

                /* End collecting information */

                // Checking if user has permission to use the lab server
                if (!AuthorizationAPI.CheckAuthorization(userID, Function.useLabServerFunctionType, qualifierID))
                {
                    // check fails

                    throw new AccessDeniedException("Access denied using labServer '" + infoLS.agentName + "'.");
                }
                else
                {
                    int[] groupIDs = new int[1];
                    groupIDs[0] = effectiveGroupID;

                    SubmissionReport sReport = new SubmissionReport();

                    clientSReport = new ClientSubmissionReport();
                    clientSReport.vReport = new ValidationReport();
                    clientSReport.wait = new WaitEstimate();

                    BrokerDB brokerDB = new BrokerDB();
                    // 1. Create Coupon for ExperimentCollection
                    Coupon coupon = brokerDB.CreateCoupon();

                    int essID = brokerDB.FindProcessAgentIdForClient(clientID, ProcessAgentType.EXPERIMENT_STORAGE_SERVER);
                    //
                    // 2. create ServiceBroker experiment record and get corresponding experiment id
                    // This checks authorization.
                    long experimentID = wrapper.CreateExperimentWrapper(StorageStatus.INITIALIZED, userID, effectiveGroupID, infoLS.agentId, clientID,
                        essID, DateTime.UtcNow, duration);

                    // Store a record of the Experiment Collection Coupon
                    DataStorageAPI.InsertExperimentCoupon(experimentID, coupon.couponId);

                    //3.A create ESS administer experiment ticket, Add 10 minutes to duration
                    // This must be created before the ESS experiment records may be created
                    ProcessAgentInfo essAgent = brokerDB.GetProcessAgentInfo(essID);
                    if (essAgent.retired)
                    {
                        throw new Exception("The Batch Lab Server is retired");
                    }
                    TicketLoadFactory factory = TicketLoadFactory.Instance();

                    brokerDB.AddTicket(coupon,
                           TicketTypes.ADMINISTER_EXPERIMENT, essAgent.AgentGuid, ProcessAgentDB.ServiceGuid, duration, factory.createAdministerExperimentPayload(experimentID, essAgent.webServiceUrl));

                    //3.B create store record ticket, in the MergedSB the records are all saved via the serviceBroker
                    brokerDB.AddTicket(coupon,
                           TicketTypes.STORE_RECORDS, essAgent.agentGuid, ProcessAgentDB.ServiceGuid, duration, factory.StoreRecordsPayload(true, experimentID, essAgent.webServiceUrl));

                    //3.C create retrieve experiment ticket, retrieve Experiment Records never expires, unless experiment deleted
                    //    This should be changed to a long but finite period once eadExisting Expermint is in place.
                    brokerDB.AddTicket(coupon,
                           TicketTypes.RETRIEVE_RECORDS, essAgent.agentGuid, ProcessAgentDB.ServiceGuid, -1, factory.RetrieveRecordsPayload(experimentID, essAgent.webServiceUrl));

                    // 3.D Create the ESS Experiment Records
                    ExperimentStorageProxy ess = new ExperimentStorageProxy();
                    ess.AgentAuthHeaderValue = new AgentAuthHeader();
                    ess.AgentAuthHeaderValue.coupon = essAgent.identOut;
                    ess.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                    ess.OperationAuthHeaderValue = new OperationAuthHeader();
                    ess.OperationAuthHeaderValue.coupon = coupon;
                    ess.Url = essAgent.webServiceUrl;

                    // Call the ESS to create the ESS Records and open the experiment
                    StorageStatus status = ess.OpenExperiment(experimentID, duration);
                    if (status != null)
                        DataStorageAPI.UpdateExperimentStatus(status);

                    seqNo = ess.AddRecord(experimentID, ProcessAgentDB.ServiceGuid,
                              BatchRecordType.SPECIFICATION, true, experimentSpecification, null);

                    // save lab configuration
                    string labConfiguration = batchLS_Proxy.GetLabConfiguration(effectiveGroup);
                    seqNo = ess.AddRecord(experimentID, labServerID,
                        BatchRecordType.LAB_CONFIGURATION, true, labConfiguration, null);

                    // call labServer submit
                    sReport = batchLS_Proxy.Submit(Convert.ToInt32(experimentID), experimentSpecification, effectiveGroup, priorityHint);

                    // save submission report
                    //wrapper.SaveSubmissionReportWrapper(experimentID, sReport);
                    if (sReport.vReport != null)
                        if ((sReport.vReport.errorMessage != null) && (sReport.vReport.errorMessage.CompareTo("") != 0))
                        {
                            seqNo = ess.AddRecord(experimentID, labServerID, BatchRecordType.VALIDATION_ERROR, false, sReport.vReport.errorMessage, null);

                        }

                    if (sReport.vReport.warningMessages != null)
                        foreach (string s in sReport.vReport.warningMessages)
                        {
                            if ((s != null) && (s.CompareTo("") != 0))
                                seqNo = ess.AddRecord(experimentID, labServerID, BatchRecordType.VALIDATION_WARNING, false, s, null);
                        }

                    // return clientSubmissionReport
                    if (sReport.vReport != null)
                    {
                        clientSReport.vReport.accepted = sReport.vReport.accepted;
                        clientSReport.vReport.errorMessage = sReport.vReport.errorMessage;
                        // if error exists then change status to "an experiment with a problem"
                        if ((sReport.vReport.errorMessage != null) && (!sReport.vReport.errorMessage.Equals("")))
                        {
                            StorageStatus sStatus = new StorageStatus();
                            sStatus.experimentId = experimentID;
                            //sStatus.estRuntime=sReport.vReport.estRuntime;
                            sStatus.status = StorageStatus.BATCH_TERMINATED_ERROR;
                            DataStorageAPI.UpdateExperimentStatus(sStatus);
                        }
                        clientSReport.vReport.estRuntime = sReport.vReport.estRuntime;
                        clientSReport.vReport.warningMessages = sReport.vReport.warningMessages;
                    }
                    clientSReport.experimentID = Convert.ToInt32(experimentID);
                    clientSReport.minTimeToLive = sReport.minTimetoLive;
                    if (sReport.wait != null)
                    {
                        clientSReport.wait.effectiveQueueLength = sReport.wait.effectiveQueueLength;
                        clientSReport.wait.estWait = sReport.wait.estWait;
                    }
                }

                return clientSReport;
            }

            catch
            {
                throw;
            }
        }
예제 #17
0
        public static ExperimentInformation[] GetExperimentInformation(int[] experimentIDs)
        {
            List<ExperimentInformation> list = new List<ExperimentInformation>();
            try
            {
               long[] expIDs = new long[experimentIDs.Length];
               for (int i = 0; i < experimentIDs.Length; i++)
               {
                   expIDs[i] = (long)experimentIDs[i];
               }

                ExperimentAdminInfo[] expSummaries = InternalDataDB.SelectExperimentAdminInfos(expIDs);

                if (expSummaries != null)
                    foreach (ExperimentAdminInfo expSum in expSummaries)
                    {
                        ExperimentInformation info = new ExperimentInformation();
                        info.experimentID = expSum.experimentID;
                        info.userID = expSum.userID;
                        info.effectiveGroupID = expSum.groupID;
                        info.labServerID = expSum.agentID;
                        info.statusCode = expSum.status & StorageStatus.BATCH_MASK;
                        info.submissionTime = expSum.creationTime;
                        info.completionTime = expSum.closeTime;
                        DateTime endTime = expSum.startTime.AddSeconds(expSum.duration);
                        info.expirationTime = endTime;
                        double hours = new TimeSpan(endTime.Ticks - DateTime.UtcNow.Ticks).TotalHours;
                        info.minTimeToLive = hours > 0 ? hours : 0;
                        info.annotation = expSum.annotation;

                      //Get the Experiment records from the ESS if one is used
                        if (expSum.essID > 0)
                        {

                            // This operation should happen within the Wrapper
                            BrokerDB brokerDB = new BrokerDB();
                            ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo(expSum.essID);
                            Coupon opCoupon = brokerDB.GetEssOpCoupon( expSum.experimentID, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid);

                            ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                            OperationAuthHeader header = new OperationAuthHeader();
                            header.coupon = opCoupon;
                            essProxy.Url = ess.webServiceUrl;
                            essProxy.OperationAuthHeaderValue = header;
                            Criterion errors = new Criterion("record_type", "like", "*Message");
                            Criterion extensions = new Criterion("record_type", "like", "*Extension");
                            Criterion [] criteria = new Criterion[] {errors,extensions };
                            ExperimentRecord[] records = brokerDB.RetrieveExperimentRecords(expSum.experimentID, criteria);
                            if (records != null)
                            {
                                List<String> valWarnings = new List<String>();
                                List<String> execWarnings = new List<String>();
                                foreach (ExperimentRecord rec in records)
                                {
                                    if (rec.type.CompareTo(BatchRecordType.EXECUTION_ERROR) == 0)
                                    {
                                        info.executionErrorMessage = rec.contents;
                                    }
                                    else if (rec.type.CompareTo(BatchRecordType.VALIDATION_ERROR) == 0)
                                    {
                                        info.validationErrorMessage = rec.contents;
                                    }
                                    else if (rec.type.CompareTo(BatchRecordType.BLOB_EXTENSION) == 0)
                                    {
                                        info.xmlBlobExtension = rec.contents;
                                    }
                                    else if (rec.type.CompareTo(BatchRecordType.RESULT_EXTENSION) == 0)
                                    {
                                        info.xmlResultExtension = rec.contents;
                                    }
                                    else if (rec.type.CompareTo(BatchRecordType.EXECUTION_WARNING) == 0)
                                    {
                                        execWarnings.Add(rec.contents);
                                    }
                                    else if (rec.type.CompareTo(BatchRecordType.VALIDATION_WARNING) == 0)
                                    {
                                        valWarnings.Add(rec.contents);
                                    }

                                }
                                if (execWarnings.Count > 0)
                                {
                                    info.executionWarningMessages = execWarnings.ToArray();
                                }
                                if (valWarnings.Count > 0)
                                {
                                    info.validationWarningMessages = valWarnings.ToArray();
                                }
                            }
                        }
                        list.Add(info);
                    }
            }
            catch
            {
                throw;
            }
            if (list.Count > 0)
            {
                return list.ToArray();
            }
            else
                return null;
        }
        public static long[] RetrieveAuthorizedExpIDs(int userID, int groupID, Criterion[] carray)
        {
            long[] expIDs = null;
            List<Criterion> sbList = new List<Criterion>();
            List<Criterion> essList = new List<Criterion>();

            if (carray != null && carray.Length > 0)
            {
                // Parse the criterion
                for (int i = 0; i < carray.Length; i++)
                {
                    switch (carray[i].attribute.ToLower())
                    {
                        //these criterion are based on external values, requiring special processing of the fields.
                        case "username":
                            sbList.Add(new Criterion("User_ID", carray[i].predicate,
                            "(select user_id from users where user_name=" + carray[i].value + ")"));
                            break;
                        case "groupname":
                            sbList.Add(new Criterion("Group_ID", carray[i].predicate,
                            "(select group_id from group where group_name=" + carray[i].value + ")"));
                            break;
                        case "clientname":
                            sbList.Add(new Criterion("Client_ID", carray[i].predicate,
                                "(select client_id from lab_clients where lab_client_name=" + carray[i].value + ")"));
                            break;
                        case "labservername":
                            sbList.Add(new Criterion("Agent_ID", carray[i].predicate,
                                "(select agent_id from processAgent where agent_name=" + carray[i].value + ")"));
                            break;
                        case "start":
                            sbList.Add(new Criterion("creationtime", carray[i].predicate, carray[i].value));
                            break;
                        case "agent_id":    // Actual SB experiment column names
                        case "annotation":
                        case "client_id":
                        case "creationtime":
                        case "ess_id":
                        case "group_id":
                        case "scheduledstart":
                        case "user_id":
                            sbList.Add(carray[i]);
                            break;
                        // ESS targets
                        case "record_count":
                        case "record_type": // Individual record criterion send to ESS
                        case "contents":
                        default: // any unhandled attributes are record attributes
                            essList.Add(carray[i]);
                            break;
                    }
                } //parsing of Criterion done
            }
            if (sbList.Count == 0 && essList.Count == 0)
            {
                // No search items - Get all experiments allowed
                expIDs = InternalDataDB.RetrieveExperimentIDs(userID, groupID);
            }
            else
            { // Query SB database to find all possible Experiments and related ESS's
                //As there are criteria only experiments with hits will be returned
                bool hasEssCriteria = (essList.Count > 0);
                 List<long> workExp = new List<long>();
                 Hashtable essLists = null;

                // DataSet contains all experimentID and ess ids that pass SB criteria,
                // and a set of all ess_ids for the authorized experiments
                DataSet results = InternalDataDB.RetrieveExperimentIDsCriteria(userID, groupID, sbList.ToArray());
                if (results != null)
                {
                    if (hasEssCriteria)
                    {

                        DataTable essids = results.Tables["ess"];
                        if (essids != null && essids.Rows != null && essids.Rows.Count > 0)
                        {
                            essLists = new Hashtable();
                            foreach (DataRow er in essids.Rows)
                            {
                                if (er[0] != DBNull.Value)
                                {
                                    List<Int64> exps = new List<Int64>();
                                    essLists.Add(Convert.ToInt32(er[0]), exps);
                                }
                            }
                        }
                    }
                    DataTable hits = results.Tables["sbHits"];
                    if (hits != null)
                    {
                        // Add SB hits to list
                        foreach (DataRow r in hits.Rows)
                        {
                            workExp.Add(Convert.ToInt64(r[0]));
                            if (hasEssCriteria)
                            {
                                if (r[1] != DBNull.Value)
                                {
                                    ((List<Int64>)essLists[Convert.ToInt32(r[1])]).Add(Convert.ToInt64(r[0]));
                                }
                            }
                        }
                    }
                    if (hasEssCriteria)
                    { // Have ESS criteria, use the workList and further filter
                        List<Int64> essHits = new List<Int64>();
                        BrokerDB brokerDB = new BrokerDB();

                        //Process ess criteria
                        foreach (object obj in essLists.Keys)
                        {
                            List<Int64> essExps = (List<Int64>)essLists[obj];
                            if (essExps.Count > 0)
                            {
                                int essId = Convert.ToInt32(obj);

                                ProcessAgentInfo info = brokerDB.GetProcessAgentInfo(essId);
                                if ((info != null) && !info.retired)
                                {
                                    ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                                    AgentAuthHeader authHeader = new AgentAuthHeader();
                                    authHeader.agentGuid = ProcessAgentDB.ServiceGuid;
                                    authHeader.coupon = info.identOut;
                                    essProxy.AgentAuthHeaderValue = authHeader;
                                    essProxy.Url = info.webServiceUrl;
                                    long[] essExpids = essProxy.GetExperimentIDs(essExps.ToArray(), essList.ToArray());
                                    if (essExpids != null && essExpids.Length > 0)
                                    {
                                        foreach (long e in essExpids)
                                        {
                                            essHits.Add(e);
                                        }
                                    }
                                }
                            }
                        }// End of ESS processing
                        expIDs = essHits.ToArray();
                    }
                    else
                    {
                        expIDs = workExp.ToArray();
                    }
                }

            }
            return expIDs;
        }
예제 #19
0
        /*
        /// <summary>
        /// finds all of those Experiments specified in experimentIDs which possess attributes that match the logical AND of conditions expressed in the Criterion array. The search is limited to those experiments that the current user created or for which he or she has a “ReadExperiment” grant. The Criterion conditions must be satisfied elements of the Experiment’s administrative data model such as its ownerID or by the RecordAttributes of a single ExperimentRecord belonging to the experiment for it to qualify.
        /// </summary>
        /// <param name="criteria">The array of Criterion objects that specify the attributes of the requested experiments; all experimentIDs match if null.</param>
        /// <returns>an array of the IDs of Experiments that match the search criteria</returns>
        // Need to stub in alternate predicates and attribute hash maps. - CV 07/08/04
        public static ExperimentSummary[] SelectExperiments(Criterion[] criteria)
        {
            StringBuilder sqlQuery = new StringBuilder();
            long[] experimentIDs;

            sqlQuery.Append("select experiment_id ");
            sqlQuery.Append(" from experiments where ");
            for (int i = 0; i < criteria.Length; i++)
            {
                if (i != 0)
                {
                    sqlQuery.Append(" AND ");
                }
                sqlQuery.Append(criteria[i].attribute + " " + criteria[i].predicate + " '" + criteria[i].value + "'");

            }

            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.GetConnection();
            myCommand.Connection = myConnection;
            myCommand.CommandType = CommandType.Text;
            myCommand.CommandText = sqlQuery.ToString();

            try
            {
                myConnection.Open();
                // get experiment ids from table experiments
                DbDataReader myReader = myCommand.ExecuteReader();
                ArrayList eIDs = new ArrayList();

                while (myReader.Read())
                {
                    if (myReader["experiment_id"] != System.DBNull.Value)
                        eIDs.Add(myReader["experiment_id"]);
                }

                myReader.Close();
                // Converting to a string array
                experimentIDs = new long[eIDs.Count];
                for (int i = 0; i < eIDs.Count; i++)
                {
                    experimentIDs[i] = Convert.ToInt64(eIDs[i]);
                }

            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown finding experiment", ex);
            }
            finally
            {
                myConnection.Close();
            }

            return SelectExperimentSummary(myConnection, experimentIDs);
        }
         * */
        /*
        /// <summary>
        /// finds all of those Experiments specified in experimentIDs which possess attributes that match the logical AND of conditions expressed in the Criterion array. The search is limited to those experiments that the current user created or for which he or she has a “ReadExperiment” grant. The Criterion conditions must be satisfied elements of the Experiment’s administrative data model such as its ownerID or by the RecordAttributes of a single ExperimentRecord belonging to the experiment for it to qualify.
        /// </summary>
        /// <param name="criteria">The array of Criterion objects that specify the attributes of the requested experiments; all experimentIDs match if null.</param>
        /// <returns>an array of the IDs of Experiments that match the search criteria</returns>
        // Need to stub in alternate predicates and attribute hash maps. - CV 07/08/04
        public static ExperimentSummary[] SelectExperimentInfo(long[] expIDs)
        {
            ExperimentSummary[] experiments = null;
            DbConnection myConnection = FactoryDB.GetConnection();
            try
            {
                experiments = SelectExperimentSummary(myConnection, expIDs);
            }
            catch (Exception e)
            {
            }
            finally
            {
                myConnection.Close();
            }
            return experiments;

        }
         */
        /// <summary>
        /// Creates a populated ESS proxy if the specified experiment has an associated ESS.
        /// </summary>
        /// <param name="experimentID"></param>
        /// <returns>a valid ESS proxy, null if the experiment does not have an ESS</returns>
        public static ExperimentStorageProxy GetEssProxy(long experimentID)
        {
            ExperimentStorageProxy proxy = null;
            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("getEssInfo", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@experimentID", experimentID,DbType.Int64));

            try
            {
                myConnection.Open();
                DbDataReader myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                    proxy = new ExperimentStorageProxy();
                    proxy.AgentAuthHeaderValue = new AgentAuthHeader();
                    Coupon coupon = new Coupon();
                    coupon.couponId = (long) myReader.GetInt64(0);
                    coupon.issuerGuid = (string)myReader.GetString(1);
                    coupon.passkey = (string) myReader.GetString(2);
                    proxy.AgentAuthHeaderValue.coupon = coupon;
                    proxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                    proxy.Url = (string) myReader.GetString(3);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown updateing ESSinfo", ex);
            }
            finally
            {
                myConnection.Close();
            }
            return proxy;
        }
 public static ExperimentSummary RetrieveExperimentSummary(long experimentID)
 {
     ExperimentSummary summary = InternalDataDB.SelectExperimentSummary(experimentID);
     if (summary.HasEss && ((summary.status | StorageStatus.CLOSED) == 0))
     {
         ProcessAgentDB ticketing = new ProcessAgentDB();
         // Retrieve the ESS Status info and update as needed
         //This uses a generic ReadRecords ticket created for the ESS
         ProcessAgentInfo ess = ticketing.GetProcessAgentInfo(summary.essGuid);
         if ((ess != null) && !ess.retired)
         {
             ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
             essProxy.Url = ess.webServiceUrl;
             essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
             essProxy.OperationAuthHeaderValue.coupon = ess.identOut;
             StorageStatus status = essProxy.GetExperimentStatus(experimentID);
             bool needsUpdate = false;
             if (status != null)
             {
                 if (summary.closeTime != status.closeTime)
                 {
                     summary.closeTime = status.closeTime;
                     needsUpdate = true;
                 }
                 if (summary.recordCount != status.recordCount)
                 {
                     summary.recordCount = status.recordCount;
                     needsUpdate = true;
                 }
                 if (summary.status != status.status)
                 {
                     summary.status = status.status;
                     needsUpdate = true;
                 }
             }
             if (needsUpdate)
             {
                 InternalDataDB.UpdateExperimentStatus(status);
             }
         }
     }
     return summary;
 }
예제 #21
0
        protected void On_BlobSelected(object sender, GridViewCommandEventArgs e)
        {
            lblResponse.Visible = false;
            if (Session["EssGuid"] != null)
            {
                long blobId = Convert.ToInt64(e.CommandArgument);

                BrokerDB brokerDB = new BrokerDB();
                ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo(Session["EssGuid"].ToString());
                if (ess == null || ess.retired)
                {
                    throw new Exception("The ESS is not registered or is retired");
                }
                Coupon opCoupon = brokerDB.GetEssOpCoupon(Convert.ToInt64(txtExperimentID.Text), TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid);
                if (opCoupon != null)
                {

                    ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                    OperationAuthHeader header = new OperationAuthHeader();
                    header.coupon = opCoupon;
                    essProxy.Url = ess.webServiceUrl;
                    essProxy.OperationAuthHeaderValue = header;
                    string url = essProxy.RequestBlobAccess(blobId, "http", 30);
                    if (url != null)
                    {

                        string jScript = "<script language='javascript'>" +
                                    "window.open('" + url + "')" + "</script>";
                        Page.RegisterStartupScript("Open New Window", jScript);
                        //Response.Redirect(url);
                    }
                    else{
                        lblResponse.Text = Utilities.FormatWarningMessage("Could not access BLOB. ");
                        lblResponse.Visible = true;
                    }
                }
            }
            else
            {
                lblResponse.Text = Utilities.FormatWarningMessage("No ESS is specified, so no records. ");
                lblResponse.Visible = true;
            }
        }
예제 #22
0
        private int ProcessRecords(string fullPath)
        {
            List<string> records = new List<string>();
            int count = 0;
            try
            {
                try
                {
                    // Attempt to open the file exclusively.

                    using (FileStream fs = File.Open(fullPath, FileMode.Open, FileAccess.ReadWrite,
                             FileShare.None))
                    {
                        string line;
                        StreamReader sr = new StreamReader(fs);
                        while ((line = sr.ReadLine()) != null)
                        {
                            records.Add(line);
                        }

                        fs.SetLength(0L);
                        sr.Close();
                    }
                }
                catch (IOException ioe)
                {
                    throw ioe;
                }

                // If we got this far send the data
                if (records.Count > 0)
                {
                    ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                    essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                    essProxy.OperationAuthHeaderValue.coupon = opCoupon;
                    essProxy.Url = essUrl;

                    //replace DataSocket code with 'Pusher' interface
                    IPusherProvider provider = new PusherProvider(pusherID, pusherKey, pusherSS, null);

                    foreach (string rec in records)
                    {
                        string[] vals = rec.Split(delim, 2);
                        DateTime timeStamp = new DateTime(0L, DateTimeKind.Local);
                        bool status = DateTime.TryParseExact(vals[0].Replace("\"", ""), "yyyy-MM-dd HH:mm:ss", null, DateTimeStyles.None, out timeStamp);
                        string record = "\"" + timeStamp.ToString("o") + "\"," + vals[1];
                        try
                        {
                            essProxy.AddRecord(experimentID, submitter, recordType, false, record, null);
                        }
                        catch (Exception essEx)
                        {
                            Logger.WriteLine("BeeEventHandler: OnChange ESS: " + essEx.Message);
                        }
                        try
                        {
                            string str = @"{'rawData': [" + record + "]}";
                            ObjectPusherRequest request =
                                new ObjectPusherRequest(pusherChannel, "meassurement-added", str);
                            provider.Trigger(request);
                        }
                        catch (Exception dsEx)
                        {
                            Logger.WriteLine("BeeEventHandler: OnChange DS: " + dsEx.Message);
                        }
                        count++;
                    }
                    //Pusher interface Close not needed
                }
            }
            catch (Exception e)
            {
            }
            return count;
        }
예제 #23
0
        public Experiment RetrieveExperiment(long experimentID, int userID, int groupID)
        {
            int roles = 0;
            Experiment experiment = null;
            AuthorizationWrapperClass wrapper = new AuthorizationWrapperClass();
            roles = wrapper.GetExperimentAuthorizationWrapper(experimentID, userID, groupID);

            if ((roles | ExperimentAccess.READ) == ExperimentAccess.READ)
            {
                experiment = new Experiment();
                experiment.experimentId = experimentID;
                experiment.issuerGuid = ProcessAgentDB.ServiceGuid;
                ProcessAgentInfo ess = GetExperimentESS(experimentID);
                if (ess != null)
                {
                    ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                    Coupon opCoupon = GetEssOpCoupon(experimentID, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid);
                    if (opCoupon == null)
                    {
                        string payload = TicketLoadFactory.Instance().RetrieveRecordsPayload(experimentID, ess.webServiceUrl);
                        opCoupon = CreateTicket(TicketTypes.RETRIEVE_RECORDS, ess.agentGuid, ProcessAgentDB.ServiceGuid,
                            60, payload);
                    }
                    essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                    essProxy.OperationAuthHeaderValue.coupon = opCoupon;
                    essProxy.Url = ess.webServiceUrl;
                    experiment.records = essProxy.GetRecords(experimentID, null);
                }

            }
            else
            {
                throw new AccessDeniedException("You do not have permission to read this experiment");
            }

            return experiment;
        }
예제 #24
0
        public int RemoveTickets(List<Ticket> ticketList, BrokerDB brokerDb)
        {
            ArrayList coupons = new ArrayList();
            Coupon coupon = null;
            int ticketCount = 0;
            int couponCount = 0;
            if (ticketList.Count > 0)
            {
                Utilities.WriteLog("RemoveTickets: expired count = " + ticketList.Count);

                foreach (Ticket ticket in ticketList)
                {
                    if (!coupons.Contains(ticket.couponId))
                    {
                        coupons.Add(ticket.couponId);
                    }
                    if (coupon == null || coupon.couponId != ticket.couponId)
                    {
                        coupon = brokerDb.GetIssuedCoupon(ticket.couponId);
                    }
                    switch (ticket.type)
                    {
                        case TicketTypes.ADMINISTER_EXPERIMENT:

                            string payload = ticket.payload;
                            if (payload != null)
                            {
                                XmlQueryDoc xDoc = new XmlQueryDoc(payload);
                                string url = xDoc.Query("AdministerExperimentPayload/essURL");
                                string expStr = xDoc.Query("AdministerExperimentPayload/experimentID");
                                long expID = Convert.ToInt64(expStr);
                                ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                                essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                                essProxy.OperationAuthHeaderValue.coupon = coupon;
                                essProxy.Url = url;
                                StorageStatus expStatus = essProxy.SetExperimentStatus(expID, (int)StorageStatus.CLOSED_TIMEOUT);
                                DataStorageAPI.UpdateExperimentStatus(expStatus);
                            }
                            break;
                        case TicketTypes.RETRIEVE_RECORDS:
                        case TicketTypes.STORE_RECORDS:
                            break;
                        case TicketTypes.EXECUTE_EXPERIMENT:
                        case TicketTypes.ALLOW_EXPERIMENT_EXECUTION:
                            break;
                        default: // Every other Ticket type
                            break;
                    }
                    bool statusR = false;

                    if (ticket.redeemerGuid != brokerDb.GetIssuerGuid())
                    {
                        ProcessAgentInfo redeemer = brokerDb.GetProcessAgentInfo(ticket.redeemerGuid);
                        if ((redeemer != null) && !redeemer.retired)
                        {
                            ProcessAgentProxy paProxy = new ProcessAgentProxy();
                            paProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                            paProxy.Url = redeemer.webServiceUrl;
                            paProxy.AgentAuthHeaderValue.coupon = redeemer.identOut;
                            paProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                            statusR = paProxy.CancelTicket(coupon, ticket.type, ticket.redeemerGuid);
                        }
                    }
                    if (ticket.issuerGuid == brokerDb.GetIssuerGuid())
                    {
                        brokerDb.DeleteIssuedTicket(ticket.ticketId);
                        ticketCount++;
                    }
                }
                foreach (long id in coupons)
                {
                    int count = brokerDb.GetIssuedCouponCollectionCount(id);
                    if (count == 0)
                    {
                        brokerDb.DeleteIssuedCoupon(id);
                        couponCount++;
                    }
                }
                Utilities.WriteLog("RemoveTickets: ticketCount=" + ticketCount + " \tcouponCount=" + couponCount);
            }
            return ticketCount;
        }
예제 #25
0
        private static void ExecuteExperimentExecutionRecipe(ProcessAgentInfo labServer, ref LabClient client, ref DateTime startExecution, long duration, int userTZ, int userID, int groupID, string groupName, out BrokerDB brokerDB, out Coupon coupon)
        {
            int essId = 0;
            ProcessAgentInfo essAgent = null;

            long ticketDuration = 7200; //Default to 2 hours
            //   Add a 10 minutes to ESS ticket duration ( in seconds ) to extend beyond experiment expiration
            if (duration != -1)
            {
                //ticketDuration = duration + 60; // For testing only add a minute
                ticketDuration = duration + 600; // Add 10 minutes beyond the experiment end
            }
            else
            {
                ticketDuration = -1;
            }

            // Authorization wrapper
            AuthorizationWrapperClass wrapper = new AuthorizationWrapperClass();

            // create ticket issuer and payload factory
            brokerDB = new BrokerDB();
            TicketLoadFactory factory = TicketLoadFactory.Instance();

            if (client.needsESS)
            {
                essId = brokerDB.FindProcessAgentIdForClient(client.clientID, ProcessAgentType.EXPERIMENT_STORAGE_SERVER);

            }

            // 1. Create Coupon for ExperimentCollection
            coupon = brokerDB.CreateCoupon();

            //
            // 2. create ServiceBroker experiment record and get corresponding experiment id
            // This checks authorization.
            long experimentID = wrapper.CreateExperimentWrapper(StorageStatus.INITIALIZED,
                userID, groupID, labServer.agentId, client.clientID,
                essId, startExecution, duration);

            // Store a record of the Experiment Collection Coupon
            DataStorageAPI.InsertExperimentCoupon(experimentID, coupon.couponId);
            string essWebAddress = null;

            // If a ESS is specified Create the ESS Tickets, this should only happen if a resource is mapped
            if (essId > 0)
            {
                //3.A create ESS administer experiment ticket, Add 10 minutes to duration
                // This must be created before the ESS experiment records may be created
                essAgent = brokerDB.GetProcessAgentInfo(essId);
                if ((essAgent != null) && !essAgent.retired)
                {
                    brokerDB.AddTicket(coupon,
                           TicketTypes.ADMINISTER_EXPERIMENT, essAgent.AgentGuid, brokerDB.GetIssuerGuid(), ticketDuration, factory.createAdministerExperimentPayload(experimentID, essAgent.webServiceUrl));

                    //3.B create store record ticket
                    brokerDB.AddTicket(coupon,
                           TicketTypes.STORE_RECORDS, essAgent.agentGuid, labServer.agentGuid, ticketDuration, factory.StoreRecordsPayload(true, experimentID, essAgent.webServiceUrl));

                    //3.C create retrieve experiment ticket, retrieve Experiment Records never expires, unless experiment deleted
                    //    This should be changed to a long but finite period once eadExisting Expermint is in place.
                    brokerDB.AddTicket(coupon,
                           TicketTypes.RETRIEVE_RECORDS, essAgent.agentGuid, brokerDB.GetIssuerGuid(), -1, factory.RetrieveRecordsPayload(experimentID, essAgent.webServiceUrl));

                    // 3.D Create the ESS Experiment Records
                    ExperimentStorageProxy ess = new ExperimentStorageProxy();
                    ess.AgentAuthHeaderValue = new AgentAuthHeader();
                    ess.AgentAuthHeaderValue.coupon = essAgent.identOut;
                    ess.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                    ess.Url = essAgent.webServiceUrl;
                    essWebAddress = essAgent.webServiceUrl;

                    // Call the ESS to create the ESS Records and open the experiment
                    StorageStatus status = ess.OpenExperiment(experimentID, ticketDuration);
                    if (status != null)
                        DataStorageAPI.UpdateExperimentStatus(status);
                }
            }

            //
            // 4. create the execution ticket for the experiment
            //

            // 4.A create payload
            string payload = factory.createExecuteExperimentPayload(essWebAddress, startExecution, duration,
                userTZ, groupName, brokerDB.GetIssuerGuid(), experimentID);

            // 4.B create experiment execution ticket.
            brokerDB.AddTicket(coupon,
                      TicketTypes.EXECUTE_EXPERIMENT, labServer.agentGuid, labServer.agentGuid, ticketDuration, payload);

            // 4.C Create sessionRedemption Ticket
            string sessionPayload = factory.createRedeemSessionPayload(userID, groupID, client.clientID);
            brokerDB.AddTicket(coupon,
                      TicketTypes.REDEEM_SESSION, brokerDB.GetIssuerGuid(), brokerDB.GetIssuerGuid(), ticketDuration, sessionPayload);
        }
예제 #26
0
파일: LabViewTask.cs 프로젝트: tordf/iLabs
        public static LabTask CreateLabTask(LabAppInfo appInfo, Coupon expCoupon, Ticket expTicket)
        {
            // set defaults
            DateTime startTime = DateTime.UtcNow;
            long duration = -1L;
            long experimentID = 0;
            int status = -1;

            string statusViName = null;
            string statusTemplate = null;
            string templatePath = null;
            LabDB dbManager = new LabDB();
            string qualName = null;
            string fullName = null;  // set defaults
           
            LabTask labTask = null;
            LabViewTask task = null;
            VirtualInstrument vi = null;
            LabViewInterface lvi = null;
            

            ////Parse experiment payload, only get what is needed 	
            string payload = expTicket.payload;
            XmlQueryDoc expDoc = new XmlQueryDoc(payload);
            string essService = expDoc.Query("ExecuteExperimentPayload/essWebAddress");
            string startStr = expDoc.Query("ExecuteExperimentPayload/startExecution");
            string durationStr = expDoc.Query("ExecuteExperimentPayload/duration");
            string groupName = expDoc.Query("ExecuteExperimentPayload/groupName");
            string userName = expDoc.Query("ExecuteExperimentPayload/userName");

            if ((startStr != null) && (startStr.Length > 0))
            {
                startTime = DateUtil.ParseUtc(startStr);
            }
            if ((durationStr != null) && (durationStr.Length > 0) && !(durationStr.CompareTo("-1") == 0))
            {
                duration = Convert.ToInt64(durationStr);
            }


            if (appInfo.extraInfo != null && appInfo.extraInfo.Length > 0)
            {
                // Note should have either statusVI or template pair
                // Add Option for VNCserver access
                try
                {
                    XmlQueryDoc viDoc = new XmlQueryDoc(appInfo.extraInfo);
                    statusViName = viDoc.Query("extra/status");
                    statusTemplate = viDoc.Query("extra/statusTemplate");
                    templatePath = viDoc.Query("extra/templatePath");
                }
                catch (Exception e)
                {
                    string err = e.Message;
                }
            }

            // log the experiment for debugging

            Utilities.WriteLog("Experiment: " + experimentID + " Start: " + DateUtil.ToUtcString(startTime) + " \tduration: " + duration);
            long statusSpan = DateUtil.SecondsRemaining(startTime, duration);



            if ((appInfo.server != null) && (appInfo.server.Length > 0) && (appInfo.port > 0))
            {
                lvi = new LabViewRemote(appInfo.server, appInfo.port);
            }
            else
            {
                lvi = new LabViewInterface();
            }
            if (!lvi.IsLoaded(appInfo.application))
            {
                vi = lvi.loadVI(appInfo.path, appInfo.application);
                vi.OpenFrontPanel(true, FPStateEnum.eVisible);
            }
            else
            {
                vi = lvi.GetVI(appInfo.path, appInfo.application);
            }
            if (vi == null)
            {
                status = -1;
                string err = "Unable to Find: " + appInfo.path + @"\" + appInfo.application;
                Utilities.WriteLog(err);
                throw new Exception(err);
            }
            // Get qualifiedName
            qualName = lvi.qualifiedName(vi);
            fullName = appInfo.path + @"\" + appInfo.application;


            status = lvi.GetVIStatus(vi);

            Utilities.WriteLog("CreateLabTask - " + qualName + ": VIstatus: " + status);
            switch (status)
            {
                case -10:
                    throw new Exception("Error GetVIStatus: " + status);
                    break;
                case -1:
                    // VI not in memory
                    throw new Exception("Error GetVIStatus: " + status);

                    break;
                case 0: // eBad == 0
                    break;
                case 1: // eIdle == 1 vi in memory but not running 
                    FPStateEnum fpState = vi.FPState;
                    if (fpState != FPStateEnum.eVisible)
                    {
                        vi.OpenFrontPanel(true, FPStateEnum.eVisible);
                    }
                    vi.ReinitializeAllToDefault();
                    break;
                case 2: // eRunTopLevel: this should be the LabVIEW application
                    break;
                case 3: // eRunning
                    //Unless the Experiment is reentrant it should be stopped and be reset.
                    if(!appInfo.reentrant){
                        int stopStatus = lvi.StopVI(vi);
                        if (stopStatus != 0)
                        {
                            lvi.AbortVI(vi);
                        }
                        vi.ReinitializeAllToDefault();
                    }
                    break;
                default:
                    throw new Exception("Error GetVIStatus: unknown status: " + status);
                    break;
            }
            try
            {
                lvi.SetBounds(vi, 0, 0, appInfo.width, appInfo.height);
                Utilities.WriteLog("SetBounds: " + appInfo.application);
            }
            catch (Exception sbe)
            {
                Utilities.WriteLog("SetBounds exception: " + Utilities.DumpException(sbe));
            }
            lvi.SubmitAction("unlockvi", lvi.qualifiedName(vi));
            Utilities.WriteLog("unlockvi Called: ");


            // Set up in-memory and database task control structures
            DataSourceManager dsManager = null;

            // Create the labTask & store in database;
            labTask = dbManager.InsertTask(appInfo.appID, experimentID,
           groupName, startTime, duration,
           LabTask.eStatus.Scheduled, expTicket.couponId, expTicket.issuerGuid, null);
            if (labTask != null)
            {
                //Convert the generic LabTask to a LabViewTask
                task = new LabViewTask(labTask);
            }
            if ((statusTemplate != null) && (statusTemplate.Length > 0))
            {
                statusViName = lvi.CreateFromTemplate(templatePath, statusTemplate, task.taskID.ToString());
            }


            if (((essService != null) && (essService.Length > 0)) && ((appInfo.dataSources != null) && (appInfo.dataSources.Length > 0)))
            {
                // Create DataSourceManager to manage dataSocket connections
                dsManager = new DataSourceManager();

                // set up an experiment storage handler
                ExperimentStorageProxy ess = new ExperimentStorageProxy();
                ess.OperationAuthHeaderValue = new OperationAuthHeader();
                ess.OperationAuthHeaderValue.coupon = expCoupon;
                ess.Url = essService;
                dsManager.essProxy = ess;
                dsManager.ExperimentID = experimentID;
                dsManager.AppKey = qualName;
                string[] sockets = appInfo.dataSources.Split(',');
                // Use the experimentID as the storage parameter
                foreach (string s in sockets)
                {
                    LVDataSocket reader = new LVDataSocket();
                    dsManager.AddDataSource(reader);
                    if (s.Contains("="))
                    {
                        string[] nv = s.Split('=');
                        reader.Type = nv[1];
                        reader.Connect(nv[0], LabDataSource.READ_AUTOUPDATE);

                    }
                    else
                    {
                        reader.Connect(s, LabDataSource.READ_AUTOUPDATE);
                    }

                }
                TaskProcessor.Instance.AddDataManager(task.taskID, dsManager);
            }
            string taskData = null;
            taskData = LabTask.constructTaskXml(appInfo.appID, fullName,appInfo.rev, statusViName, essService);
            dbManager.SetTaskData(task.taskID, taskData);
            task.data = taskData;
            TaskProcessor.Instance.Add(task);
            return task;
        }