internal override async Task <HttpResponseMessage> RunAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            string applicationNameUri;
            string serviceNameUri;
            string partitionId;
            var    fabricUri = await UtilityHelper.GetFabricUriFromRequstHeader(this._fabricRequestHeader, timeout, cancellationToken);

            FabricBackupResourceType fabricBackupResourceType = UtilityHelper.GetApplicationAndServicePartitionUri(fabricUri, out applicationNameUri, out serviceNameUri, out partitionId);
            var suspendStore = await SuspendStore.CreateOrGetSuspendStatusStore(this.StatefulService);

            var backupMappingList = await this.BackupMappingStore.GetAllProtectionForApplicationAndItsServiceAndPartition(applicationNameUri, timeout, cancellationToken);

            if (backupMappingList.Count == 0)
            {
                throw new FabricPeriodicBackupNotEnabledException();
            }

            WorkItem workItem = null;

            switch (fabricBackupResourceType)
            {
            case FabricBackupResourceType.ApplicationUri:
                workItem = new ResolveToPartitionWorkItem(FabricBackupResourceType.ApplicationUri, applicationNameUri, new WorkItemInfo {
                    WorkItemType = WorkItemPropogationType.SuspendPartition
                });
                break;

            case FabricBackupResourceType.ServiceUri:
                workItem = new ResolveToPartitionWorkItem(FabricBackupResourceType.ServiceUri, serviceNameUri, new WorkItemInfo {
                    WorkItemType = WorkItemPropogationType.SuspendPartition
                });
                break;

            case FabricBackupResourceType.PartitionUri:
                workItem = new SendToServiceNodeWorkItem(serviceNameUri, partitionId, new WorkItemInfo {
                    WorkItemType = WorkItemPropogationType.SuspendPartition
                });
                break;
            }

            if (fabricBackupResourceType == FabricBackupResourceType.Error || workItem == null)
            {
                throw new ArgumentException("Invalid argument");
            }

            using (var transaction = this.StatefulService.StateManager.CreateTransaction())
            {
                await suspendStore.AddOrUpdateAsync(fabricUri, fabricUri, (fabricUriKey, fabricUriValue) => fabricUriValue, timeout, cancellationToken, transaction);

                await this.WorkItemQueue.AddWorkItem(workItem, timeout, cancellationToken, transaction);

                await transaction.CommitAsync();
            }

            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
Exemple #2
0
        internal override async Task <BackupConfigurationInfo> RunAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            string applicationNameUri;
            string serviceNameUri;
            string partitionId;

            List <BackupEntityConfigurationInfo> backupConfigurationInfos = new List <BackupEntityConfigurationInfo>();
            var suspendStore = await SuspendStore.CreateOrGetSuspendStatusStore(this.StatefulService);

            var enablementKey = await UtilityHelper.GetFabricUriFromRequstHeader(this.fabricRequestHeader, timeout, cancellationToken);

            BRSContinuationToken brsContinuationToken = new BRSContinuationToken();

            brsContinuationToken.IncomingContinuationToken = continuationToken;
            var fabricBackupResourceType = UtilityHelper.GetApplicationAndServicePartitionUri(enablementKey, out applicationNameUri, out serviceNameUri, out partitionId);
            var backupMapping            = await this.BackupMappingStore.GetValueAsync(enablementKey, timeout, cancellationToken);

            int maxResultsForOverriddenPolicies = 0;

            if (maxResults != 0)
            {
                maxResultsForOverriddenPolicies = maxResults - 1;
            }
            switch (fabricBackupResourceType)
            {
            case FabricBackupResourceType.PartitionUri:

                PartitionBackupConfigurationInfo partitionBackupConfigurationInfo = null;
                BackupSuspensionInfo             backupSuspensionInfo             = new BackupSuspensionInfo();
                if (await suspendStore.IsFabrcUriSuspended(enablementKey, timeout, cancellationToken))
                {
                    backupSuspensionInfo.IsSuspended             = true;
                    backupSuspensionInfo.SuspensionInheritedFrom = BackupEntityKind.Partition;
                }
                else if (await suspendStore.IsFabrcUriSuspended(serviceNameUri, timeout, cancellationToken))
                {
                    backupSuspensionInfo.IsSuspended             = true;
                    backupSuspensionInfo.SuspensionInheritedFrom = BackupEntityKind.Service;
                }
                else if (await suspendStore.IsFabrcUriSuspended(applicationNameUri, timeout, cancellationToken))
                {
                    backupSuspensionInfo.IsSuspended             = true;
                    backupSuspensionInfo.SuspensionInheritedFrom = BackupEntityKind.Application;
                }
                if (backupMapping != null)
                {
                    partitionBackupConfigurationInfo = new PartitionBackupConfigurationInfo(serviceNameUri,
                                                                                            partitionId, backupMapping.BackupPolicyName, BackupEntityKind.Partition, backupSuspensionInfo
                                                                                            );
                }
                else
                {
                    var backupMappingInherited = await this.BackupMappingStore.GetValueAsync(serviceNameUri, timeout, cancellationToken);

                    if (backupMappingInherited != null)
                    {
                        partitionBackupConfigurationInfo = new PartitionBackupConfigurationInfo(serviceNameUri,
                                                                                                partitionId, backupMappingInherited.BackupPolicyName, BackupEntityKind.Service, backupSuspensionInfo
                                                                                                );
                    }
                    else
                    {
                        backupMappingInherited = await this.BackupMappingStore.GetValueAsync(applicationNameUri, timeout, cancellationToken);

                        if (backupMappingInherited != null)
                        {
                            partitionBackupConfigurationInfo = new PartitionBackupConfigurationInfo(serviceNameUri,
                                                                                                    partitionId, backupMappingInherited.BackupPolicyName, BackupEntityKind.Application, backupSuspensionInfo
                                                                                                    );
                        }
                    }
                }

                return(partitionBackupConfigurationInfo);

            case FabricBackupResourceType.ServiceUri:

                ServiceBackupConfigurationInfo serviceBackupConfigurationInfo = null;
                backupSuspensionInfo = new BackupSuspensionInfo();
                if (await suspendStore.IsFabrcUriSuspended(serviceNameUri, timeout, cancellationToken))
                {
                    backupSuspensionInfo.IsSuspended             = true;
                    backupSuspensionInfo.SuspensionInheritedFrom = BackupEntityKind.Service;
                }
                else if (await suspendStore.IsFabrcUriSuspended(applicationNameUri, timeout, cancellationToken))
                {
                    backupSuspensionInfo.IsSuspended             = true;
                    backupSuspensionInfo.SuspensionInheritedFrom = BackupEntityKind.Application;
                }
                if (backupMapping != null)
                {
                    serviceBackupConfigurationInfo = new ServiceBackupConfigurationInfo(serviceNameUri,
                                                                                        backupMapping.BackupPolicyName, BackupEntityKind.Service, backupSuspensionInfo);
                }
                else
                {
                    backupMapping = await this.BackupMappingStore.GetValueAsync(applicationNameUri, timeout, cancellationToken);

                    if (backupMapping != null)
                    {
                        serviceBackupConfigurationInfo = new ServiceBackupConfigurationInfo(serviceNameUri,
                                                                                            backupMapping.BackupPolicyName, BackupEntityKind.Application, backupSuspensionInfo);
                    }
                }

                if (serviceBackupConfigurationInfo != null && String.IsNullOrEmpty(brsContinuationToken.IncomingContinuationToken))
                {
                    backupConfigurationInfos.Add(serviceBackupConfigurationInfo);
                }


                if (maxResults == 1 && String.IsNullOrEmpty(brsContinuationToken.IncomingContinuationToken) && serviceBackupConfigurationInfo != null)
                {
                    // if maxResults is 1, then, we need to check if more elements are there or not.
                    List <string> suspendedPartitions = await
                                                        suspendStore.GetAllSuspensionWithFabricUri(serviceNameUri, timeout, cancellationToken, brsContinuationToken.IncomingContinuationToken);

                    var overridesBackupMappings = await this.BackupMappingStore.GetAllProtectionWithFabricUri(serviceNameUri,
                                                                                                              timeout, cancellationToken, brsContinuationToken.IncomingContinuationToken);

                    int countToCompare = 0;
                    if (backupSuspensionInfo.IsSuspended)
                    {
                        countToCompare = 1;
                    }
                    if (overridesBackupMappings.Count > 1 || suspendedPartitions.Count > countToCompare)
                    {
                        // overridesBackupMappings should be greater than 1 as it contains this mapping also or suspendedPartitions should have its count greater than zero.
                        brsContinuationToken.OutgoingContinuationToken = serviceNameUri + ContinuationTokenSeparatorChar + OverrideContinuationToken;
                    }
                }
                else
                {
                    backupConfigurationInfos.AddRange(
                        await this.GetOverriddenBackupConfigurationinfo(serviceNameUri, backupSuspensionInfo, timeout, cancellationToken, brsContinuationToken, maxResultsForOverriddenPolicies));
                }
                break;

            case FabricBackupResourceType.ApplicationUri:
                ApplicationBackupConfigurationInfo applicationBackupConfigurationInfo = null;
                backupSuspensionInfo = new BackupSuspensionInfo();

                if (await suspendStore.IsFabrcUriSuspended(applicationNameUri, timeout, cancellationToken))
                {
                    backupSuspensionInfo.IsSuspended             = true;
                    backupSuspensionInfo.SuspensionInheritedFrom = BackupEntityKind.Application;
                }
                if (backupMapping != null)
                {
                    applicationBackupConfigurationInfo = new ApplicationBackupConfigurationInfo(applicationNameUri,
                                                                                                backupMapping.BackupPolicyName, BackupEntityKind.Application, backupSuspensionInfo);
                }

                if (applicationBackupConfigurationInfo != null && String.IsNullOrEmpty(brsContinuationToken.IncomingContinuationToken))
                {
                    backupConfigurationInfos.Add(applicationBackupConfigurationInfo);
                }

                if (maxResults == 1 && String.IsNullOrEmpty(brsContinuationToken.IncomingContinuationToken) && applicationBackupConfigurationInfo != null)
                {
                    // if maxResults is 1, then, we need to check if more elements are there or not.
                    List <string> suspendedPartitions = await
                                                        suspendStore.GetAllSuspensionWithFabricUri(applicationNameUri, timeout, cancellationToken);

                    var overridesBackupMappings = await this.BackupMappingStore.GetAllProtectionWithFabricUri(applicationNameUri,
                                                                                                              timeout, cancellationToken, null);

                    int countToCompare = 0;
                    if (backupSuspensionInfo.IsSuspended)
                    {
                        countToCompare = 1;
                    }
                    if (overridesBackupMappings.Count > 1 || suspendedPartitions.Count > countToCompare)
                    {
                        // overridesBackupMappings is compared to 1 as 1st element will be same as this one.
                        brsContinuationToken.OutgoingContinuationToken = applicationNameUri + ContinuationTokenSeparatorChar + OverrideContinuationToken;
                    }
                }
                else
                {
                    backupConfigurationInfos.AddRange(
                        await this.GetOverriddenBackupConfigurationinfo(applicationNameUri, backupSuspensionInfo, timeout, cancellationToken, brsContinuationToken, maxResultsForOverriddenPolicies));
                }
                break;
            }

            if (backupConfigurationInfos.Count == 0)
            {
                throw new FabricException(StringResources.BackupMappingNotExisting, FabricErrorCode.BackupNotEnabled);
            }
            return(new PagedBackupConfigurationInfo()
            {
                Items = backupConfigurationInfos,
                ContinuationToken = brsContinuationToken.OutgoingContinuationToken
            });
        }
        internal override async Task <HttpResponseMessage> RunAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(this.backupPolicyName))
            {
                throw new ArgumentException(StringResources.InvalidArguments);
            }
            var backupPolicy = await this.BackupPolicyStore.GetValueAsync(this.backupPolicyName);

            BackupMappingStore backupMappingStore = await
                                                    BackupMappingStore.CreateOrGetBackupMappingStore(this.StatefulService);

            SuspendStore suspendStore = await SuspendStore.CreateOrGetSuspendStatusStore(this.StatefulService);

            List <string> allSuspensions = await suspendStore.GetAllSuspensions(timeout, cancellationToken);

            if (backupPolicy != null && backupPolicy.BackupEnabledSet.Count > 0)
            {
                HashSet <string> backupEnables = new HashSet <string>(backupPolicy.BackupEnabledSet);
                foreach (var backupEnable in backupEnables)
                {
                    if (!await this.IsFabricEntityExisting(backupEnable, timeout, cancellationToken))
                    {
                        using (ITransaction transaction = this.StatefulService.StateManager.CreateTransaction())
                        {
                            var currentBackupPolicy =
                                await
                                this.BackupPolicyStore.GetValueWithUpdateLockModeAsync(this.backupPolicyName, timeout,
                                                                                       cancellationToken,
                                                                                       transaction);

                            var updatedBackupPolicy = currentBackupPolicy.ToBuilder()
                                                      .RemoveFromBackupEnabledSet(backupEnable)
                                                      .Build();

                            await
                            this.BackupPolicyStore.RemoveProtectionEntity(updatedBackupPolicy, backupEnable,
                                                                          timeout,
                                                                          cancellationToken, transaction);

                            await backupMappingStore.DeleteValueAsync(backupEnable, timeout, cancellationToken);

                            await transaction.CommitAsync();
                        }
                    }
                }
            }

            RetentionManager retentionManager = await RetentionManager.CreateOrGetRetentionManager(this.StatefulService);

            using (var transaction = this.StatefulService.StateManager.CreateTransaction())
            {
                foreach (string suspension in allSuspensions)
                {
                    string applicationNameUri = null;
                    string serviceNameUri     = null;
                    string partitionId        = null;
                    FabricBackupResourceType fabricBackupResourceType =
                        UtilityHelper.GetApplicationAndServicePartitionUri(suspension, out applicationNameUri, out serviceNameUri, out partitionId);

                    BackupMapping backupMapping = null;
                    switch (fabricBackupResourceType)
                    {
                    case FabricBackupResourceType.PartitionUri:
                        backupMapping =
                            await backupMappingStore.GetValueAsync(UtilityHelper.GetBackupMappingKey(serviceNameUri, partitionId),
                                                                   timeout, cancellationToken, transaction) ??
                            await backupMappingStore.GetValueAsync(serviceNameUri, timeout, cancellationToken, transaction) ??
                            await backupMappingStore.GetValueAsync(applicationNameUri, timeout, cancellationToken, transaction);

                        break;

                    case FabricBackupResourceType.ServiceUri:
                        backupMapping =
                            await backupMappingStore.GetValueAsync(serviceNameUri, timeout, cancellationToken, transaction) ??
                            await backupMappingStore.GetValueAsync(applicationNameUri, timeout, cancellationToken, transaction);

                        break;

                    case FabricBackupResourceType.ApplicationUri:
                        backupMapping =
                            await backupMappingStore.GetValueAsync(applicationNameUri, timeout, cancellationToken, transaction);

                        break;
                    }

                    if (backupMapping != null && this.backupPolicyName.Equals(backupMapping.BackupPolicyName))
                    {
                        await suspendStore.DeleteValueAsync(suspension, timeout, cancellationToken, transaction);
                    }
                }

                await this.BackupPolicyStore.DeleteValueAsync(this.backupPolicyName, timeout, cancellationToken, transaction);

                await retentionManager.DeletePolicyAsync(this.backupPolicyName, timeout, cancellationToken, transaction);

                await transaction.CommitAsync();
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Exemple #4
0
        private async Task <List <BackupEntityConfigurationInfo> > GetOverriddenBackupConfigurationinfo(string applicationServiceNameUri,
                                                                                                        BackupSuspensionInfo inheritedBackupSuspensionInfo, TimeSpan timeout, CancellationToken cancellationToken, BRSContinuationToken brsContinuationToken, int maxResultsLocal = 0)
        {
            List <BackupEntityConfigurationInfo> backupConfigurationInfos = new List <BackupEntityConfigurationInfo>();

            bool listSuspended = false;

            if (!String.IsNullOrEmpty(brsContinuationToken.IncomingContinuationToken))
            {
                string[] array = brsContinuationToken.IncomingContinuationToken.Split(ContinuationTokenSeparatorChar);
                brsContinuationToken.IncomingContinuationToken = array[0];
                if (array[1] == SuspendedContinuationToken)
                {
                    // We need to check if we were listing suspended partitions previously or override.
                    listSuspended = true;
                }
            }
            string continuationTokenForSuspendendPartitions = null;

            if (listSuspended)
            {
                // if we were listing overrides, then this continuationTokenForSuspendendPartitions should be null.
                continuationTokenForSuspendendPartitions = brsContinuationToken.IncomingContinuationToken;
            }

            var suspendStore = await SuspendStore.CreateOrGetSuspendStatusStore(this.StatefulService);

            List <string> suspendedEntities = await
                                              suspendStore.GetAllSuspensionWithFabricUri(applicationServiceNameUri, timeout, cancellationToken, continuationTokenForSuspendendPartitions);

            HashSet <string> suspendedEntitiesHashSet = new HashSet <string>(suspendedEntities);
            var overridesBackupMappings = await this.BackupMappingStore.GetAllProtectionWithFabricUri(applicationServiceNameUri,
                                                                                                      timeout, cancellationToken, brsContinuationToken.IncomingContinuationToken);

            string applicationNameUri = null;
            string serviceNameUri     = null;
            string partitionId        = null;
            int    counter            = 0;

            if (maxResultsLocal != 0)
            {
                // if maxResults is equal to zero, then we dont need to sort as we have already filtered the elements.
                overridesBackupMappings = overridesBackupMappings.OrderBy(backupMapping => backupMapping.ApplicationOrServiceUri).ToList();
            }
            foreach (var overridesBackupMapping in overridesBackupMappings)
            {
                if (!applicationServiceNameUri.Equals(overridesBackupMapping.ApplicationOrServiceUri))
                {
                    BackupEntityConfigurationInfo backupConfigurationInfo  = null;
                    FabricBackupResourceType      fabricBackupResourceType = UtilityHelper
                                                                             .GetApplicationAndServicePartitionUri(
                        overridesBackupMapping.ApplicationOrServiceUri, out applicationNameUri, out serviceNameUri,
                        out partitionId);
                    BackupSuspensionInfo backupSuspensionInfo = inheritedBackupSuspensionInfo;
                    switch (fabricBackupResourceType)
                    {
                    case FabricBackupResourceType.PartitionUri:
                        if (suspendedEntitiesHashSet.Contains(overridesBackupMapping.ApplicationOrServiceUri))
                        {
                            backupSuspensionInfo = new BackupSuspensionInfo(BackupEntityKind.Partition, true);
                            suspendedEntitiesHashSet.Remove(overridesBackupMapping.ApplicationOrServiceUri);
                        }
                        if (listSuspended)
                        {
                            continue;
                        }
                        backupConfigurationInfo = new PartitionBackupConfigurationInfo(serviceNameUri,
                                                                                       partitionId, overridesBackupMapping.BackupPolicyName, BackupEntityKind.Partition, backupSuspensionInfo);

                        break;

                    case FabricBackupResourceType.ServiceUri:
                        if (suspendedEntitiesHashSet.Contains(overridesBackupMapping.ApplicationOrServiceUri))
                        {
                            backupSuspensionInfo = new BackupSuspensionInfo(BackupEntityKind.Service, true);
                            suspendedEntitiesHashSet.Remove(overridesBackupMapping.ApplicationOrServiceUri);
                        }
                        if (listSuspended)
                        {
                            continue;
                        }
                        backupConfigurationInfo = new ServiceBackupConfigurationInfo(serviceNameUri,
                                                                                     overridesBackupMapping.BackupPolicyName, BackupEntityKind.Service, backupSuspensionInfo);
                        break;

                    case FabricBackupResourceType.ApplicationUri:
                        if (suspendedEntitiesHashSet.Contains(overridesBackupMapping.ApplicationOrServiceUri))
                        {
                            backupSuspensionInfo = new BackupSuspensionInfo(BackupEntityKind.Application, true);
                            suspendedEntitiesHashSet.Remove(overridesBackupMapping.ApplicationOrServiceUri);
                        }
                        if (listSuspended)
                        {
                            continue;
                        }
                        backupConfigurationInfo = new ApplicationBackupConfigurationInfo(applicationNameUri,
                                                                                         overridesBackupMapping.BackupPolicyName, BackupEntityKind.Application, backupSuspensionInfo);
                        break;
                    }
                    if (backupConfigurationInfo != null)
                    {
                        backupConfigurationInfos.Add(backupConfigurationInfo);
                        counter++;
                        if (maxResultsLocal != 0 && counter == maxResultsLocal)
                        {
                            if (counter < overridesBackupMappings.Count || suspendedEntitiesHashSet.Count > 0)
                            {
                                // we need to check if there are more elements to be listed or not.
                                brsContinuationToken.OutgoingContinuationToken = overridesBackupMapping.ApplicationOrServiceUri + ContinuationTokenSeparatorChar + OverrideContinuationToken;
                            }
                            return(backupConfigurationInfos);
                        }
                    }
                }
            }

            suspendedEntitiesHashSet.Remove(applicationServiceNameUri);

            foreach (var leftSuspendUri in suspendedEntitiesHashSet)
            {
                if (maxResultsLocal != 0)
                {
                    // if maxResults is equal to zero, then we dont need to sort as we have already filtered the elements.
                    suspendedEntitiesHashSet.ToList().Sort();
                }
                FabricBackupResourceType leftSuspendUriType =
                    UtilityHelper
                    .GetApplicationAndServicePartitionUri(
                        leftSuspendUri, out applicationNameUri, out serviceNameUri,
                        out partitionId);
                BackupEntityConfigurationInfo backupConfigurationInfo = null;
                BackupMappingModel            backupMapping           = null;
                BackupEntityKind backupEntityKind = BackupEntityKind.Invalid;

                switch (leftSuspendUriType)
                {
                case FabricBackupResourceType.PartitionUri:
                    backupMapping = await this.BackupMappingStore.GetValueAsync(serviceNameUri);

                    backupEntityKind = backupMapping != null ? BackupEntityKind.Service : BackupEntityKind.Invalid;
                    backupMapping    = await this.BackupMappingStore.GetValueAsync(applicationNameUri);

                    backupEntityKind = backupMapping != null ? BackupEntityKind.Application : BackupEntityKind.Invalid;

                    backupConfigurationInfo = new PartitionBackupConfigurationInfo(serviceNameUri,
                                                                                   partitionId, backupMapping.BackupPolicyName, backupEntityKind,
                                                                                   new BackupSuspensionInfo(BackupEntityKind.Partition, true));
                    break;

                case FabricBackupResourceType.ServiceUri:
                    backupMapping = await this.BackupMappingStore.GetValueAsync(applicationNameUri);

                    backupEntityKind = backupMapping != null ? BackupEntityKind.Application : BackupEntityKind.Invalid;

                    backupConfigurationInfo = new ServiceBackupConfigurationInfo(serviceNameUri,
                                                                                 backupMapping.BackupPolicyName, backupEntityKind,
                                                                                 new BackupSuspensionInfo(BackupEntityKind.Service, true));
                    break;

                case FabricBackupResourceType.ApplicationUri:
                    backupMapping = await this.BackupMappingStore.GetValueAsync(applicationNameUri);

                    backupEntityKind = backupMapping != null ? BackupEntityKind.Application : BackupEntityKind.Invalid;

                    backupConfigurationInfo = new ApplicationBackupConfigurationInfo(applicationNameUri,
                                                                                     backupMapping.BackupPolicyName, backupEntityKind,
                                                                                     new BackupSuspensionInfo(BackupEntityKind.Application, true));
                    break;
                }

                if (backupMapping != null && backupEntityKind != BackupEntityKind.Invalid)
                {
                    backupConfigurationInfos.Add(backupConfigurationInfo);
                    counter++;
                    if (maxResultsLocal != 0 && counter == maxResultsLocal)
                    {
                        if (counter < suspendedEntitiesHashSet.Count)
                        {
                            // we need to check if there are more elements to be listed or not.
                            brsContinuationToken.OutgoingContinuationToken = leftSuspendUri + ContinuationTokenSeparatorChar + SuspendedContinuationToken;
                        }
                        break;
                    }
                }
            }
            return(backupConfigurationInfos);
        }
Exemple #5
0
    public async Task <BackupPolicy> GetBackupSchedulingPolicyAsync(BackupPartitionInfo backupPartitionInfo,
                                                                    TimeSpan timeout,
                                                                    CancellationToken cancellationToken)
    {
        BackupPolicy backupPolicy;

        BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "{0} GetBackupPolicy invoked", backupPartitionInfo.PartitionId);

        var backupMappingStore = await BackupMappingStore.CreateOrGetBackupMappingStore(this.statefulService);

        var backupPolicyStore = await BackupPolicyStore.CreateOrGetBackupPolicyStore(this.statefulService);

        var suspendStore = await SuspendStore.CreateOrGetSuspendStatusStore(this.statefulService);

        var serviceNameUri = await UtilityHelper.GetCustomServiceUri(backupPartitionInfo.ServiceName, timeout, cancellationToken);

        var backupMappingKey = UtilityHelper.GetBackupMappingKey(serviceNameUri, backupPartitionInfo.PartitionId.ToString());

        var backupMappingModel = (await backupMappingStore.GetValueAsync(backupMappingKey) ??
                                  await backupMappingStore.GetValueAsync(serviceNameUri)) ??
                                 await backupMappingStore.GetValueAsync(UtilityHelper.GetApplicationNameFromService(serviceNameUri));

        bool isPartitionSuspended = await suspendStore.GetValueAsync(backupMappingKey) != null;

        if (backupMappingModel == null || isPartitionSuspended)
        {
            BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "{0} Backup protection not enabled", backupPartitionInfo.PartitionId);
            throw new FabricPeriodicBackupNotEnabledException();
        }

        var backupPolicyName  = backupMappingModel.BackupPolicyName;
        var backupPolicyModel = await backupPolicyStore.GetValueAsync(backupPolicyName);

        switch (backupPolicyModel.BackupSchedule.BackupScheduleType)
        {
        case BackupScheduleType.FrequencyBased:
            backupPolicy = new FrequencyBasedBackupPolicy();
            var frequencyBasedSchedulePolicy = (System.Fabric.BackupRestore.Common.Model.FrequencyBasedBackupSchedule)backupPolicyModel.BackupSchedule;
            backupPolicy.PolicyType = BackupPolicyType.FrequencyBased;
            var freqBackupPolicy = (FrequencyBasedBackupPolicy)backupPolicy;

            freqBackupPolicy.RunFrequency = (ushort)frequencyBasedSchedulePolicy.Interval;

            if (frequencyBasedSchedulePolicy.IntervalType == BackupScheduleInterval.Hours)
            {
                freqBackupPolicy.RunFrequencyType = BackupPolicyRunFrequency.Hours;
            }

            if (frequencyBasedSchedulePolicy.IntervalType == BackupScheduleInterval.Minutes)
            {
                freqBackupPolicy.RunFrequencyType = BackupPolicyRunFrequency.Minutes;
            }

            break;

        case BackupScheduleType.TimeBased:
            backupPolicy = new ScheduleBasedBackupPolicy();
            var scheduleBasedSchedulePolicy = (System.Fabric.BackupRestore.Common.Model.TimeBasedBackupSchedule)backupPolicyModel.BackupSchedule;
            backupPolicy.PolicyType = BackupPolicyType.ScheduleBased;

            var schdBackupPolicy = (ScheduleBasedBackupPolicy)backupPolicy;
            if (scheduleBasedSchedulePolicy.ScheduleFrequencyType == BackupScheduleFrequency.Daily)
            {
                schdBackupPolicy.RunSchedule = BackupPolicyRunSchedule.Daily;
            }

            if (scheduleBasedSchedulePolicy.ScheduleFrequencyType == BackupScheduleFrequency.Weekly)
            {
                schdBackupPolicy.RunSchedule = BackupPolicyRunSchedule.Weekly;
            }

            schdBackupPolicy.RunDays  = new List <DayOfWeek>(scheduleBasedSchedulePolicy.RunDays);
            schdBackupPolicy.RunTimes = new List <TimeSpan>(scheduleBasedSchedulePolicy.RunTimes);

            break;

        default:
            throw new FabricPeriodicBackupNotEnabledException();
        }

        backupPolicy.MaxIncrementalBackups = Convert.ToByte(backupPolicyModel.MaxIncrementalBackup);
        backupPolicy.Name     = backupPolicyModel.Name;
        backupPolicy.PolicyId = backupPolicyModel.UniqueId;

        switch (backupPolicyModel.Storage.BackupStorageType)
        {
        case BackupStorageType.FileShare:
            var fileShareStorage = (System.Fabric.BackupRestore.Common.Model.FileShareBackupStorageInfo)backupPolicyModel.Storage;
            backupPolicy.StoreInformation = new FileShareBackupStore
            {
                AccessType          = String.IsNullOrEmpty(fileShareStorage.PrimaryUserName) ? FileShareAccessType.None : FileShareAccessType.DomainUser,
                FileSharePath       = Path.Combine(fileShareStorage.Path, UtilityHelper.GetBaseDirectoryPathForPartition(serviceNameUri, backupPartitionInfo.PartitionId.ToString())),
                PrimaryUserName     = fileShareStorage.PrimaryUserName,
                PrimaryPassword     = fileShareStorage.PrimaryPassword,
                SecondaryUserName   = fileShareStorage.SecondaryUserName,
                SecondaryPassword   = fileShareStorage.SecondaryPassword,
                IsPasswordEncrypted = fileShareStorage.IsPasswordEncrypted,
            };
            break;

        case BackupStorageType.AzureBlobStore:
            var azureStorage = (System.Fabric.BackupRestore.Common.Model.AzureBlobBackupStorageInfo)backupPolicyModel.Storage;
            backupPolicy.StoreInformation = new AzureBlobBackupStore
            {
                ConnectionString      = azureStorage.ConnectionString,
                ContainerName         = azureStorage.ContainerName,
                FolderPath            = UtilityHelper.GetBaseDirectoryPathForPartition(serviceNameUri, backupPartitionInfo.PartitionId.ToString()),
                IsAccountKeyEncrypted = azureStorage.IsConnectionStringEncrypted,
            };
            break;

        case BackupStorageType.DsmsAzureBlobStore:
            var dsmsAzureStorage = (System.Fabric.BackupRestore.Common.Model.DsmsAzureBlobBackupStorageInfo)backupPolicyModel.Storage;
            backupPolicy.StoreInformation = new DsmsAzureBlobBackupStore
            {
                StorageCredentialsSourceLocation = dsmsAzureStorage.StorageCredentialsSourceLocation,
                ContainerName = dsmsAzureStorage.ContainerName,
                FolderPath    = UtilityHelper.GetBaseDirectoryPathForPartition(serviceNameUri, backupPartitionInfo.PartitionId.ToString()),
            };
            break;
        }

        return(backupPolicy);
    }