Ejemplo n.º 1
0
        async Task<ResolvedServicePartition> getRsp(PartInfo part, ResolvedServicePartition prev)
        {
            ResolvedServicePartition rsp = null;

            try
            {               
                switch (part.Kind)
                {
                    case ServicePartitionKind.Singleton:
                        rsp = await Client.ServiceManager.ResolveServicePartitionAsync(part.Message.Headers.To, prev, this.timeout);
                        break;
                    case ServicePartitionKind.Int64Range:
                        rsp = await Client.ServiceManager.ResolveServicePartitionAsync(part.Message.Headers.To, part.RangeKey, prev, this.timeout);
                        break;
                    case ServicePartitionKind.Named:
                        rsp = await Client.ServiceManager.ResolveServicePartitionAsync(part.Message.Headers.To, part.NameKey, prev, this.timeout);
                        break;
                }
            }
            catch (AggregateException e)
            {
                log.Error(e, "Resolved for service {0} with partition key {1}. Found no endpoints.",
                    part.Message.Headers.To,
                    part.ToString());
                return null;
            }

            log.Info("Resolve for service {0} with partition key {1}. Found {2} endpoints.",
                        part.Message.Headers.To,
                        part.KindName,
                        rsp.Endpoints.Count);
            return rsp;
        }
Ejemplo n.º 2
0
        public Task <IServiceRemotingClient> GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector,
                                                            string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken)
        {
            ServicePartitionKey partitionKey;

            switch (previousRsp.Info.Kind)
            {
            case ServicePartitionKind.Singleton:
                partitionKey = new ServicePartitionKey();
                break;

            case ServicePartitionKind.Int64Range:
                partitionKey = new ServicePartitionKey(((Int64RangePartitionInformation)previousRsp.Info).LowKey);
                break;

            case ServicePartitionKind.Named:
                partitionKey = new ServicePartitionKey(((NamedPartitionInformation)previousRsp.Info).Name);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(GetClientAsync(previousRsp.ServiceName, partitionKey,
                                  targetReplicaSelector, listenerName, retrySettings, cancellationToken));
        }
        public static async Task <Dictionary <string, List <string> > > GetEndpointsInfo(StatelessServiceContext context, ConfigSettings configSettings)
        {
            string serviceUri = $"{context.CodePackageActivationContext.ApplicationName}/{configSettings.NCacheServiceName}";


            ServicePartitionResolver resolver = ServicePartitionResolver.GetDefault();

            ResolvedServicePartition resolvedServicePartition = await resolver.ResolveAsync(new Uri(serviceUri), new ServicePartitionKey(), new System.Threading.CancellationToken());

            var endpoints          = resolvedServicePartition.Endpoints;
            var endpointDictionary =
                new Dictionary <string, List <string> >();

            JObject addresses;
            //   string web_management_address;
            string bridge_management_address;
            string cache_management_address;
            string cache_client_address;
            string bridge_client_address;

            foreach (var endpoint1 in endpoints)
            {
                addresses = JObject.Parse(endpoint1.Address);
                //      web_management_address = (string)addresses["Endpoints"]["web-management"];
                bridge_management_address = (string)addresses["Endpoints"]["bridge-management"];
                cache_management_address  = (string)addresses["Endpoints"]["cache-management"];
                cache_client_address      = (string)addresses["Endpoints"]["cache-client"];
                bridge_client_address     = (string)addresses["Endpoints"]["bridge-client"];

                //if (!endpointDictionary.ContainsKey("web-management"))
                //{
                //    endpointDictionary["web-management"] = new List<string>();
                //}
                if (!endpointDictionary.ContainsKey("bridge-management"))
                {
                    endpointDictionary["bridge-management"] = new List <string>();
                }
                if (!endpointDictionary.ContainsKey("cache-management"))
                {
                    endpointDictionary["cache-management"] = new List <string>();
                }
                if (!endpointDictionary.ContainsKey("cache-client"))
                {
                    endpointDictionary["cache-client"] = new List <string>();
                }
                if (!endpointDictionary.ContainsKey("bridge-client"))
                {
                    endpointDictionary["bridge-client"] = new List <string>();
                }

                //     endpointDictionary["web-management"].Add(web_management_address);
                endpointDictionary["bridge-management"].Add(bridge_management_address);
                endpointDictionary["cache-management"].Add(cache_management_address);
                endpointDictionary["cache-client"].Add(cache_client_address);
                endpointDictionary["bridge-client"].Add(bridge_client_address);
            }

            return(endpointDictionary);
        }
        public async Task <IServiceRemotingClient> GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken)
        {
            IServiceRemotingClient innerClient = await _innerClientFactory
                                                 .GetClientAsync(previousRsp, targetReplicaSelector, listenerName, retrySettings, cancellationToken)
                                                 .ConfigureAwait(false);

            return(new CorrelatingServiceRemotingClient(innerClient, previousRsp.ServiceName, _methodNameProvider));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Enqueues a new item to the queue.
        /// </summary>
        /// <param name="items">Items of type <typeparamref name="TItem"/> to enqueue.</param>
        /// <param name="queue">Destination queue. Default is queue zero.</param>
        /// <param name="lease">Duration after a dequeue operation when the items lease will expire.</param>
        /// <param name="expiration">Duration after enqueue when the item expires and will not be processed.</param>
        /// <param name="cancellationToken">CancellationToken instance.</param>
        /// <param name="activityId">Activity identifier. If one is not provided a new one will be generated.</param>
        /// <returns>List containing the enqueued QueueItem&lt;TItem&gt;.</returns>
        /// <remarks>The list of QueueItem&lt;TItem&gt; are returned in case the querying of the status of an item is desired.</remarks>
        public async Task <IEnumerable <QueueItem <TItem> > > EnqueueAsync(IEnumerable <TItem> items,
                                                                           int queue           = QueueType.FirstQueue,
                                                                           TimeSpan lease      = default(TimeSpan),
                                                                           TimeSpan expiration = default(TimeSpan),
                                                                           CancellationToken cancellationToken = default(CancellationToken),
                                                                           string activityId = null)
        {
            Guard.ArgumentNotNull(items, nameof(items));

            IEnumerable <QueueItem <TItem> > list = null;

            // Get the next partition to add the items to, this is a simple round robin from 0 to number of partitions.
            long   partition   = NextEnqueuePartition();
            string queryParams = activityId ?? Guid.NewGuid().ToString();

            // Parse the optional time based parameters
            if ((default(TimeSpan) != lease) && (default(TimeSpan) != expiration))
            {
                queryParams = $"{queryParams}&leaseSeconds ={lease}&expirationMinutes={expiration}";
            }
            else if (default(TimeSpan) != lease)
            {
                queryParams = $"{queryParams}&leaseSeconds={lease}";
            }
            else if (default(TimeSpan) != lease)
            {
                queryParams = $"{queryParams}&expirationMinutes={expiration}";
            }

            // Build part of the uri.
            string relativeUri = $"/api/{queue}?requestid={queryParams}";

            // Create the content.
            string json = JsonConvert.SerializeObject(items);

            // Get the Resolved ServicePartition for the specified partition.
            ResolvedServicePartition rsp = await GetRspAsync(partition, cancellationToken).ConfigureAwait(false);

            // Make the HTTP request. CallAsync handles retries and moving endpoints.
            list = await CallAsync(rsp, cancellationToken, async (serviceEndpoints, ct) =>
            {
                string uri = serviceEndpoints.GetFirstEndpoint() + relativeUri;
                using (HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"))
                    using (HttpResponseMessage result = await _http.PostAsync(uri, content, cancellationToken).ConfigureAwait(false))
                    {
                        if (result.IsSuccessStatusCode)
                        {
                            return(result.GetResult <IEnumerable <QueueItem <TItem> > >());
                        }

                        // TODO: Replace with specific exception rather than this one.
                        throw new HttpRequestException(result.ReasonPhrase, new WebException(result.ReasonPhrase, WebExceptionStatus.ConnectFailure));
                    }
            });

            // Return the list.
            return(list);
        }
Ejemplo n.º 6
0
        private async Task ProcessInputRequest(HttpListenerContext context, CancellationToken cancelRequest)
        {
            String output = null;

            try
            {
                string lastname = context.Request.QueryString["lastname"];

                // The partitioning scheme of the processing service is a range of integers from 0 - 25.
                // This generates a partition key within that range by converting the first letter of the input name
                // into its numerica position in the alphabet.
                char firstLetterOfLastName       = lastname.First();
                ServicePartitionKey partitionKey = new ServicePartitionKey(Char.ToUpper(firstLetterOfLastName) - 'A');

                // This contacts the Service Fabric Naming Services to get the addresses of the replicas of the processing service
                // for the partition with the partition key generated above.
                // Note that this gets the most current addresses of the partition's replicas,
                // however it is possible that the replicas have moved between the time this call is made and the time that the address is actually used
                // a few lines below.
                // For a complete solution, a retry mechanism is required.
                // For more information, see http://aka.ms/servicefabricservicecommunication
                ResolvedServicePartition partition = await this.servicePartitionResolver.ResolveAsync(alphabetServiceUri, partitionKey, cancelRequest);

                ResolvedServiceEndpoint ep = partition.GetEndpoint();

                JObject addresses             = JObject.Parse(ep.Address);
                string  primaryReplicaAddress = (string)addresses["Endpoints"].First();

                UriBuilder primaryReplicaUriBuilder = new UriBuilder(primaryReplicaAddress);
                primaryReplicaUriBuilder.Query = "lastname=" + lastname;

                string result = await this.httpClient.GetStringAsync(primaryReplicaUriBuilder.Uri);

                output = String.Format(
                    "Result: {0}. <p>Partition key: '{1}' generated from the first letter '{2}' of input value '{3}'. <br>Processing service partition ID: {4}. <br>Processing service replica address: {5}",
                    result,
                    partitionKey,
                    firstLetterOfLastName,
                    lastname,
                    partition.Info.Id,
                    primaryReplicaAddress);
            }
            catch (Exception ex)
            {
                output = ex.Message;
            }

            using (HttpListenerResponse response = context.Response)
            {
                if (output != null)
                {
                    response.ContentType = "text/html";

                    byte[] outBytes = Encoding.UTF8.GetBytes(output);
                    response.OutputStream.Write(outBytes, 0, outBytes.Length);
                }
            }
        }
        /// <inheritdoc/>
        public async Task <string> GetPartitionEndPointAsync(string instanceId, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            long hash = await this.instanceIdHasher.GeneratePartitionHashCodeAsync(instanceId, cancellationToken);

            ResolvedServicePartition partition = await this.partitionResolver.ResolveAsync(this.serviceUri, new ServicePartitionKey(hash), cancellationToken);

            return(partition.GetEndpoint().Address);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Resolves a partition of the specified service by invoking FabricClient's
 /// <see cref="FabricClient.ServiceManagementClient.ResolveServicePartitionAsync(System.Uri)" />method with back-off/retry on retry-able errors. This takes in
 /// the resolved service partition that was got via an earlier invocation of the ResolveAsync() method.
 /// This method overload is used in cases where the client knows that the resolved service partition that it has is no longer valid.
 /// </summary>
 /// <param name="previousRsp">The resolved service partition that the client got from the earlier invocation of the ResolveAsync() method.</param>
 /// <param name="cancellationToken">
 /// <para>
 /// The CancellationToken that this operation is observing. It is used to notify the operation that it should be canceled.
 /// </para>
 /// </param>
 /// <returns>
 /// A <see cref="System.Threading.Tasks.Task">Task</see> that represents outstanding operation. The result from
 /// the task is the <see cref="System.Fabric.ResolvedServicePartition" /> object, that contains the information
 /// about the resolved service partition including the service endpoints.
 /// </returns>
         /// <exception cref="System.Fabric.FabricServiceNotFoundException">
         /// <para>
         /// This method can throw a FabricServiceNotFoundExcepion if the service which was resolved previously is no longer present in the cluster.
         /// </para>
         /// </exception>
         /// <remarks>
         /// <para>
         /// This method retries on all transient exceptions. For cases where you want to limit the max execution time of this method, you should create a <see href="https://docs.microsoft.com/en-us/dotnet/core/api/system.threading.cancellationtokensource#System_Threading_CancellationTokenSource__ctor_System_TimeSpan_">cancellation token associated with that max execution time</see>
         /// and pass that cancellation token to this method.
         /// </para>
         /// </remarks>
 public Task <ResolvedServicePartition> ResolveAsync(
     ResolvedServicePartition previousRsp,
     CancellationToken cancellationToken)
 {
     return(this.ResolveAsync(
                previousRsp,
                DefaultResolveTimeout,
                DefaultMaxRetryBackoffInterval,
                cancellationToken));
 }
Ejemplo n.º 9
0
        public static async Task <string> GetManagementApiEndPointAsync(string FabricEndPoint, string sMgmtAppInstanceName)
        {
            FabricClient             fc        = new FabricClient(FabricEndPoint);
            ResolvedServicePartition partition = await fc.ServiceManager.ResolveServicePartitionAsync(new Uri(sMgmtAppInstanceName));

            var jsonAddress = JObject.Parse(partition.GetEndpoint().Address);
            var address     = (string)jsonAddress["Endpoints"][""];

            return(address);
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Serializes the object to JSON.
 /// </summary>
 /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param>
 /// <param name="obj">The object to serialize to JSON.</param>
 internal static void Serialize(JsonWriter writer, ResolvedServicePartition obj)
 {
     // Required properties are always serialized, optional properties are serialized when not null.
     writer.WriteStartObject();
     writer.WriteProperty(obj.Name, "Name", ServiceNameConverter.Serialize);
     writer.WriteProperty(obj.PartitionInformation, "PartitionInformation", PartitionInformationConverter.Serialize);
     writer.WriteEnumerableProperty(obj.Endpoints, "Endpoints", ResolvedServiceEndpointConverter.Serialize);
     writer.WriteProperty(obj.Version, "Version", JsonWriterExtensions.WriteStringValue);
     writer.WriteEndObject();
 }
Ejemplo n.º 11
0
 public CommunicationClientCacheEntry()
 {
     this.Endpoint   = null;
     this.Semaphore  = new SemaphoreSlim(1, 1);
     this.client     = default(TCommunicationClient);
     this.clientWRef = null;
     this.rsp        = null;
     this.address    = null;
     this.IsInCache  = true;
 }
Ejemplo n.º 12
0
        public async Task <IServiceRemotingClient> GetClientAsync(ResolvedServicePartition previousRsp,
                                                                  TargetReplicaSelector targetReplicaSelector,
                                                                  string listenerName,
                                                                  OperationRetrySettings retrySettings,
                                                                  CancellationToken cancellationToken)
        {
            var client = await serviceRemotingClientFactory.GetClientAsync(previousRsp, targetReplicaSelector, listenerName, retrySettings, cancellationToken);

            return(new ServiceRemotingClientWrapper(client, traceId));
        }
 /// <summary>
 /// Re-resolves a partition of the specified service containing one or more communication listeners and returns a client to communicate
 /// to the endpoint corresponding to the given listenerName.
 /// The endpoint of the service is of the form - {"Endpoints":{"Listener1":"Endpoint1","Listener2":"Endpoint2" ...}}
 /// </summary>
 /// <param name="previousRsp">Previous ResolvedServicePartition value</param>
 /// <param name="targetReplicaSelector">Specifies which replica in the partition identified by the partition key, the client should connect to</param>
 /// <param name="listenerName">Specifies which listener in the endpoint of the chosen replica, to which the client should connect to</param>
 /// <param name="retrySettings">Specifies the retry policy that should be used for exceptions that occur when creating the client.</param>
 /// <param name="cancellationToken">Cancellation token</param>
 /// <returns>
 /// A <see cref="System.Threading.Tasks.Task">Task</see> that represents outstanding operation. The result of the Task is
 /// the CommunicationClient(<see cref="ICommunicationClient" />) object.
 /// </returns>
 public async Task <IServiceRemotingClient> GetClientAsync(ResolvedServicePartition previousRsp,
                                                           TargetReplicaSelector targetReplicaSelector,
                                                           string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken)
 {
     return(await this.clientFactoryImpl.GetClientAsync(previousRsp,
                                                        targetReplicaSelector,
                                                        listenerName,
                                                        retrySettings,
                                                        cancellationToken));
 }
Ejemplo n.º 14
0
        public ServicePartitionResolutionChangeEventArgs(ResolvedServicePartition partition, Exception exception, long callbackId)
        {
            if (partition == null && exception == null)
            {
                throw new ArgumentNullException("partition", "Both partition and exception cannot be null at the same time");
            }

            this.Partition  = partition;
            this.Exception  = exception;
            this.CallbackId = callbackId;
        }
        public List <PartitionActors> Get()
        {
            Int64 highKey        = 9223372036854775807;
            Int64 lowKey         = -9223372036854775808;
            int   partitionCount = 10;
            Int64 partitionRange = highKey / partitionCount - lowKey / partitionCount; // number of elements per interval of range
            int   actorCount     = 0;

            CancellationToken cancellationToken = default(CancellationToken);

            List <PartitionActors>  partitionActors      = new List <PartitionActors>();
            List <ActorInformation> actorInformationList = new List <ActorInformation>();

            for (int i = 0; i < partitionCount; i++)
            {
                // this generates a key in each of the partitions
                var partitionKeyInPartition = lowKey + i * partitionRange + 10;

                // note proxy to actor service, not a specific actor
                var actorProxy = ActorServiceProxy.Create(new Uri("fabric:/SFActors.BankAccounts/BankAccountActorService"), partitionKeyInPartition);

                // get all the actors in the partition
                ContinuationToken continuationToken = null;
                do
                {
                    PagedResult <ActorInformation> page = actorProxy.GetActorsAsync(continuationToken, cancellationToken).GetAwaiter().GetResult();
                    actorInformationList.AddRange(page.Items);
                    continuationToken = page.ContinuationToken;
                } while (continuationToken != null);

                // find the partition id for the current partition key
                ServicePartitionKey      partitionKey             = new ServicePartitionKey(partitionKeyInPartition);
                ServicePartitionResolver servicePartitionResolver = ServicePartitionResolver.GetDefault();
                ResolvedServicePartition partition = servicePartitionResolver.ResolveAsync(new Uri("fabric:/SFActors.BankAccounts/BankAccountActorService"), partitionKey, cancellationToken).GetAwaiter().GetResult();

                // prepare the result
                if (actorInformationList.Count > 0)
                {
                    PartitionActors pa = new PartitionActors
                    {
                        PartitionId       = partition.Info.Id,
                        ActorsInPartition = actorInformationList.Select(x => x.ActorId.GetStringId()).ToList()
                    };
                    partitionActors.Add(pa);

                    actorCount += actorInformationList.Count;
                    actorInformationList.Clear();
                }
            }

            ServiceEventSource.Current.Message("@AccountsController. {0} actors in {1} partitions", actorCount, partitionActors.Count);

            return(partitionActors);
        }
Ejemplo n.º 16
0
        public static string GetServiceEndPoint(string fabricName, EventSource currentEventSource = null)
        {
            ServicePartitionResolver resolver  = ServicePartitionResolver.GetDefault();
            CancellationToken        token     = new CancellationToken(false);
            ResolvedServicePartition partition = resolver.ResolveAsync(new Uri(fabricName), new ServicePartitionKey(), token).Result;
            string address         = partition.GetEndpoint().Address;
            var    endpointAddress =
                JObject.Parse(address)["Endpoints"][""].ToString();

            return(endpointAddress);
        }
        public async Task <IServiceRemotingClient> GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken)
        {
            IServiceRemotingClient client = await this.innerFactory.GetClientAsync(
                previousRsp,
                targetReplicaSelector,
                listenerName,
                retrySettings,
                cancellationToken);

            return(new FabricTransportPipelineServiceRemotingClient(client));
        }
        public async Task <IServiceRemotingClient> GetClientAsync(
            ResolvedServicePartition previousRsp,
            TargetReplicaSelector targetReplicaSelector,
            string listenerName,
            OperationRetrySettings retrySettings,
            CancellationToken cancellationToken)
        {
            var client = await this._wrapped.GetClientAsync(previousRsp, targetReplicaSelector, listenerName, retrySettings, cancellationToken);

            return(new CustomServiceRemotingClient(client));
        }
Ejemplo n.º 19
0
        public async Task <IServiceRemotingClient> GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings,
                                                                  CancellationToken cancellationToken)
        {
            var client = await _innerClientFactory.GetClientAsync(
                previousRsp,
                targetReplicaSelector,
                listenerName,
                retrySettings,
                cancellationToken);

            return(new FabricTransportActorRemotingClient(client, previousRsp.ServiceName, _logger, _actorMethodDispatcher, _serviceMethodDispatcher));
        }
Ejemplo n.º 20
0
        protected virtual string GetEndpoint()
        {
            ServicePartitionResolver resolver  = ServicePartitionResolver.GetDefault();
            ResolvedServicePartition partition = resolver.ResolveAsync(ApplicationUri, new ServicePartitionKey(), new CancellationToken()).Result;

            ResolvedServiceEndpoint serviceEndpoint = partition.GetEndpoint();

            JObject addresses = JObject.Parse(serviceEndpoint.Address);
            string  endpoint  = (string)addresses["Endpoints"].First();

            return(endpoint);
        }
Ejemplo n.º 21
0
        public CommunicationClientCacheEntry <TCommunicationClient> GetOrAddClientCacheEntry(
            Guid partitionId,
            ResolvedServiceEndpoint endpoint,
            string listenerName,
            ResolvedServicePartition rsp)
        {
            var partitionClientCache = this.clientCache.GetOrAdd(
                partitionId,
                new PartitionClientCache(partitionId, this.traceId));

            return(partitionClientCache.GetOrAddClientCacheEntry(endpoint, listenerName, rsp));
        }
Ejemplo n.º 22
0
        protected string GetEndPoint(string address)
        {
            ServicePartitionResolver resolver  = ServicePartitionResolver.GetDefault();
            ResolvedServicePartition partition =
                resolver.ResolveAsync(new Uri(address), new ServicePartitionKey(), new CancellationToken()).Result;

            ResolvedServiceEndpoint endpoint = partition.GetEndpoint();

            JObject addresses = JObject.Parse(endpoint.Address);

            return((string)addresses["Endpoints"].First());
        }
Ejemplo n.º 23
0
        public static TestServicePartitionInfo Convert(ResolvedServicePartition resolvedPartition, ResolvedServiceEndpoint resolvedEndpoint, int partitionIdentifierNumber)
        {
            ThrowIf.Null(resolvedPartition, "resolvedPartition");
            ThrowIf.Null(resolvedEndpoint, "resolvedEndpoint");
            ServicePartitionKind keyType = ServicePartitionKind.Invalid;

            object rangeHighKey = null;
            object rangeLowKey  = null;

            switch (resolvedPartition.Info.Kind)
            {
            case ServicePartitionKind.Singleton:
                keyType = ServicePartitionKind.Singleton;
                break;

            case ServicePartitionKind.Int64Range:
                keyType      = ServicePartitionKind.Int64Range;
                rangeHighKey = ((System.Fabric.Int64RangePartitionInformation)resolvedPartition.Info).HighKey;
                rangeLowKey  = ((System.Fabric.Int64RangePartitionInformation)resolvedPartition.Info).LowKey;
                break;

            case ServicePartitionKind.Named:
                keyType = ServicePartitionKind.Named;
                break;

            default:
                throw new InvalidOperationException("Unknown ServicePartitionKind " + resolvedPartition.Info.Kind.ToString() + ".");
            }

            TestServicePartitionInfo testServicePartitionInfo = new TestServicePartitionInfo()
            {
                Location            = resolvedEndpoint.Address,
                Name                = resolvedPartition.ServiceName,
                Id                  = resolvedPartition.Info.Id,
                KeyType             = keyType,
                RangeHighKey        = rangeHighKey,
                RangeLowKey         = rangeLowKey,
                Role                = resolvedEndpoint.Role,
                PartitionIdentifier = partitionIdentifierNumber,
            };

            if (resolvedPartition.Endpoints.Any(e => e.Role == ServiceEndpointRole.StatefulPrimary))
            {
                testServicePartitionInfo.IsPrimaryEndpoint = resolvedPartition.GetEndpoint().Address == resolvedEndpoint.Address;
            }
            else
            {
                testServicePartitionInfo.IsPrimaryEndpoint = false;
            }

            return(testServicePartitionInfo);
        }
Ejemplo n.º 24
0
        public async Task <string> ResolveService(string serviceName)
        {
            ServicePartitionResolver resolver = ServicePartitionResolver.GetDefault();

            System.Threading.CancellationToken cancellationToken = default;
            ResolvedServicePartition           partition         = await resolver.ResolveAsync(new Uri($"fabric:/{serviceName}"), new ServicePartitionKey(), cancellationToken);

            var     endPoint  = partition.Endpoints.Random();
            dynamic address   = JsonConvert.DeserializeObject(endPoint.Address);
            string  urlString = address.Endpoints[""];

            return(urlString);
        }
Ejemplo n.º 25
0
 private static Task <ResolvedServicePartition> ResolveSingletonPartitionAsync(
     FabricClient client,
     Uri serviceName,
     ResolvedServicePartition previousRsp,
     TimeSpan timeout,
     CancellationToken cancellationToken)
 {
     return(client.ServiceManager.ResolveServicePartitionAsync(
                serviceName,
                previousRsp,
                timeout,
                cancellationToken));
 }
        private async Task <string> GetReplicaAddress(string captainType)
        {
            var cancelRequest = new CancellationToken();
            ServicePartitionKey partitionKey = new ServicePartitionKey(captainType);

            ResolvedServicePartition partition = await this.servicePartitionResolver.ResolveAsync(serviceUri, partitionKey, cancelRequest);

            ResolvedServiceEndpoint ep = partition.GetEndpoint();

            JObject addresses = JObject.Parse(ep.Address);

            return((string)addresses["Endpoints"].First());
        }
        private async Task <ResolvedServiceEndpoint> ResolveAnyEndpoint()
        {
            int random = Random.Next();
            ResolvedServicePartition resolved = await Resolver.ResolveAsync(FabricAddress, new ServicePartitionKey(), CancellationToken.None);

            ResolvedServiceEndpoint[] array = resolved.Endpoints.Where(
                e => e.Role == ServiceEndpointRole.StatefulPrimary || e.Role == ServiceEndpointRole.Stateless)
                                              .ToArray();
            if (array.Length == 0)
            {
                throw new FabricServiceNotFoundException("No live primary services found (name may or may not be correct)");
            }
            return(array[array.Length % random]);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Returns a value indicating whether or not <paramref name="left"/> is the same partition as <paramref name="right"/>.
        /// </summary>
        /// <param name="left">One resolved partition.</param>
        /// <param name="right">The other resolved partition.</param>
        /// <returns>
        /// <see langword="true"/> if <paramref name="left"/> is the same partition as <paramref name="right"/>, <see langword="false"/> otherwise.
        /// </returns>
        public static bool IsSamePartitionAs(this ResolvedServicePartition left, ResolvedServicePartition right)
        {
            if (ReferenceEquals(left, right))
            {
                return(true);
            }

            if (ReferenceEquals(null, left) || ReferenceEquals(null, right))
            {
                return(false);
            }

            return(left.Info.IsSamePartitionAs(right.Info));
        }
        private async Task ProcessInputRequest(HttpListenerContext context, CancellationToken cancelRequest)
        {
            String output = null;

            try
            {
                string vin = context.Request.QueryString["vin"];

                // The partitioning scheme of the processing service is a range of integers from 0 - 25.
                // This generates a partition key within that range by converting the first letter of the input name
                // into its numerica position in the alphabet.
                char firstLetterOfLastName = vin.First();
                int  partitionKey          = Char.ToUpper(firstLetterOfLastName) - 'A';

                // Get the Service Partition
                ResolvedServicePartition partition = await this.servicePartitionResolver.ResolveAsync(clientServiceUri, partitionKey, cancelRequest);

                ResolvedServiceEndpoint ep = partition.GetEndpoint();

                JObject addresses             = JObject.Parse(ep.Address);
                string  primaryReplicaAddress = addresses["Endpoints"]["Gateway"].Value <string>();

                string url = primaryReplicaAddress + "api/vehicles/" + vin + "/lock";

                UriBuilder primaryReplicaUriBuilder = new UriBuilder(url);

                string result = await this.httpClient.GetStringAsync(primaryReplicaUriBuilder.Uri);

                output = String.Format(
                    "Result: {0}. Partition key: '{1}' generated from the first letter '{2}' of input value '{3}'.",
                    result,
                    partitionKey,
                    firstLetterOfLastName,
                    vin);
            }
            catch (Exception ex)
            {
                output = ex.Message;
            }

            using (HttpListenerResponse response = context.Response)
            {
                if (output != null)
                {
                    byte[] outBytes = Encoding.UTF8.GetBytes(output);
                    response.OutputStream.Write(outBytes, 0, outBytes.Length);
                }
            }
        }
        /// <summary>
        /// Re-resolves a partition of the specified service containing one or more communication listeners and returns a client to communicate
        /// to the endpoint corresponding to the given listenerName.
        /// The endpoint of the service is of the form - {"Endpoints":{"Listener1":"Endpoint1","Listener2":"Endpoint2" ...}}
        /// </summary>
        /// <param name="previousRsp">Previous ResolvedServicePartition value</param>
        /// <param name="targetReplicaSelector">Specifies which replica in the partition identified by the partition key, the client should connect to</param>
        /// <param name="listenerName">Specifies which listener in the endpoint of the chosen replica, to which the client should connect to</param>
        /// <param name="retrySettings">Specifies the retry policy that should be used for exceptions that occur when creating the client.</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>
        /// A <see cref="System.Threading.Tasks.Task">Task</see> that represents outstanding operation. The result of the Task is
        /// the CommunicationClient(<see cref="ICommunicationClient" />) object.
        /// </returns>
        async Task <IServiceRemotingClient> ICommunicationClientFactory <IServiceRemotingClient> .GetClientAsync(
            ResolvedServicePartition previousRsp,
            TargetReplicaSelector targetReplicaSelector,
            string listenerName,
            OperationRetrySettings retrySettings,
            CancellationToken cancellationToken)
        {
            var client = await this.impl.GetClientAsync(
                previousRsp,
                targetReplicaSelector,
                listenerName,
                retrySettings,
                cancellationToken);

            return(client);
        }
        public async Task <IServiceRemotingClient> GetClientAsync(
            ResolvedServicePartition previousRsp,
            TargetReplicaSelector targetReplicaSelector,
            string listenerName,
            OperationRetrySettings retrySettings,
            CancellationToken cancellationToken)
        {
            var client = await _InnerClientFactory.GetClientAsync(
                previousRsp,
                targetReplicaSelector,
                listenerName,
                retrySettings,
                cancellationToken).ConfigureAwait(false);

            return(new TrackingFabricTransportServiceRemotingClient(client));
        }
 public virtual async Task<IServiceRemotingClient> GetClientAsync(ResolvedServicePartition previousRsp, string listenerName, CancellationToken cancellationToken)
 {
     var wcfClient = await WcfFactory.GetClientAsync(previousRsp, listenerName, cancellationToken).ConfigureAwait(false);
     return new WcfServiceRemotingClient(wcfClient);
 }