Esempio n. 1
0
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(LockFileProjectLibrary library,
                                                                        Runtime.Project projectInfo,
                                                                        RestoreContext context)
        {
            var lockFileLib = new LockFileTargetLibrary
            {
                Name    = library.Name,
                Version = library.Version,
                Type    = "project"
            };

            var targetFrameworkInfo = projectInfo.GetTargetFramework(context.FrameworkName);
            var dependencies        = projectInfo.Dependencies.Concat(targetFrameworkInfo.Dependencies);

            foreach (var dependency in dependencies)
            {
                if (dependency.LibraryRange.IsGacOrFrameworkReference)
                {
                    lockFileLib.FrameworkAssemblies.Add(
                        LibraryRange.GetAssemblyName(dependency.LibraryRange.Name));
                }
                else
                {
                    lockFileLib.Dependencies.Add(new PackageDependency(
                                                     dependency.LibraryRange.Name,
                                                     dependency.LibraryRange.VersionRange));
                }
            }

            return(lockFileLib);
        }
Esempio n. 2
0
        // OnDataLossAsync is the restore part of the process. This is NOT an arbitrary name, it is an override of the
        // method on StatefulServiceBase.
        // The method below looks in the backupFolder directory (where the backup files were
        // stored in BackupCallbackAsync above), searches for the folder of backup files that have the newest ListWriteTime, then restores them.
        // Once the RestoreDescription object is told where to find your data, RestoreAsync is called
        // to restore that data to the reliable objects
        // Each partition will have OnDataLossAsync called on it
        protected override async Task <bool> OnDataLossAsync(RestoreContext restoreCtx,
                                                             CancellationToken cancellationToken)
        {
            string backupFolder;

            ServiceEventSource.Current.ServiceMessage(this, "OnDataLoss Invoked!");

            this.SetupBackupManager();

            try
            {
                if (this.backupStorageType == BackupManagerType.None)
                {
                    //since we have no backup configured, we return false to indicate
                    //that state has not changed. This replica will become the basis
                    //for future replica builds
                    return(false);
                }
                else
                {
                    backupFolder =
                        await this.backupManager.RestoreLatestBackupToTempLocation(cancellationToken);
                }


                ServiceEventSource.Current.ServiceMessage(this, "Restoration Folder Path " + backupFolder);

                RestoreDescription restoreDescription =
                    new RestoreDescription(backupFolder, RestorePolicy.Force);

                // Restore the backup copy
                await restoreCtx.RestoreAsync(restoreDescription, cancellationToken);

                ServiceEventSource.Current.ServiceMessage(this, "Restore completed");

                // Clean up the local temporary directory (the root directory where all backups were unzipped in to)
                try
                {
                    DirectoryInfo tempRestoreDirectory = new DirectoryInfo(backupFolder);
                    tempRestoreDirectory.Delete(true);
                }
                catch (System.Exception ddel)
                {
                    ServiceEventSource.Current.ServiceMessage(this, "OnDataLossAsync: Delete of backup folder failed with {0}", ddel.Message);
                }

                // now that a restore has been performed, reset the full backup flag and incremental
                // counter so you start fresh again
                // You will need to change this type of logic for your own scenario
                takeFullBackup   = true;
                incrementalCount = 0;

                return(true);
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(this, "Restoration failed: " + "{0} {1}" + e.GetType() + e.Message);
                throw;
            }
        }
Esempio n. 3
0
        public async Task RestoreAsync(RestoreContext context,
                                       CancellationToken ct)
        {
            var json = await context.Reader.ReadJsonAsync <JsonObject>(SettingsFile, ct);

            await appUISettings.SetAsync(context.AppId, null, json);
        }
Esempio n. 4
0
        public IDisposable MakeCurrent(EglSurface surface)
        {
            Monitor.Enter(_lock);
            var success = false;

            try
            {
                var old  = new RestoreContext(_egl, _disp.Handle, _lock);
                var surf = surface ?? OffscreenSurface;
                _egl.MakeCurrent(_disp.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                if (!_egl.MakeCurrent(_disp.Handle, surf?.DangerousGetHandle() ?? IntPtr.Zero,
                                      surf?.DangerousGetHandle() ?? IntPtr.Zero, Context))
                {
                    throw OpenGlException.GetFormattedException("eglMakeCurrent", _egl);
                }
                success = true;
                return(old);
            }
            finally
            {
                if (!success)
                {
                    Monitor.Enter(_lock);
                }
            }
        }
Esempio n. 5
0
        private async Task RestoreTagsAsync(RestoreContext context,
                                            CancellationToken ct)
        {
            var tags = (Dictionary <string, Tag>?)null;

            if (await context.Reader.HasFileAsync(TagsFile, ct))
            {
                tags = await context.Reader.ReadJsonAsync <Dictionary <string, Tag> >(TagsFile, ct);
            }

            var alias = (Dictionary <string, string>?)null;

            if (await context.Reader.HasFileAsync(TagsAliasFile, ct))
            {
                alias = await context.Reader.ReadJsonAsync <Dictionary <string, string> >(TagsAliasFile, ct);
            }

            if (alias == null && tags == null)
            {
                return;
            }

            var export = new TagsExport {
                Tags = tags, Alias = alias
            };

            await tagService.RebuildTagsAsync(context.AppId, TagGroups.Assets, export);
        }
        protected override async Task <bool> OnDataLossAsync(RestoreContext restoreCtx, CancellationToken cancellationToken)
        {
            ServiceEventSource.Current.ServiceMessage(this.Context, "OnDataLoss Invoked!");
            this.SetupBackupManager();

            try
            {
                string backupFolder;

                backupFolder = await this.backupManager.RestoreLatestBackupToTempLocation(cancellationToken);

                ServiceEventSource.Current.ServiceMessage(this.Context, "Restoration Folder Path " + backupFolder);

                RestoreDescription restoreRescription = new RestoreDescription(backupFolder, RestorePolicy.Force);
                await restoreCtx.RestoreAsync(restoreRescription, cancellationToken);

                ServiceEventSource.Current.ServiceMessage(this.Context, "Restore completed");

                DirectoryInfo tempRestoreDirectory = new DirectoryInfo(backupFolder);
                tempRestoreDirectory.Delete(true);

                return(true);
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(this.Context, "Restoration failed: " + "{0} {1}" + e.GetType() + e.Message);

                throw;
            }
        }
Esempio n. 7
0
        public async Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context)
        {
            switch (@event.Payload)
            {
            case AssetFolderCreated _:
                assetFolderIds.Add(@event.Headers.AggregateId());
                break;

            case AssetCreated assetCreated:
                assetIds.Add(@event.Headers.AggregateId());

                await ReadAssetAsync(
                    assetCreated.AppId.Id,
                    assetCreated.AssetId,
                    assetCreated.FileVersion,
                    context.Reader);

                break;

            case AssetUpdated assetUpdated:
                await ReadAssetAsync(
                    assetUpdated.AppId.Id,
                    assetUpdated.AssetId,
                    assetUpdated.FileVersion,
                    context.Reader);

                break;
            }

            return(true);
        }
Esempio n. 8
0
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(Runtime.Project projectDependency,
                                                                        RestoreContext context)
        {
            var targetFrameworkInfo = projectDependency.GetCompatibleTargetFramework(context.FrameworkName);

            var lockFileLib = new LockFileTargetLibrary
            {
                Name = projectDependency.Name,
                Version = projectDependency.Version,
                TargetFramework = targetFrameworkInfo.FrameworkName, // null TFM means it's incompatible
                Type = "project"
            };

            var dependencies = projectDependency.Dependencies.Concat(targetFrameworkInfo.Dependencies);

            foreach (var dependency in dependencies)
            {
                if (dependency.LibraryRange.IsGacOrFrameworkReference)
                {
                    lockFileLib.FrameworkAssemblies.Add(
                        LibraryRange.GetAssemblyName(dependency.LibraryRange.Name));
                }
                else
                {
                    lockFileLib.Dependencies.Add(new PackageDependency(
                        dependency.LibraryRange.Name, 
                        dependency.LibraryRange.VersionRange));
                }
            }

            return lockFileLib;
        }
Esempio n. 9
0
        public async Task RestoreAsync(RestoreContext context)
        {
            await RestoreTagsAsync(context);

            if (assetIds.Count > 0)
            {
                await rebuilder.InsertManyAsync <AssetDomainObject, AssetState>(async target =>
                {
                    foreach (var id in assetIds)
                    {
                        await target(id);
                    }
                });
            }

            if (assetFolderIds.Count > 0)
            {
                await rebuilder.InsertManyAsync <AssetFolderDomainObject, AssetFolderState>(async target =>
                {
                    foreach (var id in assetFolderIds)
                    {
                        await target(id);
                    }
                });
            }
        }
Esempio n. 10
0
        public async Task CompleteRestoreAsync(RestoreContext context, string appName)
        {
            await rebuilder.InsertManyAsync <AppDomainObject, AppDomainObject.State>(Enumerable.Repeat(context.AppId, 1), 1, default);

            await appsIndex.RegisterAsync(context.AppId, appName);

            await appsIndex.RemoveReservationAsync(appReservation);
        }
Esempio n. 11
0
 public async Task RestoreAsync(RestoreContext context,
                                CancellationToken ct)
 {
     if (ruleIds.Count > 0)
     {
         await rebuilder.InsertManyAsync <RuleDomainObject, RuleDomainObject.State>(ruleIds, BatchSize, ct);
     }
 }
        protected override async Task <bool> OnDataLossAsync(RestoreContext restoreContext, CancellationToken cancellationToken)
        {
            await DatalossHelper.UpdateHeathStateAsync(isHealthy : false).ConfigureAwait(false);

            UpgradeOrchestrationTrace.TraceSource.WriteWarning(TraceType, "Data loss happens. Manual cluster config upgrade is required to fix.");

            return(false);
        }
Esempio n. 13
0
        public async Task RestoreAsync(RestoreContext context)
        {
            var ids = contentIdsBySchemaId.Values.SelectMany(x => x);

            if (ids.Any())
            {
                await rebuilder.InsertManyAsync <ContentDomainObject, ContentDomainObject.State>(ids, BatchSize);
            }
        }
Esempio n. 14
0
        protected override async Task <bool> OnDataLossAsync(RestoreContext restoreCtx, CancellationToken cancellationToken)
        {
            Log.WriteLine("{0}", $"Partition {GraphEngineStatefulServiceRuntime.Instance.PartitionId} received OnDataLossAsync. Triggering data restore.");
            RestoreEventArgs rstArgs = new RestoreEventArgs(restoreCtx, cancellationToken);

            RequestRestore(this, rstArgs);
            await rstArgs.Wait();

            return(true);
        }
 /// <summary>
 /// Creates a new StatefulService.
 /// </summary>
 /// <param name="serviceContext">
 /// A <see cref="StatefulServiceContext"/> that describes the service context.
 /// </param>
 /// <param name="stateProviderReplica">
 /// A <see cref="IStateProviderReplica"/> that represents a reliable state provider replica.
 /// </param>
 protected StatefulServiceBase(
     StatefulServiceContext serviceContext,
     IStateProviderReplica stateProviderReplica)
 {
     this.stateProviderReplica = stateProviderReplica;
     this.stateProviderReplica.OnDataLossAsync = this.OnDataLossAsync;
     this.restoreContext = new RestoreContext(this.stateProviderReplica);
     this.serviceContext = serviceContext;
     this.addresses      = new ReadOnlyDictionary <string, string>(new Dictionary <string, string>());
 }
        protected override async Task <bool> OnDataLossAsync(RestoreContext restoreCtx, CancellationToken cancellationToken)
        {
            var backupsourcedir = this._fileStore.GetRestoreDirectory();

            this._serviceEventSource.Message($"BackupRestoreStatefulService: Restoring backup of partition { Context.PartitionId} of service {Context.ServiceName.AbsoluteUri} from {backupsourcedir}");
            await restoreCtx.RestoreAsync(new RestoreDescription(backupsourcedir, RestorePolicy.Force), cancellationToken);

            this._serviceEventSource.Message($"BackupRestoreStatefulService: Backup of partition { Context.PartitionId} of service {Context.ServiceName.AbsoluteUri} from {backupsourcedir} has been restored!");
            return(true);
        }
Esempio n. 17
0
        public IDisposable MakeCurrent(IntPtr xid)
        {
            var old = new RestoreContext(Glx, _x11.Display);

            if (!Glx.MakeContextCurrent(_x11.Display, xid, xid, Handle))
            {
                throw new OpenGlException("glXMakeContextCurrent failed ");
            }
            return(old);
        }
Esempio n. 18
0
        public async Task Should_restore_states_for_all_contents()
        {
            var me = new RefToken(RefTokenType.Subject, "123");

            var schemaId1 = NamedId.Of(DomainId.NewGuid(), "my-schema1");
            var schemaId2 = NamedId.Of(DomainId.NewGuid(), "my-schema2");

            var contentId1 = DomainId.NewGuid();
            var contentId2 = DomainId.NewGuid();
            var contentId3 = DomainId.NewGuid();

            var context = new RestoreContext(appId.Id, new UserMapping(me), A.Fake <IBackupReader>(), DomainId.NewGuid());

            await sut.RestoreEventAsync(ContentEvent(new ContentCreated
            {
                ContentId = contentId1,
                SchemaId = schemaId1
            }), context);

            await sut.RestoreEventAsync(ContentEvent(new ContentCreated
            {
                ContentId = contentId2,
                SchemaId = schemaId1
            }), context);

            await sut.RestoreEventAsync(ContentEvent(new ContentCreated
            {
                ContentId = contentId3,
                SchemaId = schemaId2
            }), context);

            await sut.RestoreEventAsync(ContentEvent(new ContentDeleted
            {
                ContentId = contentId2,
                SchemaId = schemaId1
            }), context);

            await sut.RestoreEventAsync(Envelope.Create(new SchemaDeleted
            {
                SchemaId = schemaId2
            }), context);

            var rebuildContents = new HashSet <DomainId>();

            A.CallTo(() => rebuilder.InsertManyAsync <ContentDomainObject, ContentState>(A <IEnumerable <DomainId> > ._, A <CancellationToken> ._))
            .Invokes((IEnumerable <DomainId> source, CancellationToken _) => rebuildContents.AddRange(source));

            await sut.RestoreAsync(context);

            Assert.Equal(new HashSet <DomainId>
            {
                DomainId.Combine(appId.Id, contentId1),
                DomainId.Combine(appId.Id, contentId2)
            }, rebuildContents);
        }
Esempio n. 19
0
        public IDisposable MakeCurrent()
        {
            var old = new RestoreContext(_egl, _disp.Handle);

            _egl.MakeCurrent(_disp.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            if (!_egl.MakeCurrent(_disp.Handle, IntPtr.Zero, IntPtr.Zero, Context))
            {
                throw OpenGlException.GetFormattedException("eglMakeCurrent", _egl);
            }
            return(old);
        }
Esempio n. 20
0
        protected override async Task <bool> OnDataLossAsync(
            RestoreContext restoreCtx,
            CancellationToken cancellationToken)
        {
            var ctx     = new StatefulServiceRestoreContext(restoreCtx);
            var payload = new StatefulServiceEventPayloadOnDataLoss(ctx);

            await this.serviceEvents.NotifyDataLossAsync(payload, cancellationToken);

            return(ctx.IsRestored);
        }
Esempio n. 21
0
        public IDisposable MakeCurrent(EglSurface surface)
        {
            var old  = new RestoreContext(_egl, _disp.Handle);
            var surf = surface ?? OffscreenSurface;

            _egl.MakeCurrent(_disp.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            if (!_egl.MakeCurrent(_disp.Handle, surf.DangerousGetHandle(), surf.DangerousGetHandle(), Context))
            {
                throw OpenGlException.GetFormattedException("eglMakeCurrent", _egl);
            }
            return(old);
        }
Esempio n. 22
0
 public async Task RestoreAsync(RestoreContext context)
 {
     if (contentIdsBySchemaId.Count > 0)
     {
         await rebuilder.InsertManyAsync <ContentDomainObject, ContentState>(async target =>
         {
             foreach (var contentId in contentIdsBySchemaId.Values.SelectMany(x => x))
             {
                 await target(contentId);
             }
         });
     }
 }
Esempio n. 23
0
        public async Task RestoreAsync(RestoreContext context)
        {
            await RestoreTagsAsync(context);

            if (assetIds.Count > 0)
            {
                await rebuilder.InsertManyAsync <AssetDomainObject, AssetState>(assetIds);
            }

            if (assetFolderIds.Count > 0)
            {
                await rebuilder.InsertManyAsync <AssetFolderDomainObject, AssetFolderState>(assetFolderIds);
            }
        }
Esempio n. 24
0
        public async Task RestoreAsync(RestoreContext context,
                                       CancellationToken ct)
        {
            await RestoreTagsAsync(context, ct);

            if (assetIds.Count > 0)
            {
                await rebuilder.InsertManyAsync <AssetDomainObject, AssetDomainObject.State>(assetIds, BatchSize, ct);
            }

            if (assetFolderIds.Count > 0)
            {
                await rebuilder.InsertManyAsync <AssetFolderDomainObject, AssetFolderDomainObject.State>(assetFolderIds, BatchSize, ct);
            }
        }
Esempio n. 25
0
        public Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context)
        {
            switch (@event.Payload)
            {
            case ContentCreated contentCreated:
                contentIdsBySchemaId.GetOrAddNew(contentCreated.SchemaId.Id).Add(contentCreated.ContentId);
                break;

            case SchemaDeleted schemaDeleted:
                contentIdsBySchemaId.Remove(schemaDeleted.SchemaId.Id);
                break;
            }

            return(TaskHelper.True);
        }
Esempio n. 26
0
        public Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context)
        {
            switch (@event.Payload)
            {
            case ContentCreated contentCreated:
                contentIdsBySchemaId.GetOrAddNew(contentCreated.SchemaId.Id).Add(@event.Headers.AggregateId());
                break;

            case SchemaDeleted schemaDeleted:
                contentIdsBySchemaId.Remove(schemaDeleted.SchemaId.Id);
                break;
            }

            return(Task.FromResult(true));
        }
Esempio n. 27
0
        public Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context)
        {
            switch (@event.Payload)
            {
            case RuleCreated ruleCreated:
                ruleIds.Add(ruleCreated.RuleId);
                break;

            case RuleDeleted ruleDeleted:
                ruleIds.Remove(ruleDeleted.RuleId);
                break;
            }

            return(Task.FromResult(true));
        }
Esempio n. 28
0
        public Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context)
        {
            switch (@event.Payload)
            {
            case SchemaCreated schemaCreated:
                schemasByName[schemaCreated.SchemaId.Name] = schemaCreated.SchemaId.Id;
                break;

            case SchemaDeleted schemaDeleted:
                schemasByName.Remove(schemaDeleted.SchemaId.Name);
                break;
            }

            return(TaskHelper.True);
        }
Esempio n. 29
0
        public Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context,
                                             CancellationToken ct)
        {
            switch (@event.Payload)
            {
            case RuleCreated:
                ruleIds.Add(@event.Headers.AggregateId());
                break;

            case RuleDeleted:
                ruleIds.Remove(@event.Headers.AggregateId());
                break;
            }

            return(Task.FromResult(true));
        }
Esempio n. 30
0
        public async Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context,
                                                   CancellationToken ct)
        {
            switch (@event.Payload)
            {
            case AppCreated appCreated:
            {
                await ReserveAppAsync(context.AppId, appCreated.Name, ct);

                break;
            }

            case AppImageUploaded:
            {
                await ReadAssetAsync(context.AppId, context.Reader, ct);

                break;
            }

            case AppContributorAssigned contributorAssigned:
            {
                if (!context.UserMapping.TryMap(contributorAssigned.ContributorId, out var user) || user.Equals(context.Initiator))
                {
                    return(false);
                }

                contributorAssigned.ContributorId = user.Identifier;
                contributors.Add(contributorAssigned.ContributorId);
                break;
            }

            case AppContributorRemoved contributorRemoved:
            {
                if (!context.UserMapping.TryMap(contributorRemoved.ContributorId, out var user) || user.Equals(context.Initiator))
                {
                    return(false);
                }

                contributorRemoved.ContributorId = user.Identifier;
                contributors.Remove(contributorRemoved.ContributorId);
                break;
            }
            }

            return(true);
        }
Esempio n. 31
0
        public async Task Should_restore_indices_for_all_non_deleted_rules()
        {
            var appId = Guid.NewGuid();

            var ruleId1 = Guid.NewGuid();
            var ruleId2 = Guid.NewGuid();
            var ruleId3 = Guid.NewGuid();

            var context = new RestoreContext(appId, new UserMapping(new RefToken(RefTokenType.Subject, "123")), A.Fake <IBackupReader>());

            await sut.RestoreEventAsync(Envelope.Create(new RuleCreated
            {
                RuleId = ruleId1
            }), context);

            await sut.RestoreEventAsync(Envelope.Create(new RuleCreated
            {
                RuleId = ruleId2
            }), context);

            await sut.RestoreEventAsync(Envelope.Create(new RuleCreated
            {
                RuleId = ruleId3
            }), context);

            await sut.RestoreEventAsync(Envelope.Create(new RuleDeleted
            {
                RuleId = ruleId3
            }), context);

            HashSet <Guid>?newIndex = null;

            A.CallTo(() => index.RebuildAsync(appId, A <HashSet <Guid> > ._))
            .Invokes(new Action <Guid, HashSet <Guid> >((_, i) => newIndex = i));

            await sut.RestoreAsync(context);

            Assert.Equal(new HashSet <Guid>
            {
                ruleId1,
                ruleId2
            }, newIndex);
        }
Esempio n. 32
0
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(LockFileLibrary library, IPackage package, RestoreContext context, string correctedPackageName)
        {
            var lockFileLib = new LockFileTargetLibrary();

            var framework = context.FrameworkName;
            var runtimeIdentifier = context.RuntimeName;

            // package.Id is read from nuspec and it might be in wrong casing.
            // correctedPackageName should be the package name used by dependency graph and
            // it has the correct casing that runtime needs during dependency resolution.
            lockFileLib.Name = correctedPackageName ?? package.Id;
            lockFileLib.Version = package.Version;
            var files = library.Files.Select(p => p.Replace(Path.DirectorySeparatorChar, '/'));
            var contentItems = new ContentItemCollection();
            contentItems.Load(files);

            IEnumerable<PackageDependencySet> dependencySet;
            if (VersionUtility.GetNearest(framework, package.DependencySets, out dependencySet))
            {
                var set = dependencySet.FirstOrDefault()?.Dependencies?.ToList();

                if (set != null)
                {
                    lockFileLib.Dependencies = set;
                }
            }

            // TODO: Remove this when we do #596
            // ASP.NET Core and .NET Core 5.0 don't have framework reference assemblies
            if (!VersionUtility.IsPackageBased(framework))
            {
                IEnumerable<FrameworkAssemblyReference> frameworkAssemblies;
                if (VersionUtility.GetNearest(framework, package.FrameworkAssemblies, out frameworkAssemblies))
                {
                    AddFrameworkReferences(lockFileLib, framework, frameworkAssemblies);
                }

                // Add framework assemblies with empty supported frameworks
                AddFrameworkReferences(lockFileLib, framework, package.FrameworkAssemblies.Where(f => !f.SupportedFrameworks.Any()));
            }

            var patterns = PatternDefinitions.DotNetPatterns;

            var criteriaBuilderWithTfm = new SelectionCriteriaBuilder(patterns.Properties.Definitions);
            var criteriaBuilderWithoutTfm = new SelectionCriteriaBuilder(patterns.Properties.Definitions);

            if (context.RuntimeSpecs != null)
            {
                foreach (var runtimeSpec in context.RuntimeSpecs)
                {
                    criteriaBuilderWithTfm = criteriaBuilderWithTfm
                        .Add["tfm", framework]["rid", runtimeSpec.Name];

                    criteriaBuilderWithoutTfm = criteriaBuilderWithoutTfm
                        .Add["rid", runtimeSpec.Name];
                }
            }

            criteriaBuilderWithTfm = criteriaBuilderWithTfm
                .Add["tfm", framework];

            var criteria = criteriaBuilderWithTfm.Criteria;

            var compileGroup = contentItems.FindBestItemGroup(criteria, patterns.CompileTimeAssemblies, patterns.ManagedAssemblies);
            if (compileGroup != null)
            {
                lockFileLib.CompileTimeAssemblies = compileGroup.Items.Select(t => (LockFileItem)t.Path).ToList();
            }

            var runtimeGroup = contentItems.FindBestItemGroup(criteria, patterns.ManagedAssemblies);
            if (runtimeGroup != null)
            {
                lockFileLib.RuntimeAssemblies = runtimeGroup.Items.Select(p => (LockFileItem)p.Path).ToList();
            }

            var resourceGroup = contentItems.FindBestItemGroup(criteria, patterns.ResourceAssemblies);
            if (resourceGroup != null)
            {
                lockFileLib.ResourceAssemblies = resourceGroup.Items.Select(ToResourceLockFileItem).ToList();
            }

            var nativeGroup = contentItems.FindBestItemGroup(criteriaBuilderWithoutTfm.Criteria, patterns.NativeLibraries);
            if (nativeGroup != null)
            {
                lockFileLib.NativeLibraries = nativeGroup.Items.Select(p => (LockFileItem)p.Path).ToList();
            }

            // COMPAT: Support lib/contract so older packages can be consumed
            string contractPath = "lib/contract/" + package.Id + ".dll";
            var hasContract = files.Any(path => path == contractPath);
            var hasLib = lockFileLib.RuntimeAssemblies.Any();

            if (hasContract && hasLib && !VersionUtility.IsDesktop(framework))
            {
                lockFileLib.CompileTimeAssemblies.Clear();
                lockFileLib.CompileTimeAssemblies.Add(contractPath);
            }

            // See if there's a list of specific references defined for this target framework
            IEnumerable<PackageReferenceSet> referenceSets;
            if (VersionUtility.GetNearest(framework, package.PackageAssemblyReferences, out referenceSets))
            {
                // Get the first compatible reference set
                var referenceSet = referenceSets.FirstOrDefault();

                if (referenceSet != null)
                {
                    // Remove all assemblies of which names do not appear in the References list
                    lockFileLib.RuntimeAssemblies.RemoveAll(path => path.Path.StartsWith("lib/") && !referenceSet.References.Contains(Path.GetFileName(path), StringComparer.OrdinalIgnoreCase));
                    lockFileLib.CompileTimeAssemblies.RemoveAll(path => path.Path.StartsWith("lib/") && !referenceSet.References.Contains(Path.GetFileName(path), StringComparer.OrdinalIgnoreCase));
                }
            }

            return lockFileLib;
        }
        //Dataloss testing can be triggered via powershell. To do so, run the following commands as a script
        //Connect-ServiceFabricCluster
        //$s = "fabric:/WebReferenceApplication/InventoryService"
        //$p = Get-ServiceFabricApplication | Get-ServiceFabricService -ServiceName $s | Get-ServiceFabricPartition | Select -First 1
        //$p | Invoke-ServiceFabricPartitionDataLoss -DataLossMode FullDataLoss -ServiceName $s

        protected override async Task<bool> OnDataLossAsync(RestoreContext restoreCtx, CancellationToken cancellationToken)
        {
            ServiceEventSource.Current.ServiceMessage(this, "OnDataLoss Invoked!");
            this.SetupBackupManager();

            try
            {
                string backupFolder;

                if (this.backupStorageType == BackupManagerType.None)
                {
                    //since we have no backup configured, we return false to indicate
                    //that state has not changed. This replica will become the basis
                    //for future replica builds
                    return false;
                }
                else
                {
                    backupFolder = await this.backupManager.RestoreLatestBackupToTempLocation(cancellationToken);
                }

                ServiceEventSource.Current.ServiceMessage(this, "Restoration Folder Path " + backupFolder);

                RestoreDescription restoreRescription = new RestoreDescription(backupFolder, RestorePolicy.Force);

                await restoreCtx.RestoreAsync(restoreRescription, cancellationToken);

                ServiceEventSource.Current.ServiceMessage(this, "Restore completed");

                DirectoryInfo tempRestoreDirectory = new DirectoryInfo(backupFolder);
                tempRestoreDirectory.Delete(true);

                return true;
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(this, "Restoration failed: " + "{0} {1}" + e.GetType() + e.Message);

                throw;
            }
        }