Exemplo n.º 1
0
        public MockPartitionEnumerationManager(params Partition[] partitions)
        {
            var servicePartitionListType = typeof(ServicePartitionList);
            var servicePartitionList     = ReflectionUtils.CreateInstanceOfInternal(servicePartitionListType, new List <Partition>(partitions)) as ServicePartitionList;

            _servicePartitionList = servicePartitionList;
        }
Exemplo n.º 2
0
        // Maps the paritions of the applications from primary cluster and secondary cluster
        public async Task MapPartitionsOfApplication(Uri applicationName, ClusterDetails primaryCluster, ClusterDetails secondaryCluster, String reliableDictionary)
        {
            FabricClient primaryFabricClient   = new FabricClient(primaryCluster.address + ':' + primaryCluster.clientConnectionEndpoint);
            FabricClient secondaryFabricClient = new FabricClient(secondaryCluster.address + ':' + secondaryCluster.clientConnectionEndpoint);

            IReliableDictionary <Guid, PartitionWrapper> myDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <Guid, PartitionWrapper> >(reliableDictionary);

            ServiceList services = await primaryFabricClient.QueryManager.GetServiceListAsync(applicationName);

            foreach (Service service in services)
            {
                ServicePartitionList primaryPartitions = await primaryFabricClient.QueryManager.GetPartitionListAsync(service.ServiceName);

                ServicePartitionList secondaryPartitions = await secondaryFabricClient.QueryManager.GetPartitionListAsync(service.ServiceName);
                await MapPartitions(applicationName, service.ServiceName, primaryCluster, primaryPartitions, secondaryCluster, secondaryPartitions, reliableDictionary);

                using (var tx = this.StateManager.CreateTransaction())
                {
                    var result = await myDictionary.GetCountAsync(tx);

                    ServiceEventSource.Current.ServiceMessage(this.Context, "The number of items in dictionary are : {0}", result);
                    await tx.CommitAsync();
                }
            }
        }
        private async Task InitializeAsync()
        {
            bool initPartitionList = false;

            if (InitializePartitionList() || RefreshPartitionList())
            {
                lock (_lock)
                {
                    if (InitializePartitionList())
                    {
                        _context.WriteEvent($"CacheController::InitializeAsync: Initialize");
                        _fabricClient     = new FabricClient();
                        initPartitionList = true;
                    }

                    if (RefreshPartitionList())
                    {
                        _context.WriteEvent($"CacheController::InitializeAsync: Refresh {_lastInitializeTime}");
                        initPartitionList = true;
                    }
                }
            }

            if (initPartitionList && RefreshPartitionList())
            {
                // Note: there is a small chance that this gets executed multiple times when _servicePartitionList == null
                _context.WriteEvent($"CacheController::InitializeAsync: GetPartitionListAsync");
                _servicePartitionList = await _fabricClient.QueryManager.GetPartitionListAsync(_context.StatefulServiceContext.ServiceUri);
            }

            _lastInitializeTime = DateTime.UtcNow;
        }
Exemplo n.º 4
0
        public async Task <IActionResult> GetAsync()
        {
            var result = new List <SmilrEvent>();

            // the stateful service service may have more than one partition.
            // this sample code uses a very basic loop to aggregate the results from each partition to illustrate aggregation.
            // note that this can be optimized in multiple ways for production code.
            ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(new Uri(serviceUri));

            foreach (Partition partition in partitions)
            {
                var proxyUrl = GetEventStoreUri(partition);

                HttpResponseMessage response = await this.httpClient.GetAsync(proxyUrl);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    // if one partition returns a failure, you can either fail the entire request or skip that partition.
                    return(this.StatusCode((int)response.StatusCode));
                }

                //Convert this into the format expected from Node
                var list = JsonConvert.DeserializeObject <List <SmilrEvent> >(await response.Content.ReadAsStringAsync());

                if (list != null && list.Any())
                {
                    result.AddRange(list);
                }
            }

            return(this.Json(result));
        }
        /// <summary>
        /// get partition key for the given Service Fabric service uri.
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="serviceUri"></param>
        /// <returns></returns>
        private ServicePartitionKey GetPartitionKey(int customerId, Uri serviceUri)
        {
            ServicePartitionList partitionList = fabricClient.QueryManager.GetPartitionListAsync(serviceUri).Result;

            // simple approach is used here -- just get the first available partition
            // for more information on partitioning, refer to the Microsoft documentation:
            // https://azure.microsoft.com/en-us/documentation/articles/service-fabric-concepts-partitioning/
            var partitionInformation = partitionList.First().PartitionInformation;

            if (partitionInformation.Kind == ServicePartitionKind.Int64Range)
            {
                var intRangePartitionInfo = (Int64RangePartitionInformation)partitionInformation;
                return(new ServicePartitionKey(intRangePartitionInfo.LowKey));
            }
            // a singleton has only one partition, use the default constructor
            else if (partitionInformation.Kind == ServicePartitionKind.Singleton)
            {
                return(new ServicePartitionKey());
            }
            else if (partitionInformation.Kind == ServicePartitionKind.Named)
            {
                var stringNamedPartitionInfo = (NamedPartitionInformation)partitionInformation;
                return(new ServicePartitionKey(stringNamedPartitionInfo.Name));
            }
            else
            {
                throw new Exception(string.Format("Unexpected partition type: {0}", partitionInformation.Kind));
            }
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Get()
        {
            Uri serviceName = GetBackEndServiceName(serviceContext);

            ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(serviceName);

            List <Team> result = new List <Team>();

            foreach (Partition partition in partitions)
            {
                long   partitionKey = ((Int64RangePartitionInformation)partition.PartitionInformation).LowKey;
                string proxyUrl     = GetProxyUrl(serviceContext, partitionKey);

                using (HttpResponseMessage response = await httpClient.GetAsync(proxyUrl))
                {
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        continue;
                    }

                    result.AddRange(JsonConvert.DeserializeObject <List <Team> >(await response.Content.ReadAsStringAsync()));
                }
            }

            return(Json(result));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Get ID for all partitions of a service. If the partition do not fit in a page, one
        /// page of results is returned as well as a continuation token which can be used to get the next page. Let PartitionFilter to be null because we are getting all partition.
        /// </summary>
        public async Task <IEnumerable <Guid> > GetPartitionListAsync(Uri serviceName, TimeSpan timeout, CancellationToken cancellationToken)
        {
            var partitionList = new List <Guid>();
            ServicePartitionList previousResult = null;

            // Set up the counter that record the time lapse.
            var stopWatch = ValueStopwatch.StartNew();

            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                var remaining = timeout - stopWatch.Elapsed;
                if (remaining.Ticks < 0)
                {
                    // If the passing time is longer than the timeout duration.
                    throw new TimeoutException($"Unable to enumerate all partition pages in the allotted time budget of {timeout.TotalSeconds} seconds");
                }

                previousResult = await ExceptionsHelper.TranslateCancellations(
                    () => _queryClient.GetPartitionListAsync(
                        serviceName: serviceName,
                        partitionIdFilter: null,
                        continuationToken: previousResult?.ContinuationToken,
                        timeout: remaining,
                        cancellationToken: cancellationToken),
                    cancellationToken);

                foreach (var partition in previousResult)
                {
                    partitionList.Add(partition.PartitionInformation.Id);
                }
            }while (!string.IsNullOrEmpty(previousResult?.ContinuationToken));

            return(partitionList);
        }
        public async Task <IActionResult> Get(int id)
        {
            ServicePartitionList partitionList = await _fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/SFPerfMonitoring/StatefulBackEnd"));

            foreach (Partition partition in partitionList)
            {
                long partitionKey = ((Int64RangePartitionInformation)partition.PartitionInformation).LowKey;

                string proxyUrl = $"http://localhost:{19081}/SFPerfMonitoring/StatefulBackEnd/api/users/{id}?PartitionKind={partition.PartitionInformation.Kind}&PartitionKey={partitionKey}";

                HttpResponseMessage response = await _httpClient.GetAsync(proxyUrl);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    // if one partition returns a failure, you can either fail the entire request or skip that partition.
                    return(this.StatusCode((int)response.StatusCode));
                }

                string stringResult = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <Models.User>(stringResult);

                return(this.Json(result));
            }

            return(null);
        }
            private async Task PopulateServiceEntityAsync(
                ServiceEntity serviceEntity,
                CancellationToken cancellationToken)
            {
                // Get all partitions in this service
                ServicePartitionList partitionListResult = await FabricClientRetryHelper.ExecuteFabricActionWithRetryAsync(
                    () => this.testContext.FabricClient.QueryManager.GetPartitionListAsync(
                        serviceEntity.Service.ServiceName,
                        null,
                        this.requestTimeOut,
                        cancellationToken),
                    FabricClientRetryErrors.GetPartitionListFabricErrors.Value,
                    this.timer.GetRemainingTime(),
                    cancellationToken).ConfigureAwait(false);

                if (partitionListResult != null)
                {
                    GetClusterStateSnapshotAction.PartitionCount += partitionListResult.Count;

                    foreach (var partitionResultItem in partitionListResult)
                    {
                        var partitionEntity = serviceEntity.AddPartition(partitionResultItem);
                        await this.PopulatePartitionEntityAsync(partitionEntity, cancellationToken).ConfigureAwait(false);
                    }
                }
            }
        public async Task <HashSet <String> > GetConfiguredApplications(String primarycs, String secondarycs)
        {
            FabricClient         fabricClient  = new FabricClient();
            ServicePartitionList partitionList = fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/SFAppDRTool/RestoreService")).Result;

            List <String> configuredApplicationNames = new List <String>();

            foreach (Partition partition in partitionList)
            {
                List <String>   configAppNames       = new List <String>();
                var             int64PartitionInfo   = partition.PartitionInformation as Int64RangePartitionInformation;
                long            lowKey               = (long)int64PartitionInfo?.LowKey;
                IRestoreService restoreServiceClient = ServiceProxy.Create <IRestoreService>(new Uri("fabric:/SFAppDRTool/RestoreService"), new ServicePartitionKey(lowKey));
                try
                {
                    configAppNames = await restoreServiceClient.GetConfiguredApplicationNames(primarycs, secondarycs);

                    configuredApplicationNames.AddRange(configAppNames);
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.Message("Web Service: Exception getting all configured application names {0}", ex);
                    throw;
                }
            }

            return(new HashSet <String>(configuredApplicationNames));
        }
Exemplo n.º 11
0
        public async Task WaitForStatefulService(Uri serviceInstanceUri)
        {
            StatefulServiceDescription description =
                await this.Client.ServiceManager.GetServiceDescriptionAsync(serviceInstanceUri) as StatefulServiceDescription;

            int targetTotalReplicas = description.TargetReplicaSetSize;

            if (description.PartitionSchemeDescription is UniformInt64RangePartitionSchemeDescription)
            {
                targetTotalReplicas *= ((UniformInt64RangePartitionSchemeDescription)description.PartitionSchemeDescription).PartitionCount;
            }

            ServicePartitionList partitions = await this.Client.QueryManager.GetPartitionListAsync(serviceInstanceUri);

            int replicaTotal = 0;

            while (replicaTotal < targetTotalReplicas)
            {
                await Task.Delay(this.interval);

                //ServiceEventSource.Current.ServiceMessage(this, "CountyService waiting for National Service to come up.");

                replicaTotal = 0;
                foreach (Partition partition in partitions)
                {
                    ServiceReplicaList replicaList = await this.Client.QueryManager.GetReplicaListAsync(partition.PartitionInformation.Id);

                    replicaTotal += replicaList.Count(x => x.ReplicaStatus == System.Fabric.Query.ServiceReplicaStatus.Ready);
                }
            }
        }
        public async Task <IEnumerable <Tuple <ClusterDetails, ClusterDetails> > > GetClusterCombinations()
        {
            FabricClient         fabricClient  = new FabricClient();
            ServicePartitionList partitionList = fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/SFAppDRTool/RestoreService")).Result;

            List <Tuple <ClusterDetails, ClusterDetails> > allClusterCombinations = new List <Tuple <ClusterDetails, ClusterDetails> >();

            foreach (Partition partition in partitionList)
            {
                List <Tuple <ClusterDetails, ClusterDetails> > localClusterCombinations = new List <Tuple <ClusterDetails, ClusterDetails> >();
                var             int64PartitionInfo   = partition.PartitionInformation as Int64RangePartitionInformation;
                long            lowKey               = (long)int64PartitionInfo?.LowKey;
                IRestoreService restoreServiceClient = ServiceProxy.Create <IRestoreService>(new Uri("fabric:/SFAppDRTool/RestoreService"), new ServicePartitionKey(lowKey));
                try
                {
                    localClusterCombinations = await restoreServiceClient.GetClusterCombinations();

                    allClusterCombinations.AddRange(localClusterCombinations);
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.Message("Web Service: Exception getting cluster combinations {0}", ex);
                    throw;
                }
            }

            return(allClusterCombinations);
        }
        public async Task <IEnumerable <PartitionWrapper> > GetPartitionStatus()
        {
            FabricClient         fabricClient  = new FabricClient();
            ServicePartitionList partitionList = fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/SFAppDRTool/RestoreService")).Result;

            List <PartitionStatusModel> partitionStatusList = new List <PartitionStatusModel>();
            List <PartitionWrapper>     mappedPartitions    = new List <PartitionWrapper>();

            foreach (Partition partition in partitionList)
            {
                List <PartitionWrapper> servicePartitions = new List <PartitionWrapper>();
                var             int64PartitionInfo        = partition.PartitionInformation as Int64RangePartitionInformation;
                long            lowKey = (long)int64PartitionInfo?.LowKey;
                IRestoreService restoreServiceClient = ServiceProxy.Create <IRestoreService>(new Uri("fabric:/SFAppDRTool/RestoreService"), new ServicePartitionKey(lowKey));
                try
                {
                    servicePartitions = await restoreServiceClient.GetStatus();

                    mappedPartitions.AddRange(servicePartitions);
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.Message("Web Service: Exception getting the status {0}", ex);
                    throw;
                }
            }

            //if (mappedPartitions.Count == 0) return null;
            return(mappedPartitions);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Get()
        {
            //return this.Json(new string[] { "value1", "value2" });


            Uri serviceName = eCommerceGatewaySvc.GetVotingDataServiceName(this.serviceContext);
            //Uri proxyAddress = this.GetProxyAddress(serviceName);

            ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(serviceName);

            List <KeyValuePair <string, int> > result = new List <KeyValuePair <string, int> >();

            foreach (Partition partition in partitions)
            {
                string proxyUrl = "http://localhost:19081/eCommerce/eCommerceOrderAPI/API/Values?PartitionKey=1&PartitionKind=Int64Range";
                //$"{proxyAddress}/api/values?PartitionKey={((Int64RangePartitionInformation)partition.PartitionInformation).LowKey}&PartitionKind=Int64Range";

                using (HttpResponseMessage response = await this.httpClient.GetAsync(proxyUrl))
                {
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        continue;
                    }

                    result.AddRange(JsonConvert.DeserializeObject <List <KeyValuePair <string, int> > >(await response.Content.ReadAsStringAsync()));
                }
            }

            return(this.Json(result));
        }
Exemplo n.º 15
0
        public async Task <IActionResult> GetQueueLengthAsync()
        {
            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(TenantDataServiceName);
            Uri serviceUri = uriBuilder.Build();

            // service may be partitioned.
            // this will aggregate the queue lengths from each partition
            ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

            HttpClient httpClient = new HttpClient(new HttpServiceClientHandler());

            long count = 0;

            foreach (Partition partition in partitions)
            {
                Uri getUrl = new HttpServiceUriBuilder()
                             .SetServiceName(serviceUri)
                             .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                             .SetServicePathAndQuery($"/api/devices/queue/length")
                             .Build();

                HttpResponseMessage response = await httpClient.GetAsync(getUrl, this.cancellationSource.Token);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    return(this.StatusCode((int)response.StatusCode));
                }

                string result = await response.Content.ReadAsStringAsync();

                count += Int64.Parse(result);
            }

            return(this.Ok(count));
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            FabricClient         fabricClient  = new FabricClient("localhost:19000");
            ServicePartitionList partitionList = fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/Codit.Core.Application/DeviceActorService")).Result;

            ContinuationToken continuationToken  = null;
            var cancellationTokenSource          = new CancellationTokenSource();
            List <ActorInformation> activeActors = new List <ActorInformation>();

            foreach (var partition in partitionList)
            {
                var           key = partition.PartitionInformation as Int64RangePartitionInformation;
                IActorService actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/Codit.Core.Application/DeviceActorService"), key.LowKey);

                do
                {
                    PagedResult <ActorInformation> page = actorServiceProxy.GetActorsAsync(continuationToken, cancellationTokenSource.Token).Result;
                    activeActors.AddRange(page.Items.Where(x => x.IsActive));
                    continuationToken = page.ContinuationToken;
                }while (continuationToken != null);
            }

            foreach (var actor in activeActors)
            {
                Console.WriteLine($"Active Actor: {actor.ActorId.ToString()}");
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
        /// <summary>
        /// Resolves the <see cref="ServicePartitionKey"/> to send the message to, based on message type name.
        /// </summary>
        /// <param name="messageTypeName">Full type name of message object.</param>
        /// <param name="brokerServiceName"></param>
        /// <returns></returns>
        private async Task <ServicePartitionKey> GetPartitionForMessageAsync(string messageTypeName, Uri brokerServiceName)
        {
            if (_cachedPartitions == null)
            {
                _cachedPartitions = await _fabricClient.QueryManager.GetPartitionListAsync(brokerServiceName ?? await LocateAsync());
            }

            int hashCode;

            unchecked
            {
                hashCode = (int)_hashingHelper.HashString(messageTypeName);
            }
            int index     = Math.Abs(hashCode % _cachedPartitions.Count);
            var partition = _cachedPartitions[index];

            if (partition.PartitionInformation.Kind != ServicePartitionKind.Int64Range)
            {
                throw new InvalidOperationException("Sorry, only Int64 Range Partitions are supported.");
            }

            var info = (Int64RangePartitionInformation)partition.PartitionInformation;
            var resolvedPartition = new ServicePartitionKey(info.LowKey);

            return(resolvedPartition);
        }
Exemplo n.º 18
0
        public async Task <ServicePartitionList> GetPartitionsAsync(CancellationToken ct)
        {
            ReleaseAssert.AssertIfNull(FabricClientRetryErrors.GetPartitionListFabricErrors.Value, "partition list error code");

            var retryableErrors = new FabricClientRetryErrors();

            retryableErrors.RetryableFabricErrorCodes.AddRangeNullSafe(FabricClientRetryErrors.GetPartitionListFabricErrors.Value.RetryableFabricErrorCodes);
            retryableErrors.RetryableExceptions.AddRangeNullSafe(FabricClientRetryErrors.GetPartitionListFabricErrors.Value.RetryableExceptions);

            retryableErrors.RetryableFabricErrorCodes.Add(FabricErrorCode.PartitionNotFound);

            ServicePartitionList servicePartitionList = new ServicePartitionList();
            string continuationToken = null;

            do
            {
                ServicePartitionList queryResult = await FabricClientRetryHelper.ExecuteFabricActionWithRetryAsync(
                    () =>
                    this.TestContext.FabricClient.QueryManager.GetPartitionListAsync(
                        this.serviceName,
                        null,
                        continuationToken,
                        this.requestTimeout,
                        ct),
                    retryableErrors,
                    this.operationTimeout,
                    ct).ConfigureAwait(false);

                servicePartitionList.AddRangeNullSafe(queryResult);
                continuationToken = queryResult.ContinuationToken;
            } while (!string.IsNullOrEmpty(continuationToken));

            return(servicePartitionList);
        }
        public async Task <ActionResult <IEnumerable <Blog> > > Get()
        {
            try
            {
                var                  results    = new List <Blog>();
                FabricClient         client     = new FabricClient();
                ServicePartitionList partitions = await client.QueryManager.GetPartitionListAsync(new Uri(rssCatalogUrl));

                foreach (var partition in partitions)
                {
                    long minKey  = (partition.PartitionInformation as Int64RangePartitionInformation).LowKey;
                    var  service = ServiceProxy.Create <IRssCatalog>(new Uri(rssCatalogUrl), new ServicePartitionKey(minKey));

                    IEnumerable <Blog> subResult = await service.GetAllBlogs();

                    if (subResult != null)
                    {
                        results.AddRange(subResult);
                    }
                }

                return(StatusCode(StatusCodes.Status200OK, results));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.ToString()));
            }
        }
Exemplo n.º 20
0
        public async Task <IEnumerable <Vehicle> > GetAllVehicles()
        {
            ServiceEventSource.Current.Message("Called GetAllVehicles in STATELESS GATEWAY service to return collection of ALL the Vehicles");

            List <Vehicle> aggregatedVehiclesList = new List <Vehicle>();

            ServicePartitionList partitions = await _fabricClient.QueryManager.GetPartitionListAsync(_vehiclesStatefulServiceUriInstance);

            foreach (Partition p in partitions)
            {
                long minKey = (p.PartitionInformation as Int64RangePartitionInformation).LowKey;
                IVehiclesStatefulService vehiclesServiceClient =
                    ServiceProxy.Create <IVehiclesStatefulService>(_vehiclesStatefulServiceUriInstance, new ServicePartitionKey(minKey));

                //Async call aggregating the results
                IList <Vehicle> currentPartitionResult;

                //(CDLTLL) This method should be substituted by a paginated method (20 vehicles per page or so).
                //No method should return ALL the vehicles as potentially there could be thousands or millions...
                currentPartitionResult = await vehiclesServiceClient.GetAllVehiclesAsync();

                if (currentPartitionResult.Count > 0)
                {
                    //Aggregate List from current partition to our global result
                    aggregatedVehiclesList.AddRange(currentPartitionResult);
                }
            }
            //Return the aggregated list from all the partitions
            return(aggregatedVehiclesList);
        }
        public async Task <IActionResult> Get()
        {
            logger.Debug("Requesting to load vote data");

            Uri serviceName  = VotingWeb.GetVotingDataServiceName(this.serviceContext);
            Uri proxyAddress = this.GetProxyAddress(serviceName);

            ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(serviceName);

            List <KeyValuePair <string, int> > result = new List <KeyValuePair <string, int> >();

            foreach (Partition partition in partitions)
            {
                string proxyUrl =
                    $"{proxyAddress}/api/VoteData?PartitionKey={((Int64RangePartitionInformation)partition.PartitionInformation).LowKey}&PartitionKind=Int64Range";

                using (HttpResponseMessage response = await this.httpClient.GetAsync(proxyUrl))
                {
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        continue;
                    }

                    result.AddRange(JsonConvert.DeserializeObject <List <KeyValuePair <string, int> > >(await response.Content.ReadAsStringAsync()));
                }
            }
            return(this.Json(result));
        }
Exemplo n.º 22
0
        public async Task <IEnumerable <Vehicle> > GetTenantVehicles([FromUri] string tenantId)
        {
            ServiceEventSource.Current.Message("Called GetTenantVehicles in STATELESS GATEWAY service to return collection of Vehicles for Tenant {0}", tenantId);

            List <Vehicle> aggregatedVehiclesList = new List <Vehicle>();

            ServicePartitionList partitions = await _fabricClient.QueryManager.GetPartitionListAsync(_vehiclesStatefulServiceUriInstance);

            foreach (Partition p in partitions)
            {
                long minKey = (p.PartitionInformation as Int64RangePartitionInformation).LowKey;
                IVehiclesStatefulService vehiclesServiceClient =
                    ServiceProxy.Create <IVehiclesStatefulService>(_vehiclesStatefulServiceUriInstance, new ServicePartitionKey(minKey));

                //Async call aggregating the results
                IList <Vehicle> currentPartitionResult;

                currentPartitionResult = await vehiclesServiceClient.GetTenantVehiclesAsync(tenantId);

                if (currentPartitionResult.Count > 0)
                {
                    //Aggregate List from current partition to our global result
                    aggregatedVehiclesList.AddRange(currentPartitionResult);
                }
            }
            //Return the aggregated list from all the partitions
            return(aggregatedVehiclesList);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Resolves the <see cref="ServicePartitionKey"/> to send the message to, based on message type.
        /// </summary>
        /// <param name="message">The message to publish</param>
        /// <param name="brokerServiceName"></param>
        /// <returns></returns>
        public async Task <ServicePartitionKey> GetPartitionForMessageAsync(object message, Uri brokerServiceName)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (brokerServiceName == null)
            {
                throw new ArgumentNullException(nameof(brokerServiceName));
            }

            string messageTypeName = (message.GetType().FullName);

            if (_cachedPartitions == null)
            {
                var fabricClient = new FabricClient();
                _cachedPartitions = await fabricClient.QueryManager.GetPartitionListAsync(brokerServiceName);
            }
            int index     = Math.Abs(messageTypeName.GetHashCode() % _cachedPartitions.Count);
            var partition = _cachedPartitions[index];

            if (partition.PartitionInformation.Kind != ServicePartitionKind.Int64Range)
            {
                throw new InvalidOperationException("Sorry, only Int64 Range Partitions are supported.");
            }

            var info = (Int64RangePartitionInformation)partition.PartitionInformation;
            var resolvedPartition = new ServicePartitionKey(info.LowKey);

            return(resolvedPartition);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Returns the list of employees from all the partitions. In our sample we have only 1 partition
        /// Also, we are making use of proxy to determine the right partition to connect to.
        /// Please refer this link for more details. https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-reverseproxy
        /// </summary>
        /// <returns></returns>
        public async Task <List <Employee> > GetEmployees()
        {
            Uri serviceName = EmployeeWeb.GetEmployeeDataServiceName(_context);

            Uri proxyAddress = this.GetProxyAddress(serviceName);

            ServicePartitionList partitions = await _fabricClient.QueryManager.GetPartitionListAsync(serviceName);

            List <Employee> employees = new List <Employee>();

            foreach (Partition partition in partitions)
            {
                string proxyUrl =
                    $"{proxyAddress}/api/Employee?PartitionKey={((Int64RangePartitionInformation)partition.PartitionInformation).LowKey}&PartitionKind=Int64Range";

                using (HttpResponseMessage response = await _httpClient.GetAsync(proxyUrl))
                {
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        continue;
                    }

                    employees.AddRange(JsonConvert.DeserializeObject <List <Employee> >(await response.Content.ReadAsStringAsync()));
                }
            }

            return(employees);
        }
Exemplo n.º 25
0
        public async Task <IActionResult> GetAsync()
        {
            string serviceUri = this.serviceContext.CodePackageActivationContext.ApplicationName + "/" + this.configSettings.ActorBackendServiceName;

            ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(new Uri(serviceUri));

            long count = 0;

            foreach (Partition partition in partitions)
            {
                long          partitionKey      = ((Int64RangePartitionInformation)partition.PartitionInformation).LowKey;
                IActorService actorServiceProxy = ActorServiceProxy.Create(new Uri(serviceUri), partitionKey);

                ContinuationToken continuationToken = null;

                do
                {
                    PagedResult <ActorInformation> page = await actorServiceProxy.GetActorsAsync(continuationToken, CancellationToken.None);

                    count += page.Items.Where(x => x.IsActive).LongCount();

                    continuationToken = page.ContinuationToken;
                }while (continuationToken != null);
            }

            return(this.Json(new { Count = count, Date = DateTime.Now }));
        }
Exemplo n.º 26
0
        public async Task <IEnumerable <string> > Get()
        {
            ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(new ServiceUriBuilder("WorkService").Build());

            List <string> result = new List <string>();

            foreach (Partition partition in partitions)
            {
                HttpClient client = new HttpClient(new HttpServiceClientHandler());

                Int64RangePartitionInformation partitionInfo = (Int64RangePartitionInformation)partition.PartitionInformation;

                Uri serviceUri = new HttpServiceUriBuilder()
                                 .SetServiceName(new ServiceUriBuilder("WorkService").Build())
                                 .SetPartitionKey(partitionInfo.LowKey)
                                 .SetServicePathAndQuery($"api/work/")
                                 .Build();

                HttpResponseMessage response = await client.GetAsync(serviceUri);

                string responseContent = await response.Content.ReadAsStringAsync();

                if (responseContent != null)
                {
                    JArray responseJson = JArray.Parse(responseContent);
                    result.AddRange(responseJson.Select(x => x.Value <string>()));
                }
            }

            return(result);
        }
        private async Task <Int64RangePartitionInformation[]> GetServicePartitionsListAsync()
        {
            if (this.servicePartitionsTaskCompletionSource == null)
            {
                bool isNewTaskCompletionSourceCreated = false;
                lock (tcsLockObject)
                {
                    if (this.servicePartitionsTaskCompletionSource == null)
                    {
                        this.servicePartitionsTaskCompletionSource = new TaskCompletionSource <Int64RangePartitionInformation[]>();
                        isNewTaskCompletionSourceCreated           = true;
                    }
                }

                if (isNewTaskCompletionSourceCreated)
                {
                    using (var fabricClient = new FabricClient())
                    {
                        ServicePartitionList partitionList = await fabricClient.QueryManager.GetPartitionListAsync(this.serviceUri);

                        Int64RangePartitionInformation[] orderedPartitions = partitionList.Select(x => x.PartitionInformation)
                                                                             .OfType <Int64RangePartitionInformation>()
                                                                             .OrderBy(x => x.LowKey).ToArray();
                        if (partitionList.Count != orderedPartitions.Length)
                        {
                            throw new NotSupportedException("FabricPartitionEndpointResolver doesn't support non Int64RangePartitionInformation partitions");
                        }

                        this.servicePartitionsTaskCompletionSource.SetResult(orderedPartitions);
                    }
                }
            }

            return(this.servicePartitionsTaskCompletionSource.Task.Result);
        }
Exemplo n.º 28
0
        public async Task <IActionResult> GetAsync()
        {
            string serviceUri = this.serviceContext.CodePackageActivationContext.ApplicationName + "/" + this.configSettings.ActorBackendServiceName;

            ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(new Uri(serviceUri));

            long count = 0;

            foreach (Partition partition in partitions)
            {
                long          partitionKey      = ((Int64RangePartitionInformation)partition.PartitionInformation).LowKey;
                IActorService actorServiceProxy = ActorServiceProxy.Create(new Uri(serviceUri), partitionKey);

                // https://docs.microsoft.com/it-it/azure/service-fabric/service-fabric-reliable-actors-enumerate
                // Gli Actors sono ranged partitioned stateful service, quindi l'enumeration è fatta per partizione.
                // Ogni partizione contiene più attori, e il risultato è un loop su un elenco di "pagine".
                ContinuationToken continuationToken = null;

                do
                {
                    PagedResult <ActorInformation> page = await actorServiceProxy.GetActorsAsync(continuationToken, CancellationToken.None);

                    count += page.Items.Where(x => x.IsActive).LongCount();

                    continuationToken = page.ContinuationToken;
                }while (continuationToken != null);
            }

            return(this.Json(new CountViewModel()
            {
                Count = count
            }));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Gets the partitions information.
        /// </summary>
        /// <param name="serviceUri">The service URI.</param>
        /// <returns></returns>
        private async Task GetPartitionsInfo(Uri serviceUri)
        {
            this.partitionList = await fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

            this.partitionInfoList  = this.partitionList.Select(p => p.PartitionInformation as Int64RangePartitionInformation).ToList();
            this.numberOfPartitions = partitionList.Count;
        }
Exemplo n.º 30
0
        public async Task <string> Disconfigure(string applicationName)
        {
            bool                 successfullyRemoved = true;
            FabricClient         fabricClient        = new FabricClient();
            ServicePartitionList partitionList       = fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/SFAppDRTool/RestoreService")).Result;

            foreach (Partition partition in partitionList)
            {
                var             int64PartitionInfo   = partition.PartitionInformation as Int64RangePartitionInformation;
                long            lowKey               = (long)int64PartitionInfo?.LowKey;
                IRestoreService restoreServiceClient = ServiceProxy.Create <IRestoreService>(new Uri("fabric:/SFAppDRTool/RestoreService"), new ServicePartitionKey(lowKey));
                try
                {
                    string applicationRemoved = await restoreServiceClient.Disconfigure("fabric:/" + applicationName);

                    if (applicationRemoved == null)
                    {
                        successfullyRemoved = false;
                    }
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.Message("Web Service: Exception Disconfiguring {0}", ex);
                    throw;
                }
            }
            if (successfullyRemoved)
            {
                return(applicationName);
            }
            return(null);
        }