private async Task <long> GetCountAsync(string serviceName)
        {
            string serviceUri = _serviceContext.CodePackageActivationContext.ApplicationName + "/" + serviceName;

            ServicePartitionList partitions = await _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(count);
        }
        public async Task TakeFullBackupAsync(string nameOfBackupset)
        {
            using (var client = new FabricClient())
            {
                var serviceUrl = new TableActorProxy().ServiceUrl;
                var partitions = await client.QueryManager.GetPartitionListAsync(serviceUrl);

                foreach (var partition in partitions)
                {
                    if (partition.PartitionInformation.Kind != ServicePartitionKind.Int64Range)
                    {
                        throw new Exception("Unexpected Partition Kind");
                    }

                    if (!(partition.PartitionInformation is Int64RangePartitionInformation actorpartition))
                    {
                        throw new Exception("Unexpected partition type");
                    }


                    var actorServiceProxy = ActorServiceProxy.Create <ITableActorService>(serviceUrl, actorpartition.LowKey);
                    await actorServiceProxy.BackupActorsAsync(nameOfBackupset);
                }
            }
        }
        //RETURN VALUE??
        /// <summary>
        /// Deletes a game session on the server (SQL register)
        /// </summary>
        /// <param name="i_gameId">Game session ID</param>
        public async Task DeleteGameAsync(string i_gameId, string i_uri)
        {
            try
            {
                IActorService actor = ActorServiceProxy.Create(new Uri(i_uri), new ActorId(i_gameId));
                await actor.DeleteActorAsync(new ActorId(i_gameId), new CancellationToken());

                //Connects to the SQL Server and close when exiting
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    //Opens SQL connection
                    connection.Open();
                    //Creates query string
                    string query = "DELETE FROM Games WHERE Id ='" + i_gameId + "'";
                    //Creates SQL Command using query and connection
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        //Executes command
                        command.ExecuteNonQuery();
                    }
                };
            }
            catch (Exception e)
            {
                Console.Write(e.ToString());
            }
        }
Example #4
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();
        }
Example #5
0
        public void TestRemotingActors_NoSerializationError()
        {
            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 <IMyService>(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)
            {
                Assert.NotNull(actor.ActorId.ToString());
            }
        }
Example #6
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
            }));
        }
 public async Task DeleteActorByID(
     [FromQuery] int id)
 {
     var actorid           = new ActorId(id);
     var actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/ServiceFabricActor/FabricActorServiceActorService"), actorid);
     await actorServiceProxy.DeleteActorAsync(actorid, new CancellationToken());
 }
        // DELETE api/values/5
        public Task Delete(int id)
        {
            var actorId = new ActorId(id);
            var proxy   = ActorServiceProxy.Create(serviceUri, actorId);

            return(proxy.DeleteActorAsync(actorId, CancellationToken.None));
        }
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            // create a remote connecting proxy to actor of which backup needs to be taken
            IBackupActorService myActorServiceProxy = ActorServiceProxy.Create <IBackupActorService>(
                new Uri("fabric:/ServiceFabricBackupRestore/BackupActorService"), ActorId.CreateRandom());

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                // call to take stateful service backup
                await PeriodicTakeBackupAsync(cancellationToken);

                // call to take actor backup
                await myActorServiceProxy.PeriodicTakeBackupAsync();

                using (var tx = this.StateManager.CreateTransaction())
                {
                    // If an exception is thrown before calling CommitAsync, the transaction aborts, all changes are
                    // discarded, and nothing is saved to the secondary replicas.
                    await tx.CommitAsync();
                }

                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
            }
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="kpuIdSearchFor"></param>
        /// <returns></returns>
        public Task <IToHActor> GetActorFromKpuId(string kpuIdSearchFor)
        {
            CancellationTokenSource source            = new CancellationTokenSource();
            CancellationToken       cancellationToken = source.Token;

            int partitionKey = 0;

            IActorService actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/CWF.Fabric.Services/ToHActorService"), 0);

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

            do
            {
                Task <PagedResult <ActorInformation> > pageTask = actorServiceProxy.GetActorsAsync(continuationToken, cancellationToken);

                PagedResult <ActorInformation> page = pageTask.Result;
                activeActors.AddRange(page.Items.Where(x => x.IsActive));

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

            foreach (ActorInformation info in activeActors)
            {
                var           proxy = ActorProxy.Create <IToHActor>(info.ActorId, "fabric:/CWF.Fabric.Services");
                Task <string> kpuId = proxy.GetKpuId();
                var           kpuid = kpuId.Result;
                if (kpuid.CompareTo(kpuIdSearchFor) == 0)
                {
                    return(Task.FromResult <IToHActor>(proxy));
                }
            }
            return(null);
        }
        public async Task Delete(string actorId)
        {
            var           actorIdObj        = new ActorId(actorId);
            IActorService actorServiceProxy = null;

            try
            {
                actorServiceProxy = ActorServiceProxy.Create(
                    new Uri("fabric:/DataLossCheckApp/ConActorService"),
                    actorIdObj);
                await actorServiceProxy.DeleteActorAsync(actorIdObj, CancellationToken.None);

                // log message
                await Helper.LogMessage(actorId, $"DELETED");
            }
            catch (Exception ex)
            {
                // log message
                await Helper.LogMessage(actorId, $"DELETE ERROR - {ex.ToString()}");
            }
            finally
            {
                if (actorIdObj != null)
                {
                    actorIdObj = null;
                }
                if (actorServiceProxy != null)
                {
                    actorServiceProxy = null;
                }
            }
        }
Example #12
0
        public async Task <DeliveryResponse> DeliverAsync(DeliveryRequest deliveryRequest, CancellationToken cancellationToken)
        {
            try
            {
                var serviceUri = new Uri(connectorInfo.ConnectorUri);
                var actorId    = new ActorId(deliveryRequest.OutputMessage.Id);

                // Create actor instance
                var connector = ActorProxy.Create <IDispatcherConnector>(actorId, serviceUri);

                // Dispatch
                var response = await connector.DeliverAsync(deliveryRequest, cancellationToken);

                // Release the actor resource at once
                var serviceProxy = ActorServiceProxy.Create(serviceUri, actorId);
                TaskHelper.FireAndForget(() => serviceProxy.DeleteActorAsync(actorId, cancellationToken));

                return(response);
            }
            catch (Exception ex)
            {
                MessageDispatcherEventSource.Current.ErrorException(deliveryRequest.OutputMessage.MessageInfo.TrackingId, this, nameof(this.DeliverAsync), OperationStates.Failed, string.Empty, ex);
                return(new DeliveryResponse(RequestOutcome.UNKNOWN));
            }
        }
Example #13
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 }));
        }
 /// <summary>
 /// Schedule a task on the thread pool to delete the actor with a specific Id. Override if needed
 /// </summary>
 /// <param name="cancellationToken"></param>
 protected virtual void DisposeActor(ActorId actorId, Uri actorServiceUri, CancellationToken cancellationToken)
 {
     Task.Run(async() =>
     {
         var serviceProxy = ActorServiceProxy.Create(actorServiceUri, actorId);
         await serviceProxy.DeleteActorAsync(actorId, cancellationToken);
     }, cancellationToken);
 }
Example #15
0
        public async void Delete(string vehicleId)
        {
            var actorId = new ActorId($"SimulatedCar:{vehicleId}");
            var proxy   = ActorProxy.Create <ICarActor>(actorId);
            await proxy.StopAsync(CancellationToken.None);

            var serviceProxy = ActorServiceProxy.Create(new Uri("fabric:/CarActorSF/CarActorService"), actorId);
            await serviceProxy.DeleteActorAsync(actorId, CancellationToken.None);
        }
Example #16
0
 public WebFront(StatelessServiceContext context)
     : base(context)
 {
     this.LoadLiveCounterSettings();
     this.counter = new LivenessCounter <string>(expirationIntervalInSeconds, fuzzIntervalInSeconds);
     nodeName     = context.NodeContext.NodeName;
     serviceUri   = ActorNameFormat.GetFabricServiceUri(typeof(IContainerAggregatorActor));
     proxy        = ActorServiceProxy.Create <IContainerAggregator>(serviceUri, 0);
     reportTimer  = new Timer(this.Report, null, TimeSpan.FromSeconds(reportIntervalInSeconds), TimeSpan.FromSeconds(reportIntervalInSeconds));
 }
        private async Task <KeyValuePair <string, string> > GetRandomIdsAsync()
        {
            ServiceUriBuilder serviceUri = new ServiceUriBuilder(this.GetSetting(DeviceServiceName));
            Uri fabricServiceName        = serviceUri.ToUri();

            CancellationTokenSource cts        = new CancellationTokenSource(TimeSpan.FromMinutes(5));
            CancellationToken       token      = cts.Token;
            FabricClient            fc         = new FabricClient();
            ServicePartitionList    partitions = await fc.QueryManager.GetPartitionListAsync(fabricServiceName);

            string doctorId = null;

            while (!token.IsCancellationRequested && doctorId == null)
            {
                try
                {
                    foreach (Partition p in partitions)
                    {
                        long partitionKey = ((Int64RangePartitionInformation)p.PartitionInformation).LowKey;
                        token.ThrowIfCancellationRequested();
                        ContinuationToken queryContinuationToken = null;
                        IActorService     proxy = ActorServiceProxy.Create(fabricServiceName, partitionKey);
                        PagedResult <ActorInformation> result = await proxy.GetActorsAsync(queryContinuationToken, token);

                        foreach (ActorInformation info in result.Items)
                        {
                            token.ThrowIfCancellationRequested();

                            ActorId      deviceActorId = info.ActorId;
                            IDeviceActor deviceActor   = ActorProxy.Create <IDeviceActor>(deviceActorId, fabricServiceName);

                            try
                            {
                                doctorId = (await deviceActor.GetAssociatedDoctorAsync()).ToString();

                                return(new KeyValuePair <string, string>(deviceActorId.ToString(), doctorId));
                            }
                            catch (Exception e)
                            {
                                ServiceEventSource.Current.Message("Exception when obtaining actor ID. No State? " + e.ToString());
                                continue;
                            }
                        }
                        //otherwise we will bounce around other partitions until we find an actor
                    }
                }
                catch (Exception e)
                {
                    ServiceEventSource.Current.Message("Exception when obtaining actor ID: " + e.ToString());
                    continue;
                }
            }

            throw new InvalidOperationException("Couldn't find actor within timeout");
        }
        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);
        }
Example #19
0
        protected override async Task OnDeactivateAsync()
        {
            if (_updateTimer != null)
            {
                UnregisterTimer(_updateTimer);
            }

            await ActorServiceProxy.Create <IActorBaseService>(ServiceUri, Id).DeactivateAsync(Id);

            await base.OnDeactivateAsync();
        }
        public async Task DeleteActorById([FromQuery] int id)
        {
            var actorId = new ActorId(id);                                                                                                        // we're creating new Actor's Id

            var actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/ProductActorAplication/ProductActorServiceActorService"), actorId); // we're connecting to actor service, not actor itself

            await actorServiceProxy.DeleteActorAsync(actorId, new CancellationToken());                                                           // allows us to delete actor and state

            // note: common use of this is when for example service proxy is on timer (e.g. one a day/week)
            // so we iterate through all actors and we delete the ones which meets conditions of being certain time old
        }
Example #21
0
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        private static void Main()
        {
            try
            {
                // The contents of your ServiceManifest.xml and ApplicationManifest.xml files
                // are automatically populated when you build this project.
                // For more information, see https://aka.ms/servicefabricactorsplatform

                var builder = new ContainerBuilder();

                // Register a type that be injected into the actor service.
                builder.Register(c => new Logger()).As <ILogger>();

                // Register the interceptors for managing lifetime scope disposal.
                builder.RegisterModule <AutofacServiceFabricModule>();

                // Register all actors in the specified assemblies.
                builder.RegisterActors(Assembly.GetExecutingAssembly());

                // Register a single actor.
                //builder.RegisterActor<DemoActor>();

                using (var container = builder.Build())
                {
                    // Register an actor service factory with the ActorRuntime.
                    container.RegisterActorServiceFactory <DemoActor>();

                    Task.Run(() =>
                    {
                        Task.Delay(TimeSpan.FromSeconds(15));

                        // Invoke the actor to create an instance.
                        var actorId    = ActorId.CreateRandom();
                        var actorProxy = ActorProxy.Create <IDemoActor>(actorId);
                        var count      = actorProxy.GetCountAsync(new CancellationToken()).GetAwaiter().GetResult();

                        Debug.WriteLine($"Actor {actorId} has count {count}");

                        // Delete the actor to trigger deactive.
                        var actorServiceProxy = ActorServiceProxy.Create(
                            new Uri("fabric:/AutofacServiceFabricDemo/DemoActorService"), actorId);

                        actorServiceProxy.DeleteActorAsync(actorId, new CancellationToken()).GetAwaiter().GetResult();
                    });

                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception e)
            {
                ActorEventSource.Current.ActorHostInitializationFailed(e.ToString());
                throw;
            }
        }
Example #22
0
        public async Task DeleteWorkerAsync(Guid uuid, CancellationToken cancellationToken)
        {
            var actorId      = new ActorId(uuid);
            var actorService = ActorServiceProxy.Create(workerServiceUri, actorId);
            var page         = await actorService.GetActorsAsync(null, cancellationToken);

            if (page.Items.Any(x => x.ActorId == actorId && x.IsActive))
            {
                await actorService.DeleteActorAsync(actorId, cancellationToken);
            }
        }
        private async Task <List <ActorInformation> > GetAllActors(Uri servicePath)
        {
            FabricClient.QueryClient query = new FabricClient().QueryManager;
            List <long> partitions         = new List <long>();
            string      continuation       = null;

            do
            {
                ServicePartitionList partitionList =
                    await query.GetPartitionListAsync(servicePath, continuation);

                foreach (Partition item in partitionList)
                {
                    ServicePartitionInformation info = item.PartitionInformation;
                    switch (info.Kind)
                    {
                    case ServicePartitionKind.Int64Range:
                        partitions.Add(((Int64RangePartitionInformation)info).LowKey);
                        break;

                    case ServicePartitionKind.Singleton:
                        partitions.Add(0L);
                        break;

                    default:
                        throw new InvalidOperationException(
                                  string.Format(
                                      "Unexpected partition kind.  Found {0}, expected either Int64Range or Singleton",
                                      info.Kind));
                    }
                }
                continuation = partitionList.ContinuationToken;
            } while (!string.IsNullOrEmpty(continuation));

            List <ActorInformation> activeActors = new List <ActorInformation>();

            foreach (long partitionId in partitions)
            {
                IActorService     actorServiceProxy = ActorServiceProxy.Create(servicePath, partitionId);
                ContinuationToken continuationToken = null;

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

                    activeActors.AddRange(page.Items);
                    continuationToken = page.ContinuationToken;
                } while (continuationToken != null);
            }
            return(activeActors);
        }
        public async Task <IActionResult> DeleteMonitor(string serviceName)
        {
            if (string.IsNullOrWhiteSpace(serviceName))
            {
                return(BadRequest());
            }

            var n = new Uri("fabric:/" + serviceName);
            var p = ActorProxy.Create <IMonitorActor>(new ActorId(n.ToString()));
            var s = ActorServiceProxy.Create(p.GetActorReference().ServiceUri, p.GetActorId());
            await s.DeleteActorAsync(p.GetActorId(), CancellationToken.None);

            return(Ok());
        }
Example #25
0
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        private static void Main()
        {
            try
            {
                // The contents of your ServiceManifest.xml and ApplicationManifest.xml files
                // are automatically populated when you build this project.
                // For more information, see https://aka.ms/servicefabricactorsplatform

                // Start with the trusty old container builder.
                var builder = new ContainerBuilder();

                // Register any regular dependencies.
                builder.RegisterModule(new LoggerModule(ActorEventSource.Current.Message));

                // Register the Autofac magic for Service Fabric support.
                builder.RegisterServiceFabricSupport();

                // Register the actor service.
                builder.RegisterActor <DemoActor>();

                using (builder.Build())
                {
                    Task.Run(async() =>
                    {
                        // Invoke the actor to create an instance.
                        var actorId    = ActorId.CreateRandom();
                        var actorProxy = ActorProxy.Create <IDemoActor>(actorId);
                        var count      = actorProxy.GetCountAsync(new CancellationToken()).GetAwaiter().GetResult();

                        Debug.WriteLine($"Actor {actorId} has count {count}");

                        await Task.Delay(TimeSpan.FromSeconds(15));

                        // Delete the actor to trigger deactive.
                        var actorServiceProxy = ActorServiceProxy.Create(
                            new Uri("fabric:/AutofacServiceFabricDemo/DemoActorService"), actorId);

                        await actorServiceProxy.DeleteActorAsync(actorId, new CancellationToken());
                    });

                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception e)
            {
                ActorEventSource.Current.ActorHostInitializationFailed(e.ToString());
                throw;
            }
        }
        public async Task DestroyAsync(T actor, CancellationToken cancellationToken)
        {
            try
            {
                ActorId actorId = actor.GetActorId();

                IActorService myActorServiceProxy = ActorServiceProxy.Create(
                    new Uri($"{FabricRuntime.GetActivationContext().ApplicationName}/{_actorServiceName}"), actorId);

                await myActorServiceProxy.DeleteActorAsync(actorId, cancellationToken);
            }
            catch (Exception ex)
            {
            }
        }
Example #27
0
        public static async Task <bool> DeleteActor <T>(this ActorId id, Uri serviceUri = null) where T : IActor
        {
            CancellationToken token = new CancellationToken();

            if (serviceUri == null)
            {
                serviceUri = ServiceUriHelper.Resolve <T>();
            }
            var            proxy             = id.Proxy <T>(serviceUri);
            ActorReference actorReference    = ActorReference.Get(proxy);
            var            actorServiceProxy = ActorServiceProxy.Create(actorReference.ServiceUri, id);
            await actorServiceProxy.DeleteActorAsync(id, token);

            return(await Task.FromResult(true));
        }
        public int DeleteAll(int bogus = 1)
        {
            IEnumerable <string> actorIds         = Get().SelectMany(x => x.ActorsInPartition);
            CancellationToken    cancelationToken = default(CancellationToken);
            int count = 0;

            foreach (string actorId in actorIds)
            {
                ActorId       actorToDelete       = new ActorId(actorId);
                IActorService myActorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/SFActors.BankAccounts/BankAccountActorService"), actorToDelete);
                myActorServiceProxy.DeleteActorAsync(actorToDelete, cancelationToken);
                count++;
            }

            return(count);
        }
        private async Task RunAsyncInternal(CancellationToken cancellationToken)
        {
            IRuntimeStore runtimeStoreClient = ServiceProxy.Create <IRuntimeStore>(new Uri("fabric:/Prototype/RuntimeStore"), new ServicePartitionKey(0));

            ServiceEventSource.Current.ServiceMessage(this.Context, "Service has woken up and executing now.");

            // Get the tenant id from Runtime store
            long actorId = await runtimeStoreClient.GetTenantInProgress();

            if (actorId == -1)
            {
                ServiceEventSource.Current.ServiceMessage(this.Context, "No tenant found to work on.");
                return;
            }

            ServiceEventSource.Current.ServiceMessage(this.Context, "Got tenant {0} to work on.", actorId);

            ITenantUpdateActor tenantUpdateActor = ActorProxy.Create <ITenantUpdateActor>(new ActorId(actorId), actorServicePath);
            string             currentState      = await tenantUpdateActor.GetWorkflowState();

            ServiceEventSource.Current.ServiceMessage(this.Context, "Current state of tenant {0} is {1}", actorId, currentState);

            if (currentState == "Completed")// any terminal
            {
                // Move tenant id in runtime store to Terminal Queue
                ServiceEventSource.Current.ServiceMessage(this.Context, "Moving the tenant to terminal state.");
                await runtimeStoreClient.TransitionTenantToTerminal(actorId, "Completed");

                // Delete actor
                ServiceEventSource.Current.ServiceMessage(this.Context, "Deleting the actor {0} in service.", actorId);
                ActorId       actorToDelete       = new ActorId(actorId);
                IActorService myActorServiceProxy = ActorServiceProxy.Create(actorServicePath, actorToDelete);
                await myActorServiceProxy.DeleteActorAsync(actorToDelete, cancellationToken);
            }
            else
            {
                // TODO Call Execute, mainly to make sure that it is doing work and if needed, move to alerted state

                /*ServiceEventSource.Current.ServiceMessage(this.Context, "Executing the actor {0} in service.", actorId);
                 * await tenantUpdateActor.Execute();*/

                // Re-put to the in-progress queue
                await runtimeStoreClient.AddTenantInProgress(actorId, "InProgress");
            }

            // If workflow running for long and still, not complete, set to terminal state
        }
        public async Task StopSimulation(string simulationName)
        {
            var fabricClient = new FabricClient();
            var deleteTasks  = new List <Task>();

            // Find all partitions for the device simulator actor application
            foreach (var partition in await fabricClient.QueryManager.GetPartitionListAsync(deviceActorApplicationUri))
            {
                var partitionInformation = ((Int64RangePartitionInformation)partition.PartitionInformation);

                // Get the rangs of possible partition key values in the partition
                var partitionKeyRange = CreateLongRange(partitionInformation.LowKey, partitionInformation.HighKey);

                foreach (var partitionKey in partitionKeyRange)
                {
                    // Get the actor service for this particular partition key
                    var actorService = ActorServiceProxy.Create(deviceActorApplicationUri, partitionKey);

                    var pagedResult = default(PagedResult <ActorInformation>);

                    // Page through all the actors in this partition and delete them concurrently
                    do
                    {
                        pagedResult = await actorService.GetActorsAsync(pagedResult?.ContinuationToken, CancellationToken.None);

                        foreach (var actorInformation in pagedResult.Items)
                        {
                            deleteTasks.Add(actorService.DeleteActorAsync(actorInformation.ActorId, CancellationToken.None));
                        }

                        // Wait for the actors in this page to be deleted
                        await Task.WhenAll(deleteTasks);
                    }while (pagedResult.ContinuationToken != null);
                }

                deleteTasks.Clear();
            }

            IEnumerable <long> CreateLongRange(long start, long end)
            {
                for (var i = start; i <= end; i++)
                {
                    yield return(i);
                }
            }
        }