Beispiel #1
0
        /// <summary>
        /// Initializes a new instance of the ServiceJobProvider class
        /// </summary>
        /// <param name="startInfo">The session attach info</param>
        /// <param name="binding">indicting the binding</param>
        public ServiceJobProvider(SessionAttachInfo info, Binding binding)
        {
            this.binding  = binding;
            this.headNode = info.Headnode;
            if ((info.TransportScheme & TransportScheme.NetTcp) == TransportScheme.NetTcp)
            {
                this.endpointPrefix = SessionLauncherClient.EndpointPrefix;
            }
            else if ((info.TransportScheme & TransportScheme.Http) == TransportScheme.Http || (info.TransportScheme & TransportScheme.NetHttp) == TransportScheme.NetHttp)
            {
                this.endpointPrefix = SessionLauncherClient.HttpsEndpointPrefix;
            }
            else if ((info.TransportScheme & TransportScheme.Custom) == TransportScheme.Custom)
            {
                this.endpointPrefix = SessionLauncherClient.EndpointPrefix;
            }

            this.client = new SessionLauncherClient(info, binding);
#if !net40
            if (info.UseAad)
            {
                this.client.Endpoint.Behaviors.UseAadClientBehaviors(info).GetAwaiter().GetResult();
            }
#endif
        }
Beispiel #2
0
        public async Task <SessionInfo> GetResourceInfo(SessionAttachInfo attachInfo, TimeSpan timeout)
        {
            this.client.InnerChannel.OperationTimeout = timeout;
            RetryManager retry = SoaHelper.GetDefaultExponentialRetryManager();

            SessionInfo info;
            DateTime    startTime = DateTime.Now;

            if (attachInfo.TransportScheme == TransportScheme.Http)
            {
                info = Utility.BuildSessionInfoFromDataContract(
                    await RetryHelper <SessionInfoContract> .InvokeOperationAsync(
                        async() => await this.client.GetInfoAsync(SessionLauncherClient.HttpsEndpointPrefix, attachInfo.SessionId).ConfigureAwait(false),
                        (e, r) =>
                {
                    var remainingTime = GetRemainingTime(timeout, startTime);
                    if ((e is EndpointNotFoundException || (e is CommunicationException && !(e is FaultException <SessionFault>))) && remainingTime > TimeSpan.Zero)
                    {
                        Utility.SafeCloseCommunicateObject(this.client);
                        this.client = new SessionLauncherClient(attachInfo, this.binding);
                        this.client.InnerChannel.OperationTimeout = remainingTime;
                    }
                    else
                    {
                        r.MaxRetryCount = 0;
                    }

                    return(Task.CompletedTask);
                },
                        retry)
                    .ConfigureAwait(false));
            }
            else
            {
                info = Utility.BuildSessionInfoFromDataContract(
                    await RetryHelper <SessionInfoContract> .InvokeOperationAsync(
                        async() => await this.client.GetInfoAsync(SessionLauncherClient.EndpointPrefix, attachInfo.SessionId).ConfigureAwait(false),
                        (e, r) =>
                {
                    var remainingTime = GetRemainingTime(timeout, startTime);

                    if ((e is EndpointNotFoundException || (e is CommunicationException && !(e is FaultException <SessionFault>))) && remainingTime > TimeSpan.Zero)
                    {
                        Utility.SafeCloseCommunicateObject(this.client);
                        this.client = new SessionLauncherClient(attachInfo, this.binding);
                        this.client.InnerChannel.OperationTimeout = remainingTime;
                    }
                    else
                    {
                        r.MaxRetryCount = 0;
                    }

                    return(Task.CompletedTask);
                },
                        retry)
                    .ConfigureAwait(false));
            }

            return(info);
        }
Beispiel #3
0
 /// <summary>
 /// Save the credential at local Windows Vault.
 /// </summary>
 /// <param name="info">
 /// attach info
 /// it specifies credential and targeted scheduler
 /// </param>
 internal static void SaveCrendential(SessionAttachInfo info)
 {
     if (info.SavePassword)
     {
         SaveCrendential(info.Headnode, info.Username, info.InternalPassword);
     }
 }
        /// <summary>
        /// Get resource information
        /// </summary>
        /// <param name="attachInfo">indicating session attach information</param>
        /// <param name="timeout">indicating the timeout</param>
        /// <returns>returns session information</returns>
        public Task <SessionInfo> GetResourceInfo(SessionAttachInfo attachInfo, TimeSpan timeout)
        {
            try
            {
#if net40
                return(TaskEx.FromResult(InprocessSessions.GetInstance().FetchSessionInfo(attachInfo.SessionId)));
#else
                return(Task.FromResult(InprocessSessions.GetInstance().FetchSessionInfo(attachInfo.SessionId)));
#endif
            }
            catch (SessionException e)
            {
                if (this.durable && attachInfo.SessionId == InprocessSessions.DebugModeSessionId && e.ErrorCode == SOAFaultCode.Session_ValidateJobFailed_AlreadyFinished)
                {
                    // Return an empty instance of SessionInfo as it is not used in debug mode when trying to raise up a broker
#if net40
                    return(TaskEx.FromResult(new SessionInfo()));
#else
                    return(Task.FromResult(new SessionInfo()));
#endif
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #5
0
        private void retrieveResp()
        {
            #region Init
            result[] results = new result[10];
            for (int i = 0; i < 10; i++)
            {
                results[i] = new result();
            }
            #endregion

            SessionAttachInfo attachInfo = new SessionAttachInfo(Config.headNode, Convert.ToInt32(this.Range["D20", missing].Value2));

            using (DurableSession session = DurableSession.AttachSession(attachInfo))
            {
                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
                {
                    foreach (BrokerResponse <PriceAsianOptionsResponse> response in client.GetResponses <PriceAsianOptionsResponse>())
                    {
                        cellContext idx   = response.GetUserData <cellContext>();
                        double      price = response.Result.PriceAsianOptionsResult;
                        Interlocked.Increment(ref results[idx.iteration].count);

                        this.Range[idx.range, missing].Value2 = price;

                        results[idx.iteration].min = Math.Min(results[idx.iteration].min, price);
                        results[idx.iteration].max = Math.Max(results[idx.iteration].max, price);

                        results[idx.iteration].sumPrice       += price;
                        results[idx.iteration].sumSquarePrice += price * price;

                        results[idx.iteration].stdDev = Math.Sqrt(results[idx.iteration].sumSquarePrice - results[idx.iteration].sumPrice * results[idx.iteration].sumPrice / results[idx.iteration].count) / ((results[idx.iteration].count == 1) ? 1 : results[idx.iteration].count - 1);
                        results[idx.iteration].stdErr = results[idx.iteration].stdDev / Math.Sqrt(results[idx.iteration].count);

                        if (results[idx.iteration].count == 100)
                        {
                            int i = idx.iteration;
                            this.Range[string.Format("{0}14", cols[i]), missing].Value2 = results[i].sumPrice / results[i].count;
                            this.Range[string.Format("{0}15", cols[i]), missing].Value2 = results[i].min;
                            this.Range[string.Format("{0}16", cols[i]), missing].Value2 = results[i].max;
                            this.Range[string.Format("{0}17", cols[i]), missing].Value2 = results[i].stdDev;
                            this.Range[string.Format("{0}18", cols[i]), missing].Value2 = results[i].stdErr;
                        }
                    }
                }
                session.Close();
            }

            #region Summarize
            for (int i = 0; i < 10; i++)
            {
                this.Range[string.Format("{0}14", cols[i]), missing].Value2 = results[i].sumPrice / results[i].count;
                this.Range[string.Format("{0}15", cols[i]), missing].Value2 = results[i].min;
                this.Range[string.Format("{0}16", cols[i]), missing].Value2 = results[i].max;
                this.Range[string.Format("{0}17", cols[i]), missing].Value2 = results[i].stdDev;
                this.Range[string.Format("{0}18", cols[i]), missing].Value2 = results[i].stdErr;
            }
            #endregion
        }
Beispiel #6
0
        /// <summary>
        /// Build an instance of the AbstractSessionFactory class to create session
        /// </summary>
        /// <param name="sessionAttachInfo">indicating the session attach information</param>
        /// <returns>returns an instance of the AbstractSessionFactory class</returns>
        public static AbstractSessionFactory BuildSessionFactory(SessionAttachInfo sessionAttachInfo)
        {
            if ((sessionAttachInfo.TransportScheme & TransportScheme.WebAPI) == TransportScheme.WebAPI)
            {
                throw new ArgumentException(SR.TransportSchemeWebAPIExclusive);
            }

            return(new OnPremiseSessionFactory());
        }
 /// <summary>
 /// Build broker factory
 /// </summary>
 protected static IBrokerFactory BuildBrokerFactory(SessionAttachInfo attachInfo, bool durable)
 {
     if (attachInfo.UseInprocessBroker)
     {
         return(new InprocessBrokerFactory(attachInfo.Headnode, durable));
     }
     else
     {
         return(new V3BrokerFactory(durable));
     }
 }
 /// <summary>
 /// Build resource provider by attach info
 /// </summary>
 /// <param name="attachInfo">indicating the session attach information</param>
 /// <param name="durable">indicating whether the session is a durable session</param>
 /// <param name="binding">indicting the binding</param>
 /// <returns>returns the instance of IResourceProvider</returns>
 private static IResourceProvider BuildResourceProvider(SessionAttachInfo attachInfo, bool durable, Binding binding)
 {
     if (!attachInfo.DebugModeEnabled)
     {
         Debug.Assert(attachInfo.Headnode != null, "[AbstractSessionFactory] Head node should not be null if debug mode is enabled.");
         return(new ServiceJobProvider(attachInfo, binding));
     }
     else
     {
         return(new DummyResourceProvider(durable));
     }
 }
Beispiel #9
0
        /// <summary>
        /// Get user's credential for Azure cluster when attaching session.
        /// </summary>
        /// <param name="info">Session attach info</param>
        /// <returns>pops up credential dialog or not</returns>
        internal static bool RetrieveCredentialOnAzure(SessionAttachInfo info)
        {
            string username         = info.Username;
            string internalPassword = info.InternalPassword;
            bool   savePassword     = info.SavePassword;

            bool result = RetrieveCredentialOnAzure(info.Headnode, ref username, ref internalPassword, ref savePassword);

            info.Username     = username;
            info.Password     = internalPassword;
            info.SavePassword = savePassword;
            return(result);
        }
Beispiel #10
0
        /// <summary>
        /// Attach to a existing session async with the session attach info and binding
        /// </summary>
        /// <param name="attachInfo">The attach info</param>
        /// <param name="binding">indicting the binding</param>
        /// <returns>A persistant session</returns>
        public static async Task <V3Session> AttachSessionAsync(SessionAttachInfo attachInfo, Binding binding)
        {
            Utility.ThrowIfNull(attachInfo, "attachInfo");

            if (Utility.IsHpcSessionType(attachInfo.GetType()))
            {
                Utility.ThrowIfEmpty(attachInfo.Headnode, "headNode");

                return((V3Session)await HpcSessionFactory.BuildSessionFactory(attachInfo).AttachSession(attachInfo, false, Timeout.Infinite, binding).ConfigureAwait(false));
            }
            else
            {
                throw new ArgumentException(SR.BackendNotSupported, "attachInfo");
            }
        }
Beispiel #11
0
 internal static void CheckCredential(SessionAttachInfo info)
 {
     if (info.InternalPassword != null)
     {
         // Verify the username password if we can.
         // Verify the cached credential in case it is expired.
         Credentials.ValidateCredentials(info.Username, info.InternalPassword, true);
     }
     else
     {
         // For back-compact, don't transmit null password to session service, which can causes exception there.
         // It is fine to replace null by empty string even user's password is empty string.
         info.InternalPassword = String.Empty;
     }
 }
Beispiel #12
0
        static void Main(string[] args)
        {
            try
            {
                //Input sessionId here
                int sessionId;
                Console.Write("Input the session id : ");
                sessionId = Int32.Parse(Console.ReadLine());

                //Change the headnode name here
                SessionAttachInfo info = new SessionAttachInfo("head.contoso.com", sessionId);

                //Attach to session
                DurableSession session = DurableSession.AttachSession(info);
                Console.WriteLine("Attached to session {0}", sessionId);

                int numberResponse = 0;

                //Get responses
                using (BrokerClient <IPrimeFactorization> client = new BrokerClient <IPrimeFactorization>(session))
                {
                    foreach (BrokerResponse <FactorizeResponse> response in client.GetResponses <FactorizeResponse>())
                    {
                        int   number  = response.GetUserData <int>();
                        int[] factors = response.Result.FactorizeResult;

                        Console.WriteLine("{0} = {1}", number, string.Join <int>(" * ", factors));

                        numberResponse++;
                    }
                }

                session.Close(true);
                Console.WriteLine("{0} responses have been received", numberResponse);

                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// Attach the broker
        /// </summary>
        /// <param name="startInfo">session start info</param>
        /// <param name="sessionInfo">session info</param>
        /// <param name="durable">whether durable session</param>
        /// <param name="timeoutMilliseconds">attach timeout</param>
        /// <param name="binding">indicating the binding</param>
        /// <returns>session object</returns>
        public override async Task <SessionBase> AttachBroker(SessionStartInfo startInfo, SessionInfoContract sessionInfo, bool durable, int timeoutMilliseconds, Binding binding)
        {
            DateTime targetTimeout;

            Utility.ThrowIfNull(sessionInfo, "sessionInfo");
            Utility.ThrowIfInvalidTimeout(timeoutMilliseconds, "timeoutMilliseconds");

            if (timeoutMilliseconds == Timeout.Infinite)
            {
                targetTimeout = DateTime.MaxValue;
            }
            else
            {
                targetTimeout = DateTime.Now.AddMilliseconds(timeoutMilliseconds);
            }

            SessionBase.TraceSource.TraceEvent(TraceEventType.Information, 0, "[Session:{0}] Start to attach broker...", sessionInfo.Id);

            SessionInfo       info       = Utility.BuildSessionInfoFromDataContract(sessionInfo); // resourceProvider.GetResourceInfo(attachInfo, SessionBase.GetTimeout(targetTimeout));
            SessionAttachInfo attachInfo = new SessionAttachInfo(startInfo.Headnode, sessionInfo.Id);

            attachInfo.TransportScheme  = startInfo.TransportScheme;
            attachInfo.Username         = startInfo.Username;
            attachInfo.InternalPassword = startInfo.InternalPassword;

            IBrokerFactory brokerFactory = BuildBrokerFactory(attachInfo, durable);

            try
            {
                return(await brokerFactory.AttachBroker(attachInfo, info, SessionBase.GetTimeout(targetTimeout), binding).ConfigureAwait(false));
            }
            finally
            {
                IDisposable disposableObject = brokerFactory as IDisposable;
                if (disposableObject != null)
                {
                    disposableObject.Dispose();
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the SessionLauncherClient class.
        /// </summary>
        /// <param name="startInfo">The session attach info</param>
        /// <param name="binding">indicating the binding</param>
        public SessionLauncherClient(SessionAttachInfo attachInfo, Binding binding)
            : base(binding ?? attachInfo.GetSessionLauncherBinding(), GetEndpoint(attachInfo))
        {
            if (SoaHelper.IsSchedulerOnIaaS(attachInfo.Headnode))
            {
                this.schedulerOnIaaS = true;
            }

            if ((attachInfo.TransportScheme & TransportScheme.NetTcp) == TransportScheme.NetTcp || (attachInfo.TransportScheme & TransportScheme.NetHttp) == TransportScheme.NetHttp)
            {
                if (this.schedulerOnIaaS || attachInfo.UseWindowsClientCredential)
                {
                    string domainName;
                    string userName;
                    SoaHelper.ParseDomainUser(attachInfo.Username, out domainName, out userName);
                    this.ClientCredentials.Windows.ClientCredential.Domain   = domainName;
                    this.ClientCredentials.Windows.ClientCredential.UserName = userName;
                    this.ClientCredentials.Windows.ClientCredential.Password = attachInfo.InternalPassword;
                }
                else if (attachInfo.UseAad)
                {
                }
                else if (attachInfo.LocalUser)
                {
                    this.UseInternalAuthenticationAsync().GetAwaiter().GetResult();
                }
            }
            else if ((attachInfo.TransportScheme & TransportScheme.Http) == TransportScheme.Http)
            {
                this.ClientCredentials.UserName.UserName = attachInfo.Username;
                this.ClientCredentials.UserName.Password = attachInfo.InternalPassword;
            }

            if (!SoaHelper.IsOnAzure() && !attachInfo.UseAad)
            {
                this.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
            }
        }
Beispiel #15
0
        public GeneralResourceProvider(SessionAttachInfo info, Binding binding)
        {
            this.sessionNode = info.Headnode;
            this.binding     = binding;
            if ((info.TransportScheme & TransportScheme.NetTcp) == TransportScheme.NetTcp)
            {
                this.endpointPrefix = SessionLauncherClient.EndpointPrefix;
            }
            else if ((info.TransportScheme & TransportScheme.Http) == TransportScheme.Http || (info.TransportScheme & TransportScheme.NetHttp) == TransportScheme.NetHttp)
            {
                this.endpointPrefix = SessionLauncherClient.HttpsEndpointPrefix;
            }
            else if ((info.TransportScheme & TransportScheme.Custom) == TransportScheme.Custom)
            {
                this.endpointPrefix = SessionLauncherClient.EndpointPrefix;
            }
            else if ((info.TransportScheme & TransportScheme.AzureStorage) == TransportScheme.AzureStorage)
            {
                this.endpointPrefix = "az.table";
            }

            this.client = new SessionLauncherClient(info, binding);
        }
 /// <summary>
 /// Initializes a new instance of the BrokerLauncherClient class.
 /// </summary>
 /// <param name="uri">The broker launcher EPR</param>
 /// <param name="startInfo">The session attach info</param>
 /// <param name="binding">indicting the binding</param>
 public BrokerLauncherClient(Uri uri, SessionAttachInfo attachInfo, Binding binding)
     : this(attachInfo, binding, uri)
 {
     if (attachInfo.UseAad)
     {
     }
     else if ((attachInfo.TransportScheme & TransportScheme.NetTcp) == TransportScheme.NetTcp)
     {
         if (SoaHelper.IsSchedulerOnIaaS(attachInfo.Headnode) || attachInfo.UseWindowsClientCredential)
         {
             string domainName;
             string userName;
             SoaHelper.ParseDomainUser(attachInfo.Username, out domainName, out userName);
             this.ClientCredentials.Windows.ClientCredential.Domain   = domainName;
             this.ClientCredentials.Windows.ClientCredential.UserName = userName;
             this.ClientCredentials.Windows.ClientCredential.Password = attachInfo.InternalPassword;
         }
     }
     else if ((attachInfo.TransportScheme & TransportScheme.Http) == TransportScheme.Http || (attachInfo.TransportScheme & TransportScheme.NetHttp) == TransportScheme.NetHttp)
     {
         this.ClientCredentials.UserName.UserName = attachInfo.Username;
         this.ClientCredentials.UserName.Password = attachInfo.InternalPassword;
     }
 }
Beispiel #17
0
 /// <summary>
 /// Attach to a existing session with the session attach info and binding
 /// </summary>
 /// <param name="attachInfo">The attach info</param>
 /// <param name="binding">indicting the binding</param>
 /// <returns>A persistant session</returns>
 public static V3Session AttachSession(SessionAttachInfo attachInfo, Binding binding)
 {
     return(AttachSessionAsync(attachInfo, binding).GetAwaiter().GetResult());
 }
 /// <summary>
 ///   <para>Attaches a service-oriented architecture (SOA) client to an
 /// existing durable session by using the specified information about the session.</para>
 /// </summary>
 /// <param name="attachInfo">
 ///   <para>A
 /// <see cref="Microsoft.Hpc.Scheduler.Session.SessionAttachInfo" /> object that specifies information about the durable session to which you want to attach the SOA client, including the name of the head node for the cluster that hosts the session and the identifier of the session.</para>
 /// </param>
 /// <returns>
 ///   <para>A <see cref="HpcDurableSession" /> that represents the durable session to which the client attached.</para>
 /// </returns>
 public static HpcDurableSession AttachSession(SessionAttachInfo attachInfo)
 {
     return(AttachSession(attachInfo, null));
 }
Beispiel #19
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string     headnode    = "[headnode]";
            const string     serviceName = "EchoService";
            const int        numRequests = 12;
            SessionStartInfo startInfo   = new SessionStartInfo(headnode, serviceName);

            startInfo.BrokerSettings.SessionIdleTimeout = 15 * 60 * 1000;
            startInfo.BrokerSettings.ClientIdleTimeout  = 15 * 60 * 1000;

            Console.Write("Creating a session for EchoService...");

            // Create a durable session
            int       sessionId       = 0;
            const int retryCountMax   = 20;
            const int retryIntervalMs = 5000;

            DurableSession session = DurableSession.CreateSession(startInfo);

            sessionId = session.Id;
            Console.WriteLine("Done session id = {0}", sessionId);


            //send requests with reliable broker client
            bool successFlag = false;
            int  retryCount  = 0;

            using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
            {
                Console.Write("Sending {0} requests...", numRequests);
                while (!successFlag && retryCount++ < retryCountMax)
                {
                    try
                    {
                        for (int i = 0; i < numRequests; i++)
                        {
                            client.SendRequest <EchoRequest>(new EchoRequest(i.ToString()), i);
                        }

                        client.EndRequests();
                        successFlag = true;
                        Console.WriteLine("done");
                    }
                    catch (Exception e)
                    {
                        //general exceptions
                        Console.WriteLine("Exception {0}", e.ToString());
                        Thread.Sleep(retryIntervalMs);
                    }
                }
            }


            //attach the session
            SessionAttachInfo attachInfo = new SessionAttachInfo(headnode, sessionId);

            successFlag = false;
            retryCount  = 0;
            Console.WriteLine("Retrieving responses...");
            using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
            {
                int responseCount = 0;
                retryCount = 0;
                while (responseCount < numRequests && retryCount++ < retryCountMax)
                {
                    try
                    {
                        foreach (var response in client.GetResponses <EchoResponse>())
                        {
                            Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), response.Result.EchoResult);
                            responseCount++;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        Thread.Sleep(retryIntervalMs);
                    }
                }
            }

            Console.WriteLine("Close the session...");
            session.Close(true);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Beispiel #20
0
        /// <summary>
        /// Attach to a broker, returns session instance
        /// </summary>
        /// <param name="attachInfo">indicating the attach information</param>
        /// <param name="info">indicating the session info to be updated</param>
        /// <param name="timeout">indicating the timeout</param>
        /// <param name="binding">indicting the binding</param>
        /// <returns>returns the session instance</returns>
        public Task <SessionBase> AttachBroker(SessionAttachInfo attachInfo, SessionInfo info, TimeSpan timeout, Binding binding)
        {
            SessionBase.TraceSource.TraceInformation("[Session:{0}] Try to attach broker...", attachInfo.SessionId);
            BrokerLauncherClient broker = new BrokerLauncherClient(new Uri(info.BrokerLauncherEpr), attachInfo, binding);

            broker.InnerChannel.OperationTimeout = timeout;
            try
            {
                BrokerInitializationResult result = broker.Attach(info.Id);
                info.BrokerEpr                       = result.BrokerEpr;
                info.ControllerEpr                   = result.ControllerEpr;
                info.ResponseEpr                     = result.ResponseEpr;
                info.ServiceOperationTimeout         = result.ServiceOperationTimeout;
                info.MaxMessageSize                  = result.MaxMessageSize;
                info.ClientBrokerHeartbeatInterval   = result.ClientBrokerHeartbeatInterval;
                info.ClientBrokerHeartbeatRetryCount = result.ClientBrokerHeartbeatRetryCount;
                info.BrokerUniqueId                  = result.BrokerUniqueId;

                info.UseAzureQueue         = result.UseAzureQueue;
                info.AzureRequestQueueUris = result.AzureRequestQueueUris;
                info.AzureRequestBlobUri   = result.AzureRequestBlobUri;

                info.Username         = attachInfo.Username;
                info.InternalPassword = attachInfo.InternalPassword;
                info.Headnode         = attachInfo.Headnode;

                info.UseWindowsClientCredential = attachInfo.UseWindowsClientCredential;
            }
            catch (FaultException <SessionFault> e)
            {
                SessionBase.TraceSource.TraceEvent(TraceEventType.Error, 0, "[Session:{0}] Fault exception occured while attaching broker: {1}. FaultCode = {2}", attachInfo.SessionId, e, e.Detail.Code);
                throw Utility.TranslateFaultException(e);
            }
            catch (CommunicationException e)
            {
                SessionBase.TraceSource.TraceEvent(TraceEventType.Error, 0, "[Session:{0}] Failed to attach to broker: {1}", attachInfo.SessionId, e);
                throw new SessionException(SOAFaultCode.ConnectBrokerLauncherFailure, SR.ConnectBrokerLauncherFailure, e);
            }
            catch (Exception e)
            {
                SessionBase.TraceSource.TraceEvent(TraceEventType.Error, 0, "[Session:{0}] Failed to attach to broker: {1}", attachInfo.SessionId, e);
                throw new SessionException(SOAFaultCode.UnknownError, e.ToString());
            }
            finally
            {
                Utility.SafeCloseCommunicateObject(broker);
            }

            if (SoaHelper.IsSchedulerOnIaaS(attachInfo.Headnode))
            {
                string suffix = SoaHelper.GetSuffixFromHeadNodeEpr(attachInfo.Headnode);
                if (info.BrokerEpr != null)
                {
                    SoaHelper.UpdateEprWithCloudServiceName(info.BrokerEpr, suffix);
                }

                if (info.ControllerEpr != null)
                {
                    SoaHelper.UpdateEprWithCloudServiceName(info.ControllerEpr, suffix);
                }

                if (info.ResponseEpr != null)
                {
                    SoaHelper.UpdateEprWithCloudServiceName(info.ResponseEpr, suffix);
                }
            }

            if (this.durable)
            {
                if (!info.Durable)
                {
                    throw new SessionException(SOAFaultCode.InvalidAttachInteractiveSession, SR.InvalidAttachInteractiveSession);
                }
#if net40
                return(TaskEx.FromResult <SessionBase>(new DurableSession(info, attachInfo.Headnode, binding)));
#else
                return(Task.FromResult <SessionBase>(new DurableSession(info, attachInfo.Headnode, binding)));
#endif
            }
            else
            {
                if (info.Durable)
                {
                    throw new SessionException(SOAFaultCode.InvalidAttachDurableSession, SR.InvalidAttachDurableSession);
                }
#if net40
                return(TaskEx.FromResult <SessionBase>(new V3Session(info, attachInfo.Headnode, true, binding)));
#else
                return(Task.FromResult <SessionBase>(new V3Session(info, attachInfo.Headnode, true, binding)));
#endif
            }
        }
        /// <summary>
        /// Attach to an existing session
        /// </summary>
        /// <param name="attachInfo">indicating the session attach information</param>
        /// <param name="durable">indicating a value whether a durable session is to be created</param>
        /// <param name="timeoutMilliseconds">indicating the timeout</param>
        /// <param name="binding">indicating the binding</param>
        /// <returns>returns session instance</returns>
        public override async Task <SessionBase> AttachSession(SessionAttachInfo attachInfo, bool durable, int timeoutMilliseconds, Binding binding)
        {
            Debug.Assert(attachInfo is SessionAttachInfo, "[OnPremiseSessionFactory].AttachSession: attachInfo's type must be SessionAttachInfo.");
            DateTime targetTimeout;

            Utility.ThrowIfNull(attachInfo, "attachInfo");
            Utility.ThrowIfInvalidTimeout(timeoutMilliseconds, "timeoutMilliseconds");

            if (timeoutMilliseconds == Timeout.Infinite)
            {
                targetTimeout = DateTime.MaxValue;
            }
            else
            {
                targetTimeout = DateTime.Now.AddMilliseconds(timeoutMilliseconds);
            }

            SessionBase.TraceSource.TraceEvent(TraceEventType.Information, 0, "[Session:{0}] Start to attach session...", attachInfo.SessionId);

            IResourceProvider resourceProvider   = null;
            SessionInfo       info               = null;
            CredType          typeOfExpectedCred = CredType.None;

            try
            {
                int  retry            = 0;
                bool askForCredential = false;

                // allow users to try credential at most MaxRetryCount times
                int askForCredentialTimes = 0;
                while (Utility.CanRetry(retry, askForCredential, askForCredentialTimes))
                {
                    retry++;

                    try
                    {
                        SessionBase.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "[Session:{0}] Start to attach session.", attachInfo.SessionId);
                        Stopwatch watch = new Stopwatch();
                        watch.Start();

                        if (attachInfo.UseAad)
                        {
                            // Authentication handled by AADUtil
                        }
                        else if (SoaHelper.IsSchedulerOnAzure(attachInfo.Headnode) || SoaHelper.IsSchedulerOnIaaS(attachInfo.Headnode) || (attachInfo.TransportScheme & TransportScheme.Http) == TransportScheme.Http)
                        {
                            askForCredential = HpcSessionCredUtil.RetrieveCredentialOnAzure(attachInfo);

                            if (askForCredential)
                            {
                                askForCredentialTimes++;
                            }
                        }
                        else
                        {
                            askForCredential = await HpcSessionCredUtil.RetrieveCredentialOnPremise(attachInfo, typeOfExpectedCred, binding).ConfigureAwait(false);

                            if (askForCredential)
                            {
                                askForCredentialTimes++;
                            }

                            HpcSessionCredUtil.CheckCredential(attachInfo);
                            HpcSessionCredUtil.CheckCredential(attachInfo);
                        }

                        resourceProvider = BuildResourceProvider(attachInfo, durable, binding);
                        watch.Stop();

                        // re-calculate the timeout to exclude the timespan for getting credential
                        try
                        {
                            targetTimeout = targetTimeout.AddMilliseconds(watch.ElapsedMilliseconds);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                        }

                        info = await resourceProvider.GetResourceInfo(attachInfo, SessionBase.GetTimeout(targetTimeout)).ConfigureAwait(false);

                        SessionBase.TraceSource.TraceEvent(TraceEventType.Verbose, 0, "[Session:{0}] Successfully got resource info. BrokerLauncherEpr = {1}", attachInfo.SessionId, info.BrokerLauncherEpr);

                        // If the session is an inprocess broker session, info.UseInprocessBroker will be set
                        // to true by HpcSession service. Need to set attachInfo.UseInprocessBroker to true
                        // in order to build correct broker factory instance.
                        if (info.UseInprocessBroker)
                        {
                            attachInfo.UseInprocessBroker = true;
                        }

                        // If debug mode is enabled, need to set info.UseInprocessBroker to true in order to
                        // build correct broker factory instance.
                        if (attachInfo.DebugModeEnabled)
                        {
                            info.UseInprocessBroker = true;
                        }

                        if (SoaHelper.IsSchedulerOnIaaS(attachInfo.Headnode))
                        {
                            string suffix = SoaHelper.GetSuffixFromHeadNodeEpr(attachInfo.Headnode);
                            info.BrokerLauncherEpr = SoaHelper.UpdateEprWithCloudServiceName(info.BrokerLauncherEpr, suffix);
                            if (info.BrokerEpr != null)
                            {
                                SoaHelper.UpdateEprWithCloudServiceName(info.BrokerEpr, suffix);
                            }

                            if (info.ControllerEpr != null)
                            {
                                SoaHelper.UpdateEprWithCloudServiceName(info.ControllerEpr, suffix);
                            }

                            if (info.ResponseEpr != null)
                            {
                                SoaHelper.UpdateEprWithCloudServiceName(info.ResponseEpr, suffix);
                            }
                        }
                        HpcSessionCredUtil.SaveCrendential(attachInfo);
                        break;
                    }
                    catch (SessionException)
                    {
                        throw;
                    }
                    catch (EndpointNotFoundException)
                    {
                        SessionBase.TraceSource.TraceEvent(TraceEventType.Error, 0, "[Session:{0}] EndpointNotFoundException occured while getting resource info.", attachInfo.SessionId);
                        SessionBase.HandleEndpointNotFoundException(attachInfo.Headnode);
                    }
                    catch (AuthenticationException e)
                    {
                        SessionBase.TraceSource.TraceEvent(TraceEventType.Warning, 0, "[Session:{0}] AuthenticationException occured while attaching session: {1}", attachInfo.SessionId, e);

                        attachInfo.ClearCredential();
                        SessionBase.PurgeCredential(attachInfo);
                        if (Utility.CanRetry(retry, askForCredential, askForCredentialTimes))
                        {
                            if (typeOfExpectedCred == CredType.None)
                            {
                                typeOfExpectedCred = await CredUtil.GetCredTypeFromClusterAsync(attachInfo, binding).ConfigureAwait(false);
                            }

                            if (resourceProvider is IDisposable)
                            {
                                ((IDisposable)resourceProvider).Dispose();
                            }
                            continue;
                        }
                        else
                        {
                            throw;
                        }
                    }
                    catch (MessageSecurityException e)
                    {
                        SessionBase.TraceSource.TraceEvent(TraceEventType.Warning, 0, "[Session:{0}] MessageSecurityException occured while attaching session: {1}", attachInfo.SessionId, e);

                        attachInfo.ClearCredential();
                        SessionBase.PurgeCredential(attachInfo);
                        if (Utility.CanRetry(retry, askForCredential, askForCredentialTimes))
                        {
                            if (typeOfExpectedCred == CredType.None)
                            {
                                typeOfExpectedCred = await CredUtil.GetCredTypeFromClusterAsync(attachInfo, binding).ConfigureAwait(false);
                            }

                            if (resourceProvider is IDisposable)
                            {
                                ((IDisposable)resourceProvider).Dispose();
                            }
                            continue;
                        }
                        else
                        {
                            throw;
                        }
                    }
                    catch (FaultException <SessionFault> ex)
                    {
                        typeOfExpectedCred = Utility.CanRetry(retry, askForCredential, askForCredentialTimes) ?
                                             CredUtil.GetCredTypeFromFaultCode(ex.Detail.Code) : CredType.None;
                        SessionBase.TraceSource.TraceEvent(TraceEventType.Warning, 0, "[Session:{0}] Fault exception occured while allocating resource. FaultCode = {1}", attachInfo.SessionId, ex.Detail.Code);

                        if (typeOfExpectedCred == CredType.None)
                        {
                            throw Utility.TranslateFaultException(ex);
                        }
                        else
                        {
                            attachInfo.ClearCredential();

                            if (resourceProvider is IDisposable)
                            {
                                ((IDisposable)resourceProvider).Dispose();
                            }
                            continue;
                        }
                    }
                    catch (CommunicationException e)
                    {
                        throw new SessionException(SOAFaultCode.ConnectSessionLauncherFailure, SR.ConnectSessionLauncherFailure, e);
                    }
                    catch (TimeoutException e)
                    {
                        throw new TimeoutException(string.Format(SR.ConnectSessionLauncherTimeout, Constant.DefaultCreateSessionTimeout), e);
                    }
                    catch (Exception e)
                    {
                        throw new SessionException(SOAFaultCode.UnknownError, e.ToString());
                    }
                } // while
            }
            finally
            {
                IDisposable disposableObject = resourceProvider as IDisposable;
                if (disposableObject != null)
                {
                    disposableObject.Dispose();
                }
            }

            if (String.IsNullOrEmpty(info.BrokerLauncherEpr) && !info.UseInprocessBroker)
            {
                if ((info.JobState &
                     (JobState.Configuring
                      | JobState.ExternalValidation
                      | JobState.Queued
                      | JobState.Running
                      | JobState.Submitted
                      | JobState.Validating)) != 0)
                {
                    throw new SessionException(string.Format(SR.AttachConfiguringSession, attachInfo.SessionId));
                }
                else
                {
                    throw new SessionException(string.Format(SR.AttachNoBrokerSession, attachInfo.SessionId));
                }
            }

            IBrokerFactory brokerFactory = BuildBrokerFactory(attachInfo, durable);

            try
            {
                return(await brokerFactory.AttachBroker(attachInfo, info, SessionBase.GetTimeout(targetTimeout), binding).ConfigureAwait(false));
            }
            finally
            {
                IDisposable disposableObject = brokerFactory as IDisposable;
                if (disposableObject != null)
                {
                    disposableObject.Dispose();
                }
            }
        }
        public override Task <SessionBase> AttachSession(SessionAttachInfo attachInfo, bool durable, int timeoutMilliseconds, Binding binding)
        {
            SessionAttachInfo info = attachInfo as SessionAttachInfo;

            NetworkCredential credential  = null;
            WebSessionInfo    sessionInfo = null;

            int  retry                 = 0;
            bool askForCredential      = false;
            int  askForCredentialTimes = 0;

            // User can try credential at most SessionBase.MaxRetryCount times.
            while (true)
            {
                retry++;
                SessionBase.TraceSource.TraceInformation("[Session:Unknown] Try to attach session via REST API. TryCount = {0}, IsDurable = {1}", retry, durable);
                askForCredential = SessionBase.RetrieveCredentialOnAzure(info);

                if (askForCredential)
                {
                    askForCredentialTimes++;
                }

                credential = Utility.BuildNetworkCredential(info.Username, info.InternalPassword);

                sessionInfo = null;

                HttpWebRequest attachSessionRequest = null;

                try
                {
                    // Following method needs to get cluster name, it may throw WebException because
                    // of invalid credential. Give chance to users to re-enter the credential.
                    attachSessionRequest = SOAWebServiceRequestBuilder.GenerateAttachSessionWebRequest(info.Headnode, info.SessionId, durable, credential);
                }
                catch (WebException e)
                {
                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        HttpWebResponse response = (HttpWebResponse)e.Response;
                        if (response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            // cleanup local cached invalid credential
                            info.ClearCredential();
                            SessionBase.PurgeCredential(info);

                            if (Utility.CanRetry(retry, askForCredential, askForCredentialTimes))
                            {
                                response.Close();
                                continue;
                            }
                        }
                    }

                    SessionBase.TraceSource.TraceEvent(
                        TraceEventType.Error, 0, "[Session:Unknown] Failed to build AttachSession request: {0}", e);

                    Utility.HandleWebException(e);
                }

                try
                {
                    using (WebResponse response = attachSessionRequest.GetResponse())
                        using (Stream stream = response.GetResponseStream())
                        {
                            sessionInfo = Utility.BuildWebSessionInfoFromDataContract((WebSessionInfoContract)this.webSessionInfoSerializer.ReadObject(stream));
                        }

                    break;
                }
                catch (WebException e)
                {
                    SessionBase.TraceSource.TraceEvent(
                        TraceEventType.Error, 0, "[Session:Unknown] Failed to attach session via REST API: {0}", e);

                    Utility.HandleWebException(e);
                }
            }

            SessionBase.SaveCrendential(info);

            sessionInfo.HeadNode   = info.Headnode;
            sessionInfo.Credential = credential;

            if (durable)
            {
#if net40
                return(TaskEx.FromResult <SessionBase>(new DurableSession(sessionInfo, attachInfo.Headnode, binding)));
#else
                return(Task.FromResult <SessionBase>(new DurableSession(sessionInfo, attachInfo.Headnode, binding)));
#endif
            }
            else
            {
#if net40
                return(TaskEx.FromResult <SessionBase>(new V3Session(sessionInfo, attachInfo.Headnode, true, binding)));
#else
                return(Task.FromResult <SessionBase>(new V3Session(sessionInfo, attachInfo.Headnode, true, binding)));
#endif
            }
        }
        /// <summary>
        /// Attach to a broker, returns session instance
        /// </summary>
        /// <param name="attachInfo">indicating the attach information</param>
        /// <param name="info">indicating the session info to be updated</param>
        /// <param name="timeout">indicating the timeout</param>
        /// <param name="binding">indicating the binding</param>
        /// <returns>returns the session instance</returns>
        public async Task <SessionBase> AttachBroker(SessionAttachInfo attachInfo, SessionInfo info, TimeSpan timeout, Binding binding)
        {
            SessionBase session;

            try
            {
                session = InprocessSessions.GetInstance().FetchSessionInstance(attachInfo.SessionId);
            }
            catch (SessionException e)
            {
                if (this.durable && attachInfo.SessionId == InprocessSessions.DebugModeSessionId && e.ErrorCode == SOAFaultCode.Session_ValidateJobFailed_AlreadyFinished)
                {
                    session = null;
                }
                else
                {
                    throw;
                }
            }


            if (session == null)
            {
                if (this.durable)
                {
                    if (attachInfo.SessionId != InprocessSessions.DebugModeSessionId)
                    {
                        throw new SessionException(SOAFaultCode.InvalidSessionId, String.Format(SR.Broker_InvalidSessionId, attachInfo.SessionId));
                    }

                    SessionStartInfo startInfo = InprocessSessions.GetInstance().PreviousSessionStartInfo;
                    if (startInfo != null)
                    {
                        DateTime targetTimeout;
                        if (timeout == TimeSpan.MaxValue)
                        {
                            targetTimeout = DateTime.MaxValue;
                        }
                        else
                        {
                            targetTimeout = DateTime.Now.Add(timeout);
                        }

                        return(await this.CreateBrokerInternal(startInfo, attachInfo.SessionId, true, binding).ConfigureAwait(false));
                    }
                }

                throw new SessionException(SOAFaultCode.Session_ValidateJobFailed_AlreadyFinished, SR.Session_ValidateJobFailed_AlreadyFninshed);
            }
            else
            {
                if (this.durable)
                {
                    if (session is V3Session)
                    {
                        throw new SessionException(SOAFaultCode.InvalidAttachInteractiveSession, SR.InvalidAttachInteractiveSession);
                    }
                }
                else
                {
                    if (session is DurableSession)
                    {
                        throw new SessionException(SOAFaultCode.InvalidAttachDurableSession, SR.InvalidAttachDurableSession);
                    }
                }

                Debug.Assert(session.Info is SessionInfo, "[InprocessBrokerFactory] session.Info must be the type SessionInfo for inprocess broker.");
                SessionInfo sessionInfo = (SessionInfo)session.Info;
                Debug.Assert(sessionInfo.InprocessBrokerAdapter != null, "[InprocessBrokerFactory] session.Info.InprocessBrokerAdapter must be not null for inprocess broker.");
                sessionInfo.InprocessBrokerAdapter.Attach(session.Id);
            }

            return(session);
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            const string headnode    = "[headnode]";
            const string serviceName = "EchoService";

            if (args.Length == 1)
            {
                // attach to the session
                int sessionId          = Int32.Parse(args[0]);
                SessionAttachInfo info = new SessionAttachInfo(headnode, sessionId);

                Console.Write("Attaching to session {0}...", sessionId);
                // Create attach to a session
                using (DurableSession session = DurableSession.AttachSession(info))
                {
                    Console.WriteLine("done.");

                    // Create a client proxy
                    using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
                    {
                        Console.WriteLine("Retrieving results...");
                        // Get all the results
                        foreach (BrokerResponse <EchoResponse> response in client.GetResponses <EchoResponse>())
                        {
                            string reply = response.Result.EchoResult;
                            Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply);
                        }
                        Console.WriteLine("Done retrieving results.");
                    }

                    // Close the session to reclaim the system storage
                    // used to store the results.  After the session is closed
                    // you cannot attatch to the same session again
                    session.Close();
                }
            }
            else
            {
                // Create a durable session, fire the requests and exit
                SessionStartInfo info = new SessionStartInfo(headnode, serviceName);
                Console.Write("Creating a session...");
                using (DurableSession session = DurableSession.CreateSession(info))
                {
                    Console.WriteLine("done session id = {0}.", session.Id);
                    NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);

                    using (BrokerClient <IService1> client = new BrokerClient <IService1>(session, binding))
                    {
                        Console.Write("Sending requests...");
                        for (int i = 0; i < 12; i++)
                        {
                            EchoRequest request = new EchoRequest("hello world!");
                            client.SendRequest <EchoRequest>(request, i);
                        }
                        client.EndRequests();
                        Console.WriteLine("done");
                    }

                    Console.WriteLine("Type \"FileNRecollect.exe {0}\" to collect the results", session.Id);
                }
            }
        }
Beispiel #25
0
 private IResourceProvider BuildResourceProvider(SessionAttachInfo attachInfo, Binding binding)
 {
     return(new GeneralResourceProvider(attachInfo, binding));
 }
Beispiel #26
0
        public void BvtDurableCase1()
        {
            Info("Start BVT");
            SessionStartInfo sessionStartInfo;

            sessionStartInfo        = BuildSessionStartInfo(Server, EchoSvcName, null, null, null, null, SessionUnitType.Node, null, null, null);
            sessionStartInfo.Secure = false;
            string serviceJobId;

            Info("Begin to create Durable Session.");
            string guid = Guid.NewGuid().ToString();

            using (DurableSession session = DurableSession.CreateSession(sessionStartInfo))
            {
                serviceJobId = session.Id;
                var epr = new EndpointAddress(string.Format(NetTcpEndpointPattern, Server, serviceJobId));
                Info("EPR: {0}", epr);
                try
                {
                    Info("Client {0}: Begin to send requests.", guid);
                    using (BrokerClient <IEchoSvc> client = new BrokerClient <IEchoSvc>(guid, session))
                    {
                        for (int i = 0; i < NumberOfCalls; i++)
                        {
                            client.SendRequest <EchoRequest>(new EchoRequest(i.ToString()), i + ":" + guid);
                        }

                        Info("Client {0}: Begin to call EndOfMessage.", guid);
                        client.EndRequests();
                    }
                }
                catch (Exception e)
                {
                    Error("Unexpected exception of Client {0}", e.ToString());
                    throw;
                }
            }

            // sleep 10 seconds
            Info("Client disconnects and sleep 10 seconds");
            Thread.Sleep(10000);

            SessionAttachInfo sessionAttachInfo = new SessionAttachInfo(Server, serviceJobId);
            int count = 0;

            Info("Begin to attach Durable Session.");
            try
            {
                using (DurableSession session = DurableSession.AttachSession(sessionAttachInfo))
                {
                    Info("Begin to retrieve results.");
                    using (BrokerClient <IEchoSvc> client = new BrokerClient <IEchoSvc>(guid, session))
                    {
                        foreach (BrokerResponse <EchoResponse> response in client.GetResponses <EchoResponse>())
                        {
                            Info(response.Result.EchoResult);
                            string[] rtn = response.Result.EchoResult.Split(new[] { ':' });
                            Assert(
                                rtn[rtn.Length - 1] == response.GetUserData <string>().Split(new[] { ':' })[0] && response.GetUserData <string>().Split(new[] { ':' })[1] == guid,
                                "Result is corrupt: expected:computername:{0}, actual:{1}",
                                response.GetUserData <string>().Split(new[] { ':' })[0],
                                response.Result.EchoResult);
                            count++;
                        }
                    }

                    session.Close();
                }

                if (NumberOfCalls == count)
                {
                    Info("Total {0} calls returned.", count);
                }
                else
                {
                    Error("Total {0} calls returned, but losing {1} results.\n", count, NumberOfCalls - count);
                }
            }
            catch (Exception e)
            {
                Error("Unexpected exception during attaching and getting response {0}", e.ToString());
                throw;
            }
        }
Beispiel #27
0
        public void BvtDurableCase2()
        {
            Info("Start BVT");
            SessionStartInfo sessionStartInfo;

            sessionStartInfo        = BuildSessionStartInfo(Server, EchoSvcName, null, null, null, null, SessionUnitType.Node, null, null, null);
            sessionStartInfo.Secure = false;
            Info("Begin to create session");
            string         serviceJobId;
            int            clientNum     = 2;
            AutoResetEvent anotherClient = new AutoResetEvent(false);

            Task[]         tasks   = new Task[clientNum];
            DurableSession session = DurableSession.CreateSession(sessionStartInfo);

            serviceJobId = session.Id;

            SessionAttachInfo sessionAttachInfo = new SessionAttachInfo(Server, serviceJobId);

            for (int i = 0; i < clientNum; i++)
            {
                var idx = i;
                tasks[i] = Task.Run(
                    () =>
                {
                    string guid = Guid.NewGuid().ToString();
                    using (DurableSession attachSession = DurableSession.AttachSession(sessionAttachInfo))
                    {
                        try
                        {
                            Info("Client {0}: Begin to send requests.", guid);
                            using (BrokerClient <IEchoSvc> client = new BrokerClient <IEchoSvc>(guid, attachSession))
                            {
                                for (int j = 0; j < NumberOfCalls; j++)
                                {
                                    client.SendRequest <EchoRequest>(new EchoRequest(j.ToString()), j + ":" + guid);
                                }

                                Info("Client {0}: Begin to call EndOfMessage.", guid);
                                client.EndRequests();
                                Info("Client {0}: Begin to get responses.", guid);
                                int count = 0;
                                if (idx == 0)
                                {
                                    foreach (BrokerResponse <EchoResponse> response in client.GetResponses <EchoResponse>())
                                    {
                                        count++;
                                        Info(response.Result.EchoResult);
                                        string[] rtn = response.Result.EchoResult.Split(new[] { ':' });
                                        Assert(
                                            rtn[rtn.Length - 1] == response.GetUserData <string>().Split(new[] { ':' })[0] && response.GetUserData <string>().Split(new[] { ':' })[1] == guid,
                                            "Result is corrupt: expected:computername:{0}, actual:{1}",
                                            response.GetUserData <string>().Split(new[] { ':' })[0],
                                            response.Result.EchoResult);
                                    }
                                }
                                else
                                {
                                    foreach (var response in client.GetResponses())
                                    {
                                        count++;
                                        EchoResponse result = (EchoResponse)response.Result;
                                        Info(result.EchoResult);
                                        string[] rtn = result.EchoResult.Split(new[] { ':' });
                                        Assert(
                                            rtn[rtn.Length - 1] == response.GetUserData <string>().Split(new[] { ':' })[0] && response.GetUserData <string>().Split(new[] { ':' })[1] == guid,
                                            "Result is corrupt: expected:computername:{0}, actual:{1}",
                                            response.GetUserData <string>(),
                                            result.EchoResult);
                                    }
                                }

                                if (count == NumberOfCalls)
                                {
                                    Info("Client {0}: Total {1} calls returned.", guid, count);
                                }
                                else
                                {
                                    Error("Client {0}: Total {1} calls returned, but losing {2} results.", guid, count, NumberOfCalls - count);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Error("Unexpected exception of Client {0}", e.ToString());
                            throw;
                        }
                        finally
                        {
                            if (Interlocked.Decrement(ref clientNum) <= 0)
                            {
                                anotherClient.Set();
                            }
                        }
                    }
                });
            }

            anotherClient.WaitOne();
            Task.WaitAll(tasks);
            session.Close(true);
            session.Dispose();
        }
Beispiel #28
0
        public static async Task <bool> RetrieveCredentialOnPremise(SessionAttachInfo info, CredType expectedCredType, Binding binding)
        {
            bool popupDialog = false;

            // Make sure that we have a password and credentials for the user.
            if (String.IsNullOrEmpty(info.Username) || String.IsNullOrEmpty(info.InternalPassword))
            {
                string username = null;

                // First try to get something from the cache.
                if (String.IsNullOrEmpty(info.Username))
                {
                    username = WindowsIdentity.GetCurrent().Name;
                }
                else
                {
                    username = info.Username;
                }

                // Use local machine name for session without service job
                string headnode = info.Headnode;
                if (String.IsNullOrEmpty(headnode))
                {
                    headnode = Environment.MachineName;
                }

                // For back compact, get the cached password if it exists.
                byte[] cached = CredentialHelper.FetchPassword(headnode, username);
                if (cached != null)
                {
                    info.Username         = username;
                    info.InternalPassword = Encoding.Unicode.GetString(ProtectedData.Unprotect(cached, null, DataProtectionScope.CurrentUser));
                }
                else
                {
                    if (expectedCredType != CredType.None)
                    {
                        if (expectedCredType == CredType.Either || expectedCredType == CredType.Either_CredUnreusable)
                        {
                            // Pops up dialog asking users to specify the type of the credetial (password or certificate).
                            // The behavior here aligns with the job submission.
                            expectedCredType = CredUtil.PromptForCredentialType(bConsole, hwnd, expectedCredType);
                        }

                        Debug.Assert(expectedCredType == CredType.Password ||
                                     expectedCredType == CredType.Password_CredUnreusable ||
                                     expectedCredType == CredType.Certificate);

                        if (expectedCredType == CredType.Password)
                        {
                            bool         fSave    = false;
                            SecureString password = null;
                            Credentials.PromptForCredentials(headnode, ref username, ref password, ref fSave, bConsole, hwnd);
                            popupDialog = true;

                            info.Username         = username;
                            info.SavePassword     = fSave;
                            info.InternalPassword = Credentials.UnsecureString(password);
                        }
                        else if (expectedCredType == CredType.Password_CredUnreusable)
                        {
                            SecureString password = null;
                            Credentials.PromptForCredentials(headnode, ref username, ref password, bConsole, hwnd);
                            popupDialog = true;

                            info.Username         = username;
                            info.SavePassword     = false;
                            info.InternalPassword = Credentials.UnsecureString(password);
                        }
                        else
                        {
                            // Get the value of cluster parameter HpcSoftCardTemplate.
                            SessionLauncherClient client = new SessionLauncherClient(await Utility.GetSessionLauncherAsync(info, binding).ConfigureAwait(false), binding, info.IsAadOrLocalUser);
                            string softCardTemplate      = String.Empty;
                            try
                            {
                                softCardTemplate = await client.GetSOAConfigurationAsync(Constant.HpcSoftCardTemplateParam).ConfigureAwait(false);
                            }
                            finally
                            {
                                Utility.SafeCloseCommunicateObject(client);
                            }

                            // Query certificate from local store, and pops up CertSelectionDialog.
                            SecureString pfxPwd;
                            info.Certificate = CredUtil.GetCertFromStore(null, softCardTemplate, bConsole, hwnd, out pfxPwd);
                            info.PfxPassword = Credentials.UnsecureString(pfxPwd);
                        }
                    }
                    else
                    {
                        // Expect to use the cached credential at scheuler side.
                        // Exception may happen later if no cached redential or it is invalid.
                        info.ClearCredential();
                        info.Username = username;
                    }
                }
            }

            return(popupDialog);
        }
Beispiel #29
0
 /// <summary>
 /// Attach to a existing session with the session attach info
 /// </summary>
 /// <param name="attachInfo">The attach info</param>
 /// <returns>A persistant session</returns>
 public static V3Session AttachSession(SessionAttachInfo attachInfo)
 {
     return(AttachSession(attachInfo, null));
 }
Beispiel #30
0
 /// <summary>
 /// Attach to a existing session async with the session attach info
 /// </summary>
 /// <param name="attachInfo">The attach info</param>
 /// <returns>A persistant session</returns>
 public static async Task <V3Session> AttachSessionAsync(SessionAttachInfo attachInfo)
 {
     return(await AttachSessionAsync(attachInfo, null).ConfigureAwait(false));
 }