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]);
        }
        private static void CallCloud()
        {
            var binding           = WcfUtility.CreateTcpClientBinding();
            var partitionResolver = new ServicePartitionResolver("ilrprocessingsfpoc.uksouth.cloudapp.azure.com:777", "ilrprocessingsfpoc.uksouth.cloudapp.azure.com:19000");
            var wcfClientFactory  =
                new WcfCommunicationClientFactory <IValidationServiceStateful>(binding,
                                                                               servicePartitionResolver: partitionResolver);
            var serviceUri = new Uri("fabric:/DCT.ILR.Processing.POC/DCT.ILR.VadationServiceStateful");
            var client     = new ValidationServiceClient(wcfClientFactory, serviceUri, new ServicePartitionKey(LongRandom()));

            var resolved = partitionResolver.ResolveAsync(new Uri("fabric:/DCT.ILR.Processing.POC/DCT.ILR.VadationServiceStateful"),
                                                          new ServicePartitionKey(9223372036854775807), CancellationToken.None).Result;

            do
            {
                var correlationId = Guid.NewGuid();
                Console.WriteLine(client.Validation(new Models.Models.IlrContext()
                {
                    CorrelationId      = correlationId,
                    ContainerReference = "ilr-files",
                    Filename           = "ILR-10006341-1718-20171107-113456-01.xml",
                    //Filename = "ILR-10006148-1718-20170203-144336-03.xml",
                    IsShredAndProcess = false
                }).Result);
                Console.ReadKey();
            } while (true);
        }
        public async Task <IActionResult> CommunicationWithServiceRegistryQuery()
        {
            ServicePartitionResolver resolver = ServicePartitionResolver.GetDefault();

            var cancellationToken = new CancellationToken(); //TODO: use it!

            ResolvedServicePartition partition = await resolver.ResolveAsync(new Uri("fabric:/MyApp/MyService"), new ServicePartitionKey(), cancellationToken);

            string url     = "http://{0}/api/yourController";
            bool   urlIsOk = false;

            foreach (var endpoint in partition.Endpoints)
            {
                switch (endpoint.Role)
                {
                case ServiceEndpointRole.Stateless:     //TODO: implement load balancing!
                case ServiceEndpointRole.StatefulPrimary:
                    url     = string.Format(url, endpoint.Address);
                    urlIsOk = true;
                    break;

                case ServiceEndpointRole.Invalid:
                case ServiceEndpointRole.StatefulSecondary:     //TODO: may be used for read operations
                default:
                    continue;
                }
            }

            if (urlIsOk)
            {
                //DO YOUR STUFF
            }
            return(new OkResult());
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            string hostName = "sfv2.eastus.cloudapp.azure.com";

            Regex ipRex = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
            IServicePartitionResolver partitionResolver = new ServicePartitionResolver(hostName + ":19000");
            var binding = WcfUtility.CreateTcpClientBinding();


            var resolveResults = partitionResolver.ResolveAsync(new Uri("fabric:/CalculatorApplication/CalculatorService"),
                                                                ServicePartitionKey.Singleton,
                                                                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), new System.Threading.CancellationToken()).Result;

            var endpoint       = resolveResults.GetEndpoint();
            var endpointObject = JsonConvert.DeserializeObject <JObject>(endpoint.Address);
            var addressString  = ((JObject)endpointObject.Property("Endpoints").Value)[""].Value <string>();

            addressString = ipRex.Replace(addressString, hostName, 1);
            var endpointAddress = new EndpointAddress(addressString);
            var channel         = ChannelFactory <ICalculatorService> .CreateChannel(binding, endpointAddress);

            for (int i = 0; i < 10; i++)
            {
                var calculatorServiceCommunicationClient = new WcfCommunicationClient <ICalculatorService>(channel);
                var result = calculatorServiceCommunicationClient.Channel.Add(2, 3).Result;
                Console.WriteLine(result);
            }
        }
Beispiel #5
0
        public async void Post([FromUri] string value)
        {
            var firstDelimiter = value.IndexOf(';');
            var lastDelimiter  = value.LastIndexOf(';');

            var username  = value.Substring(0, firstDelimiter);
            var stockname = value.Substring(firstDelimiter + 1, value.Length - (firstDelimiter + 1));

            stockname = stockname.Substring(0, stockname.IndexOf(';'));

            var amount = value.Substring(lastDelimiter + 1, value.Length - (lastDelimiter + 1));

            int amountInt;

            if (int.TryParse(amount, out amountInt))
            {
                //Buyer.AddBidOnMatchingService(username, stockname, amountInt);
                ServicePartitionResolver resolver = ServicePartitionResolver.GetDefault();

                ResolvedServicePartition partition = await resolver.ResolveAsync(new System.Uri("fabric:/TSEIS1/Matcher"), new ServicePartitionKey(0), CancellationToken.None);

                // Converts the partition from JSON and gets the url
                var endpoints = Newtonsoft.Json.Linq.JObject.Parse(partition.GetEndpoint().Address)["Endpoints"];
                var url       = endpoints[""].ToString();
                var url1      = url.Substring(0, 23);

                // VIrker ikke

                string urlReverseProxy  = $"http://localhost:19081/TSEIS1/Matcher1/api/{value}?PartitionKey=0&PartitionKind=Int64Range";
                HttpResponseMessage msg = await _client.PostAsync(urlReverseProxy, null).ConfigureAwait(false);

                string urlReverseProxy1  = $"http://localhost:19081/TSEIS1/VotingState/api/{value}?PartitionKey=0&PartitionKind=Int64Range";
                HttpResponseMessage msg1 = await _client.PostAsync(urlReverseProxy1, null).ConfigureAwait(false);
            }
        }
Beispiel #6
0
        public async Task <IActionResult> PostToDo([FromBody] ToDo toDo)
        {
            int userId = GetUserId();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            toDo.UserId = userId;
            _context.ToDos.Add(toDo);
            await _context.SaveChangesAsync();

            ServicePartitionResolver servicePartitionResolver = ServicePartitionResolver.GetDefault();
            ResolvedServicePartition partition = await servicePartitionResolver.ResolveAsync(new Uri("fabric:/MyToDoListAttempt2/MailService"), new ServicePartitionKey(), CancellationToken.None);

            string endpoint = JObject.Parse(partition.GetEndpoint().Address)["Endpoints"].First.First.ToString();
            string email    = HttpContext.User.FindFirst("Email").Value;

            using (var httpClient = new HttpClient())
            {
                dynamic emailDto = new
                {
                    To      = email,
                    Subject = "New ToDo Added",
                    Content = toDo.Title
                };
                string emailDtoJson = JsonConvert.SerializeObject(emailDto);
                await httpClient.PostAsync(endpoint, new StringContent(emailDtoJson));
            }
            return(CreatedAtAction("GetToDo", new { id = toDo.Id }, toDo));
        }
Beispiel #7
0
        private async Task <T> GetResponseAsync <T>(
            Uri serviceName,
            string partitionName,
            string resource,
            CancellationToken cancellationToken)
        {
            var client   = new HttpClient();
            var resolver = new ServicePartitionResolver();

            // Resolve information about 'Partition'
            var partition = await resolver.ResolveAsync(serviceName, new ServicePartitionKey(partitionName), cancellationToken);

            // Get endpoint address information and retrieve ServiceEndpoint's address in particular.
            var address = partition.GetEndpoint().Address;
            var value   = JObject.Parse(address)["Endpoints"]?["ServiceEndpoint"]?.Value <string>();

            var response = await client.GetAsync($"{value}/{resource}", cancellationToken);

            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();

            var serializer = JsonSerializer.Create();

            using (var reader = new StringReader(json))
            {
                using (var jsonReader = new JsonTextReader(reader))
                {
                    return(serializer.Deserialize <T>(jsonReader));
                }
            }
        }
Beispiel #8
0
        private async Task QueryServicePartitions(List <BackupEnabledServiceReference> backupEnabledServices, Application app, Service service, Guid?partitionId)
        {
            string token;

            do
            {
                var partitions = await _fabricClient.QueryManager.GetPartitionListAsync(service.ServiceName, partitionId).ConfigureAwait(true);

                foreach (var partition in partitions)
                {
                    ServicePartitionKey key;
                    switch (partition.PartitionInformation.Kind)
                    {
                    //only int64 partitions are supported at this time
                    case ServicePartitionKind.Int64Range:
                        var longKey = (Int64RangePartitionInformation)partition.PartitionInformation;
                        key = new ServicePartitionKey(longKey.LowKey);
                        break;

                    default:
                        continue;
                    }

                    var resolved = await _servicePartitionResolver.ResolveAsync(service.ServiceName, key, CancellationToken.None).ConfigureAwait(true);

                    foreach (var endpoint in resolved.Endpoints.Where(e => !string.IsNullOrWhiteSpace(e.Address)))
                    {
                        QueryPartitionEndpoints(backupEnabledServices, app, service, partition, endpoint);
                    }
                }
                token = partitions.ContinuationToken;
            } while (token != null);
        }
        // POST api/values
        public async Task PostAsync([FromBody] ProxyItem proxy)
        {
            if (proxy.TrafficPercentage > 0 && proxy.TrafficPercentage <= 100)
            {
                ServicePartitionResolver resolver  = ServicePartitionResolver.GetDefault();
                ResolvedServicePartition partition =
                    await resolver.ResolveAsync(new Uri("fabric:/ReverseProxy/ReverseProxyService"), new ServicePartitionKey(), new CancellationToken());

                var totalEndpoints = partition.Endpoints.Count;

                var targetEndpointCount = Math.Floor(totalEndpoints * (proxy.TrafficPercentage / 100.0));
                foreach (var endpoint in partition.Endpoints)
                {
                    if (targetEndpointCount > 0)
                    {
                        JObject addresses = JObject.Parse(endpoint.Address);
                        string  address   = (string)addresses["Endpoints"].First;

                        // Send request to subset of nodes to set A:B test policy
                        HttpContent content = new StringContent(JsonConvert.SerializeObject(proxy));
                        await client.PostAsync(address + "/proxy", content);

                        targetEndpointCount--;
                    }
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            ServicePartitionResolver resolver = ServicePartitionResolver.GetDefault();

            ResolvedServicePartition partition =
                await resolver.ResolveAsync(new Uri(@"fabric:/my_akka_remote_service_fabric/MyStatelessGreeter"), new ServicePartitionKey(), cancellationToken);

            var endpoint = partition.GetEndpoint();

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

            var greeter = _actorSystem.ActorSelection(primaryReplicaAddress + "/user/greeter");

            long iterations = 0;

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                iterations++;
                var name = $"MyStatelessGreetee: {iterations}, {this.Context.NodeContext.NodeName}";

                greeter.Tell(new GreetMessage(name));

                ServiceEventSource.Current.ServiceMessage(this.Context, "MyStatelessGreeter is working-{0}", ++iterations);

                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
            }
        }
        private async Task RewriteRequestUriAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var resolver = new ServicePartitionResolver(() => new FabricClient());

            //
            // Resolve service endpoint
            //
            ResolvedServiceEndpoint endpoint = null;

            if (_computePartitionKeyAsLong != null)
            {
                var partition = await resolver.ResolveAsync(_serviceName, _computePartitionKeyAsLong(request), cancellationToken);

                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.StatefulPrimary);
            }
            else if (_computePartitionKeyAsString != null)
            {
                var partition = await resolver.ResolveAsync(_serviceName, _computePartitionKeyAsString(request), cancellationToken);

                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.StatefulPrimary);
            }
            else
            {
                var partition = await resolver.ResolveAsync(_serviceName, cancellationToken);

                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.Stateless);
            }

            //
            // Parse the endpoint
            //
            dynamic address   = JsonConvert.DeserializeObject(endpoint.Address);
            string  urlString = address.Endpoints[""];
            Uri     url       = new Uri(urlString, UriKind.Absolute);

            //
            // Rewrite request URL
            //
            var builder = new UriBuilder(request.RequestUri)
            {
                Scheme = url.Scheme,
                Host   = url.Host,
                Port   = url.Port
            };

            request.RequestUri = builder.Uri;
        }
        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);
        }
Beispiel #13
0
        /// <summary>
        /// http://fabric/app/service/#/partitionkey/any|primary|secondary/endpoint-name/api-path
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            int retries    = MaxRetries;
            int retryDelay = InitialRetryDelayMs;

            ResponseData responseData = null;

            ServicePartitionResolver resolver   = ServicePartitionResolver.GetDefault();
            ResolvedServicePartition partition  = null;
            HttpServiceUriBuilder    uriBuilder = null;

            try
            {
                uriBuilder = new HttpServiceUriBuilder(request.RequestUri);
            }
            catch (Exception)
            {
                string serializedJson = JsonConvert.SerializeObject(request.RequestUri, Formatting.None, _jsonSerializerSettings);

                throw new RequestUriArgumentException($"HttpServiceUriBuilder create failed due to RequestUri={serializedJson}");
            }


            while (retries-- > 0)
            {
                cancellationToken.ThrowIfCancellationRequested();

                partition = partition != null
                    ? await resolver.ResolveAsync(partition, cancellationToken)
                    : await resolver.ResolveAsync(uriBuilder.ServiceName, uriBuilder.PartitionKey, cancellationToken);

                Uri resolvedRequestUri = GetResolvedRequestUri(partition, uriBuilder);

                responseData = await SingleSendAsync(request, resolvedRequestUri, cancellationToken);

                if (responseData.HttpResponseMessage != null)
                {
                    return(responseData.HttpResponseMessage);
                }
                await Task.Delay(retryDelay, cancellationToken);

                retryDelay += retryDelay;
            }

            throw responseData.LastException;
        }
        public async Task <IActionResult> GetServicePartitiion(string id)
        {
            try
            {
                List <string> partitionIds  = new List <string>();
                var           serviceUri    = this._context.CodePackageActivationContext.ApplicationName + "/" + id;
                var           partitionList = await this._client.QueryManager.GetPartitionListAsync(new Uri(serviceUri));

                foreach (var partition in partitionList)
                {
                    partitionIds.Add(partition.PartitionInformation.Id.ToString());

                    long partitionKey      = ((Int64RangePartitionInformation)partition.PartitionInformation).HighKey;
                    var  resolvedPartition = await servicePartitionResolver.ResolveAsync(new Uri(serviceUri), new ServicePartitionKey(partitionKey), CancellationToken.None);

                    var endpoint = resolvedPartition.GetEndpoint();


                    var message = new ServiceMessage();
                    message.CommChannel      = "Remoting";
                    message.StampOne.Visited = true;
                    message.StampOne.TimeNow = DateTime.UtcNow;

                    var storage = await _manager.GetOrAddAsync <IReliableDictionary <string, ServiceMessage> >("storage");

                    using (var tx = _manager.CreateTransaction())
                    {
                        await storage.AddAsync(tx, message.MessageId, message);

                        await tx.CommitAsync();
                    }


                    var service = ServiceProxy.Create <IServiceThree>(new Uri(serviceUri), new ServicePartitionKey(partitionKey));
                    await service.VisitByRemotingAsync(message);
                }

                return(Ok(partitionIds));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        private async Task RewriteRequestUriAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var resolver = new ServicePartitionResolver(() => new FabricClient());

            //
            // Resolve service endpoint
            //
            ResolvedServiceEndpoint endpoint = null;
            if (_computePartitionKeyAsLong != null)
            {
                var partition = await resolver.ResolveAsync(_serviceName, _computePartitionKeyAsLong(request), cancellationToken);
                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.StatefulPrimary);
            }
            else if (_computePartitionKeyAsString != null)
            {
                var partition = await resolver.ResolveAsync(_serviceName, _computePartitionKeyAsString(request), cancellationToken);
                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.StatefulPrimary);
            }
            else
            {
                var partition = await resolver.ResolveAsync(_serviceName, cancellationToken);
                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.Stateless);
            }

            //
            // Parse the endpoint
            //
            dynamic address = JsonConvert.DeserializeObject(endpoint.Address);
            string urlString = address.Endpoints[""];
            Uri url = new Uri(urlString, UriKind.Absolute);

            //
            // Rewrite request URL
            //
            var builder = new UriBuilder(request.RequestUri)
            {
                Scheme = url.Scheme,
                Host = url.Host,
                Port = url.Port
            };

            request.RequestUri = builder.Uri;
        }
        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);
        }
Beispiel #17
0
        private async Task <string> resolveCatalogServiceAddress()
        {
            Uri serviceName = new Uri("fabric:/SFServiceCatalog/CatalogService");
            ServicePartitionResolver resolve = new ServicePartitionResolver(() => new System.Fabric.FabricClient());
            var partition = await resolve.ResolveAsync(serviceName, ServicePartitionKey.Singleton, default(CancellationToken));

            string address = partition.GetEndpoint().Address.Substring(18, partition.GetEndpoint().Address.Length - 21);

            address = address.Replace("\\", "");
            return(address);
        }
Beispiel #18
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);
        }
Beispiel #19
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);
        }
Beispiel #20
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());
        }
Beispiel #21
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);
        }
        private static void ListEndpoints(ServicePartitionResolver resolver)
        {
            //var resolver = ServicePartitionResolver.GetDefault();
            var fabricClient = new FabricClient();
            var apps         = fabricClient.QueryManager.GetApplicationListAsync().Result;

            foreach (var app in apps)
            {
                Console.WriteLine($"Discovered application:'{app.ApplicationName}");

                var services = fabricClient.QueryManager.GetServiceListAsync(app.ApplicationName).Result;
                foreach (var service in services)
                {
                    Console.WriteLine($"Discovered Service:'{service.ServiceName}");

                    var partitions = fabricClient.QueryManager.GetPartitionListAsync(service.ServiceName).Result;
                    foreach (var partition in partitions)
                    {
                        Console.WriteLine($"Discovered Service Partition:'{partition.PartitionInformation.Kind} {partition.PartitionInformation.Id}");


                        ServicePartitionKey key;
                        switch (partition.PartitionInformation.Kind)
                        {
                        case ServicePartitionKind.Singleton:
                            key = ServicePartitionKey.Singleton;
                            break;

                        case ServicePartitionKind.Int64Range:
                            var longKey = (Int64RangePartitionInformation)partition.PartitionInformation;
                            key = new ServicePartitionKey(longKey.LowKey);
                            break;

                        case ServicePartitionKind.Named:
                            var namedKey = (NamedPartitionInformation)partition.PartitionInformation;
                            key = new ServicePartitionKey(namedKey.Name);
                            break;

                        default:
                            throw new ArgumentOutOfRangeException("partition.PartitionInformation.Kind");
                        }
                        var resolved = resolver.ResolveAsync(service.ServiceName, key, CancellationToken.None).Result;
                        foreach (var endpoint in resolved.Endpoints)
                        {
                            Console.WriteLine($"Discovered Service Endpoint:'{endpoint.Address}");
                        }
                    }
                }
            }
        }
        public async Task <TResult> ResolveAsync <TResult>(CancellationToken cancellationToken, Func <String, CancellationToken, Task <TResult> > func)
        {
            if (m_rsp == null)
            {
                // Get endpoints from naming service; https://msdn.microsoft.com/en-us/library/azure/dn707638.aspx
                m_rsp = await m_spr.ResolveAsync(ServiceName, PartitionKey, cancellationToken);
            }
            for (;;)
            {
                try {
                    if (m_endpoint == null)
                    {
                        m_endpoint = DeserializeEndpoints(m_rsp.GetEndpoint())[EndpointName];
                    }
                    return(await func(m_endpoint, cancellationToken));
                }
                catch (HttpRequestException ex) when((ex.InnerException as WebException)?.Status == WebExceptionStatus.ConnectFailure)
                {
                    m_rsp = await m_spr.ResolveAsync(m_rsp, cancellationToken);

                    m_endpoint = null; // Retry after getting the latest endpoints from naming service
                }
            }
        }
Beispiel #24
0
        private async Task <string> ResolveApiAddress()
        {
            //Warning: Very simplistic/optimistic implementation
            //This demo uses only 1 partition. Other stateful services might have more..
            ServicePartitionResolver resolver  = ServicePartitionResolver.GetDefault();
            ResolvedServicePartition partition =
                await resolver.ResolveAsync(
                    new Uri("fabric:/TrafficServiceFabric/TrafficApi"),
                    new ServicePartitionKey(0), CancellationToken.None);

            ResolvedServiceEndpoint endpoint = partition.GetEndpoint();

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

            return(address);
        }
Beispiel #25
0
        /// <summary>
        /// Gets the ResolvedServicePartition for a partition key value.
        /// </summary>
        /// <param name="partition">Partition value.</param>
        /// <param name="token">CancellationToken instance.</param>
        /// <returns>ResolvedServicePartition instance or null if resolution is not possible.</returns>
        private async Task <ResolvedServicePartition> GetRspAsync(long partition, CancellationToken token)
        {
            ServicePartitionResolver resolver = ServicePartitionResolver.GetDefault();

            // Get the ResolvedServicePartition for this partition.
            ResolvedServicePartition rsp = _partitionMap[partition].Item2;

            if (null == rsp)
            {
                var spk = new ServicePartitionKey(partition);
                rsp = await resolver.ResolveAsync(_serviceUri, spk, token).ConfigureAwait(false);

                _partitionMap[partition] = new Tuple <ServicePartitionKey, ResolvedServicePartition>(spk, rsp);
            }

            return(rsp);
        }
Beispiel #26
0
        public static async Task <ResolvedServicePartition> ResolvedServicePartition(HttpContext context,
                                                                                     IdentityModel identity, RouteInfo validRoute, ServicePartitionResolver resolver)
        {
            var partitionKey = identity.OrganizationPrefix;
            var resolvedKey  = PartitionResolver.Resolve(partitionKey);

            var servicePartitionKey = validRoute.IsPartitioned
                ? new ServicePartitionKey(resolvedKey)
                : ServicePartitionKey.Singleton;

            var resolved = await resolver
                           .ResolveAsync(new Uri(validRoute.ServiceUri), servicePartitionKey,
                                         context.RequestAborted)
                           .ConfigureAwait(false);

            return(resolved);
        }
Beispiel #27
0
        public async Task Invoke(HttpContext context)
        {
            var validationResponse = await _routeValidator.VerifyRequest(context).ConfigureAwait(false);

            if (!validationResponse.IsSuccess)
            {
                var statusCode = (int)validationResponse.Status;
                context.Response.StatusCode = statusCode;
                return;
            }

            var contextRequestBody = Helpers.SetContextRequestBody(context);
            var identity           = validationResponse.Identity;
            var validRoute         = validationResponse.ValidRoute;

            var resolved = await Helpers
                           .ResolvedServicePartition(context, identity, validRoute, _resolver)
                           .ConfigureAwait(false);

            var endpoint = Helpers.ExtractEndpoint(resolved, validRoute);

            var policy = Policy
                         .Handle <Exception>()
                         .OrResult <HttpResponseMessage>(message => (int)message.StatusCode >= 500)
                         .RetryAsync(5, (delegateResult, retryCount, c) =>
            {
                if (delegateResult.Result?.StatusCode != HttpStatusCode.ServiceUnavailable)
                {
                    return(Task.Delay(TimeSpan.FromSeconds(Helpers.ExponentialDelay(retryCount)),
                                      context.RequestAborted));
                }

                return(_resolver
                       .ResolveAsync(resolved, context.RequestAborted)
                       .ContinueWith(task => endpoint = Helpers.ExtractEndpoint(task.Result, validRoute)));
            });

            var response = await policy
                           .ExecuteAsync(() =>
                                         MakeServiceCallAsync(endpoint, context, contextRequestBody, identity))
                           .ConfigureAwait(false);

            await response.CopyToCurrentContext(context).ConfigureAwait(false);
        }
        static void Main(string[] args)
        {
            ServicePartitionResolver partitionResolver = new ServicePartitionResolver("localhost:19000");
            var partition = partitionResolver.ResolveAsync(new Uri("fabric:/gRPCApplication/gRPCServer"),
                                                           ServicePartitionKey.Singleton, new System.Threading.CancellationToken()).Result;
            var endpoint = partition.Endpoints.ElementAt(mRand.Next(0, partition.Endpoints.Count));

            var address = endpoint.Address.Substring(endpoint.Address.IndexOf("\"\":\"") + 4);

            address = address.Substring(0, address.IndexOf("\""));

            Channel channel = new Channel(address, ChannelCredentials.Insecure);
            var     client  = new Calculator.Calculator.CalculatorClient(channel);
            var     reply   = client.Add(new Calculator.CalculateRequest {
                A = 100, B = 200
            });

            Console.WriteLine(string.Format("Replica {0} returned: {1} ", reply.ReplicaId, reply.Result));
        }
Beispiel #29
0
        public async Task ImportJokesAsync(
            IEnumerable <JokeImportModel> importJokes,
            CancellationToken cancellationToken)
        {
            var resolver = new ServicePartitionResolver();

            var client = new HttpClient();

            var serializer = JsonSerializer.Create();

            foreach (var byLanguage in importJokes.GroupBy(importJoke => importJoke.Language))
            {
                foreach (var byCategory in byLanguage.GroupBy(importJoke => importJoke.Category))
                {
                    var tuple = await this.ResolveServiceAsync(byLanguage.Key, byCategory.Key);

                    var partition = await resolver.ResolveAsync(
                        tuple.serviceName,
                        new ServicePartitionKey(tuple.partitionName),
                        cancellationToken);

                    // Find endpoint address information of primary replica
                    var address = partition.Endpoints.Single(e => e.Role == ServiceEndpointRole.StatefulPrimary)?.Address;

                    var value = JObject.Parse(address)["Endpoints"]?["ServiceEndpoint"]?.Value <string>();

                    var builder = new StringBuilder();

                    using (var writer = new StringWriter(builder))
                    {
                        serializer.Serialize(writer, byCategory);
                    }

                    var response = await client.PostAsync(
                        $"{value}/api/jokes/import",
                        new StringContent(builder.ToString(), Encoding.UTF8, "application/json"),
                        cancellationToken);

                    response.EnsureSuccessStatusCode();
                }
            }
        }
Beispiel #30
0
        static void Main(string[] args)
        {
            ServicePartitionResolver resolver  = ServicePartitionResolver.GetDefault();
            var cancellationTokenS             = new CancellationTokenSource();
            ResolvedServicePartition partition =
                resolver.ResolveAsync(
                    new Uri("fabric:/SFTest/ConfigurationService"),
                    new ServicePartitionKey(0),
                    cancellationTokenS.Token).GetAwaiter().GetResult();
            var     endpoint  = partition.GetEndpoint();
            dynamic endpoints = JsonConvert.DeserializeObject(endpoint.Address);
            var     client    = new HttpClient();
            var     response  = client.GetAsync(endpoints.Endpoints["ReadonlyEndpoint"].Value + "/api/config/1c05d13fbf3448309816d614883e8df2").GetAwaiter().GetResult();
            var     config    = JsonConvert.DeserializeObject <CustomConfig>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

            if (config != null)
            {
                Console.WriteLine("ID:{0}, AppType:{1}", config.Id, config.ApproximationType);
            }

            Console.ReadKey();
        }
Beispiel #31
0
        public async Task <string> GetAPIResult()
        {
            String responseString = string.Empty;

            ResolvedServicePartition mypartition = await resolver.ResolveAsync(serviceUri, new ServicePartitionKey(), new CancellationToken());

            ResolvedServiceEndpoint endpoint = mypartition.GetEndpoint();

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

            HttpClient          client   = new HttpClient();
            HttpRequestMessage  request  = new HttpRequestMessage(HttpMethod.Get, address + "/api/values");
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                responseString = await response.Content.ReadAsStringAsync();
            }

            return(responseString);
        }