예제 #1
0
        private RestAzureNS.AzureOperationResponse <ProtectedItemResource> EnableOrModifyProtection(bool disableWithRetentionData = false)
        {
            string vaultName = (string)ProviderData[VaultParams.VaultName];
            string vaultResourceGroupName = (string)ProviderData[VaultParams.ResourceGroupName];

            PolicyBase policy = ProviderData.ContainsKey(ItemParams.Policy) ?
                                (PolicyBase)ProviderData[ItemParams.Policy] : null;

            ProtectableItemBase protectableItemBase = ProviderData.ContainsKey(ItemParams.ProtectableItem) ?
                                                      (ProtectableItemBase)ProviderData[ItemParams.ProtectableItem] : null;
            AzureWorkloadProtectableItem protectableItem = ProviderData.ContainsKey(ItemParams.ProtectableItem) ?
                                                           (AzureWorkloadProtectableItem)ProviderData[ItemParams.ProtectableItem] : null;

            ItemBase itemBase = ProviderData.ContainsKey(ItemParams.Item) ?
                                (ItemBase)ProviderData[ItemParams.Item] : null;
            AzureWorkloadSQLDatabaseProtectedItem item = ProviderData.ContainsKey(ItemParams.Item) ?
                                                         (AzureWorkloadSQLDatabaseProtectedItem)ProviderData[ItemParams.Item] : null;

            AzureVmWorkloadSQLDatabaseProtectedItem properties = new AzureVmWorkloadSQLDatabaseProtectedItem();
            string containerUri     = "";
            string protectedItemUri = "";

            if (disableWithRetentionData)
            {
                //Disable protection while retaining backup data
                ValidateAzureWorkloadDisableProtectionRequest(itemBase);

                Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(item.Id);
                containerUri                = HelperUtils.GetContainerUri(keyValueDict, item.Id);
                protectedItemUri            = HelperUtils.GetProtectedItemUri(keyValueDict, item.Id);
                properties.PolicyId         = string.Empty;
                properties.ProtectionState  = ProtectionState.ProtectionStopped;
                properties.SourceResourceId = item.SourceResourceId;
            }
            else
            {
                if (protectableItem != null)
                {
                    Dictionary <UriEnums, string> keyValueDict =
                        HelperUtils.ParseUri(protectableItem.Id);
                    containerUri = HelperUtils.GetContainerUri(
                        keyValueDict, protectableItem.Id);
                    protectedItemUri = HelperUtils.GetProtectableItemUri(
                        keyValueDict, protectableItem.Id);

                    properties.PolicyId = policy.Id;
                }
                else if (item != null)
                {
                    Dictionary <UriEnums, string> keyValueDict =
                        HelperUtils.ParseUri(item.Id);
                    containerUri = HelperUtils.GetContainerUri(
                        keyValueDict, item.Id);
                    protectedItemUri = HelperUtils.GetProtectedItemUri(
                        keyValueDict, item.Id);

                    properties.PolicyId = policy.Id;
                }
            }

            ProtectedItemResource serviceClientRequest = new ProtectedItemResource()
            {
                Properties = properties
            };

            return(ServiceClientAdapter.CreateOrUpdateProtectedItem(
                       containerUri,
                       protectedItemUri,
                       serviceClientRequest,
                       vaultName: vaultName,
                       resourceGroupName: vaultResourceGroupName));
        }
예제 #2
0
        /// <summary>
        /// Lists protected items protected by the recovery services vault according to the provider data
        /// </summary>
        /// <returns>List of protected items</returns>
        public List <ItemBase> ListProtectedItems()
        {
            ContainerBase        container        = (ContainerBase)ProviderData[ItemParams.Container];
            string               name             = (string)ProviderData[ItemParams.AzureVMName];
            ItemProtectionStatus protectionStatus =
                (ItemProtectionStatus)ProviderData[ItemParams.ProtectionStatus];
            ItemProtectionState status =
                (ItemProtectionState)ProviderData[ItemParams.ProtectionState];

            CmdletModel.WorkloadType workloadType =
                (CmdletModel.WorkloadType)ProviderData[ItemParams.WorkloadType];

            ODataQuery <ProtectedItemQueryObject> queryParams =
                new ODataQuery <ProtectedItemQueryObject>(
                    q => q.BackupManagementType
                    == ServiceClientModel.BackupManagementType.AzureSql &&
                    q.ItemType == DataSourceType.AzureSqlDb);

            List <ProtectedItemResource> protectedItems = new List <ProtectedItemResource>();
            string skipToken    = null;
            var    listResponse = ServiceClientAdapter.ListProtectedItem(queryParams, skipToken);

            protectedItems.AddRange(listResponse);


            // 1. Filter by container
            if (container != null)
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <UriEnums, string> dictionary =
                        HelperUtils.ParseUri(protectedItem.Id);
                    string containerUri =
                        HelperUtils.GetContainerUri(dictionary, protectedItem.Id);
                    return(containerUri.Contains(container.Name));
                }).ToList();
            }

            List <ProtectedItemResource> protectedItemGetResponses =
                new List <ProtectedItemResource>();

            // 2. Filter by item's friendly name
            if (!string.IsNullOrEmpty(name))
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <UriEnums, string> dictionary =
                        HelperUtils.ParseUri(protectedItem.Id);
                    string protectedItemUri =
                        HelperUtils.GetProtectedItemUri(dictionary, protectedItem.Id);
                    return(protectedItemUri.ToLower().Contains(name.ToLower()));
                }).ToList();

                ODataQuery <GetProtectedItemQueryObject> getItemQueryParams =
                    new ODataQuery <GetProtectedItemQueryObject>(q => q.Expand == extendedInfo);

                for (int i = 0; i < protectedItems.Count; i++)
                {
                    Dictionary <UriEnums, string> dictionary =
                        HelperUtils.ParseUri(protectedItems[i].Id);
                    string containerUri =
                        HelperUtils.GetContainerUri(dictionary, protectedItems[i].Id);
                    string protectedItemUri =
                        HelperUtils.GetProtectedItemUri(dictionary, protectedItems[i].Id);

                    var getResponse = ServiceClientAdapter.GetProtectedItem(
                        containerUri, protectedItemUri, getItemQueryParams);
                    protectedItemGetResponses.Add(getResponse.Body);
                }
            }

            List <ItemBase> itemModels = ConversionHelpers.GetItemModelList(protectedItems);

            if (!string.IsNullOrEmpty(name))
            {
                for (int i = 0; i < itemModels.Count; i++)
                {
                    AzureSqlProtectedItem azureSqlProtectedItem =
                        (AzureSqlProtectedItem)protectedItemGetResponses[i].Properties;
                    AzureSqlItemExtendedInfo extendedInfo = new AzureSqlItemExtendedInfo();
                    var hydraExtendedInfo = azureSqlProtectedItem.ExtendedInfo;
                    if (hydraExtendedInfo.OldestRecoveryPoint.HasValue)
                    {
                        extendedInfo.OldestRecoveryPoint = hydraExtendedInfo.OldestRecoveryPoint;
                    }
                    extendedInfo.PolicyState                   = hydraExtendedInfo.PolicyState;
                    extendedInfo.RecoveryPointCount            = hydraExtendedInfo.RecoveryPointCount;
                    ((AzureSqlItem)itemModels[i]).ExtendedInfo = extendedInfo;
                }
            }

            // 3. Filter by item's Protection Status
            if (protectionStatus != 0)
            {
                throw new Exception(
                          string.Format(
                              Resources.ProtectionStatusNotAllowedForAzureSqlItem,
                              protectionStatus.ToString()));
            }

            // 4. Filter by item's Protection State
            if (status != 0)
            {
                if (status != ItemProtectionState.Protected)
                {
                    throw new Exception(
                              string.Format(
                                  Resources.ProtectionStateInvalidForAzureSqlItem,
                                  status.ToString()));
                }

                itemModels = itemModels.Where(itemModel =>
                {
                    return(((AzureSqlItem)itemModel).ProtectionState == status.ToString());
                }).ToList();
            }

            // 5. Filter by workload type
            if (workloadType != 0)
            {
                itemModels = itemModels.Where(itemModel =>
                {
                    return(itemModel.WorkloadType == workloadType);
                }).ToList();
            }

            return(itemModels);
        }
예제 #3
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                // fetch source vault and target vault subscription
                Dictionary <CmdletModel.UriEnums, string> SourceVaultDict = HelperUtils.ParseUri(SourceVault.ID);
                string sourceSub = SourceVaultDict[CmdletModel.UriEnums.Subscriptions];

                Dictionary <CmdletModel.UriEnums, string> TargetVaultDict = HelperUtils.ParseUri(TargetVault.ID);
                string targetSub = TargetVaultDict[CmdletModel.UriEnums.Subscriptions];

                // change subscription for HTTP requests
                string subscriptionContext = ServiceClientAdapter.BmsAdapter.Client.SubscriptionId;
                ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = targetSub;

                // Check if the Target vault is empty
                /// Check the containers count in target vault
                var protectionContainersCount = BackupUtils.GetProtectionContainersCount(TargetVault.Name, TargetVault.ResourceGroupName, ServiceClientAdapter);

                Logger.Instance.WriteDebug("Protection Containers within vault: " + TargetVault.Name + " and resource Group: "
                                           + TargetVault.ResourceGroupName + " are " + protectionContainersCount);

                if (protectionContainersCount > 0)
                {
                    throw new ArgumentException(string.Format(Resources.TargetVaultNotEmptyException));
                }

                /// check the count for VM backupItems
                int vmItemsCount = BackupUtils.GetProtectedItems(TargetVault.Name, TargetVault.ResourceGroupName,
                                                                 BackupManagementType.AzureIaasVM, WorkloadType.VM, ServiceClientAdapter).Count;

                Logger.Instance.WriteDebug("Protected VMs within vault: " + TargetVault.Name + " and resource Group: "
                                           + TargetVault.ResourceGroupName + " are " + vmItemsCount);

                if (vmItemsCount > 0)
                {
                    throw new ArgumentException(string.Format(Resources.TargetVaultNotEmptyException));
                }

                // Confirm the target vault storage type
                BackupResourceConfigResource getStorageResponse = ServiceClientAdapter.GetVaultStorageType(
                    TargetVault.ResourceGroupName, TargetVault.Name);

                Logger.Instance.WriteDebug("Storage Type: " + getStorageResponse.Properties.StorageType);

                string correlationId = "";
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Resources.TargetVaultStorageRedundancy, TargetVault.Name, getStorageResponse.Properties.StorageType),
                    Resources.TargetVaultStorageRedundancy,
                    getStorageResponse.Properties.StorageType, () =>
                {
                    base.ExecuteCmdlet();

                    if (string.Compare(ParameterSetName, AzureRSVaultDataMoveParameterSet) == 0)
                    {
                        // Prepare Data Move
                        ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = sourceSub;
                        PrepareDataMoveRequest prepareMoveRequest             = new PrepareDataMoveRequest();
                        prepareMoveRequest.TargetResourceId = TargetVault.ID;
                        prepareMoveRequest.TargetRegion     = TargetVault.Location;

                        /// currently only allowing vault level data move
                        prepareMoveRequest.DataMoveLevel = "Vault";

                        if (RetryOnlyFailed.IsPresent)
                        {
                            prepareMoveRequest.IgnoreMoved = true;
                        }
                        else
                        {
                            prepareMoveRequest.IgnoreMoved = false;
                        }

                        Logger.Instance.WriteDebug("Retry only with failed items : " + prepareMoveRequest.IgnoreMoved);
                        Logger.Instance.WriteDebug("Location of Target vault: " + TargetVault.Location);

                        correlationId = ServiceClientAdapter.PrepareDataMove(SourceVault.Name, SourceVault.ResourceGroupName, prepareMoveRequest);
                    }
                    else
                    {
                        correlationId = CorrelationIdForDataMove;
                    }

                    // Trigger Data Move
                    ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = targetSub;
                    TriggerDataMoveRequest triggerMoveRequest             = new TriggerDataMoveRequest();
                    triggerMoveRequest.SourceResourceId = SourceVault.ID;
                    triggerMoveRequest.SourceRegion     = SourceVault.Location;

                    /// currently only allowing vault level data move
                    triggerMoveRequest.DataMoveLevel = "Vault";
                    triggerMoveRequest.CorrelationId = correlationId;
                    triggerMoveRequest.PauseGC       = false;

                    Logger.Instance.WriteDebug("Location of Source vault: " + SourceVault.Location);
                    ServiceClientAdapter.TriggerDataMove(TargetVault.Name, TargetVault.ResourceGroupName, triggerMoveRequest);

                    // set subscription to original
                    ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = subscriptionContext;

                    WriteObject(ParamHelpMsgs.DSMove.CmdletOutput);
                }
                    );
            }, ShouldProcess(TargetVault.Name, VerbsCommon.Set));
        }
예제 #4
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName         = resourceIdentifier.ResourceName;
                string resourceGroupName = resourceIdentifier.ResourceGroupName;

                if (!OriginalWorkloadRestore.IsPresent && !AlternateWorkloadRestore.IsPresent)
                {
                    throw new ArgumentException(string.Format(Resources.AzureWorkloadRestoreLocationException));
                }

                AzureWorkloadRecoveryConfig azureWorkloadRecoveryConfig = new AzureWorkloadRecoveryConfig();
                azureWorkloadRecoveryConfig.SourceResourceId            = Item != null ? Item.SourceResourceId : GetResourceId();
                DateTime currentTime = DateTime.Now;
                TimeSpan timeSpan    = DateTime.UtcNow - new DateTime(1970, 1, 1);
                int offset           = (int)timeSpan.TotalSeconds;
                string targetServer  = "";
                string parentName    = "";
                string targetDb      = "";
                if (ParameterSetName == RpParameterSet)
                {
                    azureWorkloadRecoveryConfig.RecoveryPoint  = RecoveryPoint;
                    Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(RecoveryPoint.Id);
                    string containerUri = HelperUtils.GetContainerUri(keyValueDict, RecoveryPoint.Id);
                    try
                    {
                        targetServer = containerUri.Split(new string[] { ";" }, StringSplitOptions.None)[3];
                    }
                    catch
                    {
                        targetServer = containerUri.Split(new string[] { ";" }, StringSplitOptions.None)[1];
                    }
                    string itemUri = HelperUtils.GetProtectedItemUri(keyValueDict, RecoveryPoint.Id);
                    parentName     = itemUri.Split(new string[] { ";" }, StringSplitOptions.None)[1];
                    targetDb       = itemUri.Split(new string[] { ";" }, StringSplitOptions.None)[2];
                }
                else
                {
                    azureWorkloadRecoveryConfig.PointInTime = PointInTime;
                }
                if (OriginalWorkloadRestore.IsPresent)
                {
                    azureWorkloadRecoveryConfig.RestoreRequestType = "Original WL Restore";
                    azureWorkloadRecoveryConfig.TargetServer       = Item != null ?
                                                                     ((AzureWorkloadSQLDatabaseProtectedItem)Item).ServerName : targetServer;
                    azureWorkloadRecoveryConfig.TargetInstance = Item != null ?
                                                                 ((AzureWorkloadSQLDatabaseProtectedItem)Item).ParentName : parentName;
                    azureWorkloadRecoveryConfig.RestoredDBName = Item != null ?
                                                                 ((AzureWorkloadSQLDatabaseProtectedItem)Item).FriendlyName : targetDb;
                    azureWorkloadRecoveryConfig.OverwriteWLIfpresent = "No";
                    azureWorkloadRecoveryConfig.NoRecoveryMode       = "Disabled";
                    if (RecoveryPoint == null)
                    {
                        Models.AzureWorkloadRecoveryPoint azureWorkloadRecoveryPoint = new Models.AzureWorkloadRecoveryPoint()
                        {
                            Id = Item.Id + "/recoveryPoints/DefaultRangeRecoveryPoint",
                            RecoveryPointId = "DefaultRangeRecoveryPoint"
                        };
                        azureWorkloadRecoveryConfig.RecoveryPoint = azureWorkloadRecoveryPoint;
                    }
                    azureWorkloadRecoveryConfig.ContainerId = Item != null ?
                                                              GetContainerId(Item.Id) : GetContainerId(GetItemId(RecoveryPoint.Id));
                }
                else if (AlternateWorkloadRestore.IsPresent && Item == null)
                {
                    if (string.Compare(((AzureWorkloadProtectableItem)TargetItem).ProtectableItemType,
                                       ProtectableItemType.SQLInstance.ToString()) != 0)
                    {
                        throw new ArgumentException(string.Format(Resources.AzureWorkloadRestoreProtectableItemException));
                    }

                    azureWorkloadRecoveryConfig.RestoreRequestType = "Alternate WL Restore";
                    azureWorkloadRecoveryConfig.TargetServer       = ((AzureWorkloadProtectableItem)TargetItem).ServerName;
                    azureWorkloadRecoveryConfig.TargetInstance     = ((AzureWorkloadProtectableItem)TargetItem).ParentName;
                    azureWorkloadRecoveryConfig.RestoredDBName     =
                        GetRestoredDBName(((AzureWorkloadProtectableItem)TargetItem).ParentName, RecoveryPoint.ItemName, currentTime);
                    azureWorkloadRecoveryConfig.OverwriteWLIfpresent  = "No";
                    azureWorkloadRecoveryConfig.NoRecoveryMode        = "Disabled";
                    List <SQLDataDirectoryMapping> targetPhysicalPath = new List <SQLDataDirectoryMapping>();

                    //Get target workload item
                    ODataQuery <BMSWorkloadItemQueryObject> queryParams = null;
                    string backupManagementType = ServiceClientModel.BackupManagementType.AzureWorkload;
                    queryParams = new ODataQuery <BMSWorkloadItemQueryObject>(
                        q => q.WorkloadItemType == WorkloadItemType.SQLInstance &&
                        q.BackupManagementType == backupManagementType);

                    var itemResponses = ServiceClientAdapter.ListWorkloadItem(
                        TargetItem.ContainerName,
                        queryParams,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);

                    foreach (var itemResponse in itemResponses)
                    {
                        if (string.Compare(((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).FriendlyName,
                                           ((AzureWorkloadProtectableItem)TargetItem).FriendlyName) == 0 &&
                            string.Compare(((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).ServerName,
                                           ((AzureWorkloadProtectableItem)TargetItem).ServerName) == 0)
                        {
                            string itemId = GetItemId(RecoveryPoint.Id);
                            IList <SQLDataDirectory> dataDirectoryPaths = GetRpDetails(vaultName, resourceGroupName);
                            foreach (var dataDirectoryPath in dataDirectoryPaths)
                            {
                                targetPhysicalPath.Add(new SQLDataDirectoryMapping()
                                {
                                    MappingType       = dataDirectoryPath.Type,
                                    SourceLogicalName = dataDirectoryPath.LogicalName,
                                    SourcePath        = dataDirectoryPath.Path,
                                    TargetPath        = GetTargetPath(dataDirectoryPath.Path, dataDirectoryPath.LogicalName, dataDirectoryPath.Type,
                                                                      ((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).DataDirectoryPaths
                                                                      as List <SQLDataDirectory>, offset)
                                });
                            }
                            break;
                        }
                    }
                    azureWorkloadRecoveryConfig.targetPhysicalPath = targetPhysicalPath;
                    azureWorkloadRecoveryConfig.ContainerId        = GetContainerId(TargetItem.Id);
                }
                else if (Item != null && TargetItem != null)
                {
                    if (string.Compare(((AzureWorkloadProtectableItem)TargetItem).ProtectableItemType,
                                       ProtectableItemType.SQLDataBase.ToString()) == 0)
                    {
                        throw new ArgumentException(string.Format(Resources.AzureWorkloadRestoreProtectableItemException));
                    }

                    azureWorkloadRecoveryConfig.RestoreRequestType = "Alternate WL Restore to diff item";
                    azureWorkloadRecoveryConfig.TargetServer       = ((AzureWorkloadProtectableItem)TargetItem).ServerName;
                    azureWorkloadRecoveryConfig.TargetInstance     = ((AzureWorkloadProtectableItem)TargetItem).ParentName;
                    azureWorkloadRecoveryConfig.RestoredDBName     =
                        GetRestoredDBName(((AzureWorkloadProtectableItem)TargetItem).ParentName, Item.Name, currentTime);
                    azureWorkloadRecoveryConfig.OverwriteWLIfpresent  = "No";
                    azureWorkloadRecoveryConfig.NoRecoveryMode        = "Disabled";
                    List <SQLDataDirectoryMapping> targetPhysicalPath = new List <SQLDataDirectoryMapping>();

                    //Get target workload item
                    ODataQuery <BMSWorkloadItemQueryObject> queryParams = null;
                    string backupManagementType = ServiceClientModel.BackupManagementType.AzureWorkload;
                    queryParams = new ODataQuery <BMSWorkloadItemQueryObject>(
                        q => q.WorkloadItemType == WorkloadItemType.SQLInstance &&
                        q.BackupManagementType == backupManagementType);

                    var itemResponses = ServiceClientAdapter.ListWorkloadItem(
                        TargetItem.ContainerName,
                        queryParams,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);

                    foreach (var itemResponse in itemResponses)
                    {
                        if (string.Compare(((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).FriendlyName,
                                           ((AzureWorkloadProtectableItem)TargetItem).FriendlyName) == 0 &&
                            string.Compare(((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).ServerName,
                                           ((AzureWorkloadProtectableItem)TargetItem).ServerName) == 0)
                        {
                            List <SQLDataDirectory> dataDirectory = GetDataDirectory(vaultName, resourceGroupName, Item.Id, PointInTime);
                            foreach (var dataDirectoryPath in dataDirectory)
                            {
                                targetPhysicalPath.Add(new SQLDataDirectoryMapping()
                                {
                                    MappingType       = dataDirectoryPath.Type,
                                    SourceLogicalName = dataDirectoryPath.LogicalName,
                                    SourcePath        = dataDirectoryPath.Path,
                                    TargetPath        = GetTargetPath(dataDirectoryPath.Path, dataDirectoryPath.LogicalName, dataDirectoryPath.Type,
                                                                      ((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).DataDirectoryPaths
                                                                      as List <SQLDataDirectory>, offset)
                                });
                            }
                            break;
                        }
                    }

                    Models.AzureWorkloadRecoveryPoint azureWorkloadRecoveryPoint = new Models.AzureWorkloadRecoveryPoint()
                    {
                        Id = Item.Id + "/recoveryPoints/DefaultRangeRecoveryPoint",
                        RecoveryPointId = "DefaultRangeRecoveryPoint"
                    };
                    azureWorkloadRecoveryConfig.RecoveryPoint = azureWorkloadRecoveryPoint;

                    azureWorkloadRecoveryConfig.targetPhysicalPath = targetPhysicalPath;
                    azureWorkloadRecoveryConfig.ContainerId        = GetContainerId(TargetItem.Id);
                }
                RecoveryConfigBase baseobj = azureWorkloadRecoveryConfig;
                WriteObject(baseobj);
            });
        }
예제 #5
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Resources.DisableProtectionWarning, Item.Name),
                    Resources.DisableProtectionMessage,
                    Item.Name, () =>
                {
                    base.ExecuteCmdlet();

                    ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                    string vaultName         = resourceIdentifier.ResourceName;
                    string resourceGroupName = resourceIdentifier.ResourceGroupName;

                    PsBackupProviderManager providerManager =
                        new PsBackupProviderManager(new Dictionary <System.Enum, object>()
                    {
                        { VaultParams.VaultName, vaultName },
                        { VaultParams.ResourceGroupName, resourceGroupName },
                        { ItemParams.Item, Item },
                        { ItemParams.DeleteBackupData, this.DeleteBackupData },
                    }, ServiceClientAdapter);

                    IPsBackupProvider psBackupProvider =
                        providerManager.GetProviderInstance(Item.WorkloadType,
                                                            Item.BackupManagementType);

                    if (DeleteBackupData)
                    {
                        // Fetch RecoveryPoints in Archive Tier, if yes throw warning and confirmation prompt
                        Dictionary <UriEnums, string> uriDict = HelperUtils.ParseUri(Item.Id);
                        string containerUri      = HelperUtils.GetContainerUri(uriDict, Item.Id);
                        string protectedItemName = HelperUtils.GetProtectedItemUri(uriDict, Item.Id);

                        var rpListResponse = ServiceClientAdapter.GetRecoveryPoints(
                            containerUri,
                            protectedItemName,
                            null,
                            vaultName: vaultName,
                            resourceGroupName: resourceGroupName);

                        var recoveryPointList = RecoveryPointConversions.GetPSAzureRecoveryPoints(rpListResponse, Item);
                        recoveryPointList     = RecoveryPointConversions.FilterRPsBasedOnTier(recoveryPointList, RecoveryPointTier.VaultArchive);

                        if (recoveryPointList.Count != 0)
                        {
                            bool yesToAll = Force.IsPresent;
                            bool noToAll  = false;
                            if (ShouldContinue(Resources.DeleteArchiveRecoveryPoints, Resources.DeleteRecoveryPoints, ref yesToAll, ref noToAll))
                            {
                                var itemResponse = psBackupProvider.DisableProtectionWithDeleteData();
                                Logger.Instance.WriteDebug("item Response " + JsonConvert.SerializeObject(itemResponse));
                                // Track Response and display job details
                                HandleCreatedJob(
                                    itemResponse,
                                    Resources.DisableProtectionOperation,
                                    vaultName: vaultName,
                                    resourceGroupName: resourceGroupName);
                            }
                        }
                        else
                        {
                            var itemResponse = psBackupProvider.DisableProtectionWithDeleteData();
                            Logger.Instance.WriteDebug("item Response " + JsonConvert.SerializeObject(itemResponse));
                            // Track Response and display job details
                            HandleCreatedJob(
                                itemResponse,
                                Resources.DisableProtectionOperation,
                                vaultName: vaultName,
                                resourceGroupName: resourceGroupName);
                        }
                    }
                    else
                    {
                        var itemResponse = psBackupProvider.DisableProtection();
                        Logger.Instance.WriteDebug("Disable protection response " + JsonConvert.SerializeObject(itemResponse));
                        // Track Response and display job details
                        HandleCreatedJob(
                            itemResponse,
                            Resources.DisableProtectionOperation,
                            vaultName: vaultName,
                            resourceGroupName: resourceGroupName);
                    }
                }
                    );
            }, ShouldProcess(Item.Name, VerbsLifecycle.Disable));
        }
        public List <RecoveryPointBase> ListRecoveryPoints(Dictionary <Enum, object> ProviderData)
        {
            string   vaultName             = (string)ProviderData[VaultParams.VaultName];
            string   resourceGroupName     = (string)ProviderData[VaultParams.ResourceGroupName];
            DateTime startDate             = (DateTime)(ProviderData[RecoveryPointParams.StartDate]);
            DateTime endDate               = (DateTime)(ProviderData[RecoveryPointParams.EndDate]);
            string   restorePointQueryType = ProviderData.ContainsKey(RecoveryPointParams.RestorePointQueryType) ?
                                             (string)ProviderData[RecoveryPointParams.RestorePointQueryType] : "All";
            bool secondaryRegion = (bool)ProviderData[CRRParams.UseSecondaryRegion];

            ItemBase item = ProviderData[RecoveryPointParams.Item] as ItemBase;

            Dictionary <UriEnums, string> uriDict = HelperUtils.ParseUri(item.Id);
            string containerUri      = HelperUtils.GetContainerUri(uriDict, item.Id);
            string protectedItemName = HelperUtils.GetProtectedItemUri(uriDict, item.Id);

            TimeSpan duration = endDate - startDate;

            if (duration.TotalDays > 30)
            {
                throw new Exception(Resources.RestoreDiskTimeRangeError);
            }

            //we need to fetch the list of RPs
            var queryFilterString = "null";

            if (string.Compare(restorePointQueryType, "All") == 0)
            {
                queryFilterString = QueryBuilder.Instance.GetQueryString(new BMSRPQueryObject()
                {
                    StartDate = startDate,
                    EndDate   = endDate,
                });
            }
            else
            {
                queryFilterString = QueryBuilder.Instance.GetQueryString(new BMSRPQueryObject()
                {
                    StartDate             = startDate,
                    EndDate               = endDate,
                    RestorePointQueryType = restorePointQueryType,
                    ExtendedInfo          = true
                });
            }

            ODataQuery <BMSRPQueryObject> queryFilter = new ODataQuery <BMSRPQueryObject>();

            queryFilter.Filter = queryFilterString;

            List <RecoveryPointResource> rpListResponse;

            if (secondaryRegion)
            {
                //fetch recovery points from secondary region
                rpListResponse = ServiceClientAdapter.GetRecoveryPointsFromSecondaryRegion(
                    containerUri,
                    protectedItemName,
                    queryFilter,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);
            }
            else
            {
                rpListResponse = ServiceClientAdapter.GetRecoveryPoints(
                    containerUri,
                    protectedItemName,
                    queryFilter,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);
            }

            return(RecoveryPointConversions.GetPSAzureRecoveryPoints(rpListResponse, item));
        }
        public List <PointInTimeBase> ListLogChains(Dictionary <Enum, object> ProviderData)
        {
            string   vaultName             = (string)ProviderData[VaultParams.VaultName];
            string   resourceGroupName     = (string)ProviderData[VaultParams.ResourceGroupName];
            DateTime startDate             = (DateTime)(ProviderData[RecoveryPointParams.StartDate]);
            DateTime endDate               = (DateTime)(ProviderData[RecoveryPointParams.EndDate]);
            string   restorePointQueryType = (string)ProviderData[RecoveryPointParams.RestorePointQueryType];
            bool     secondaryRegion       = (bool)ProviderData[CRRParams.UseSecondaryRegion];

            ItemBase item = ProviderData[RecoveryPointParams.Item] as ItemBase;

            Dictionary <UriEnums, string> uriDict = HelperUtils.ParseUri(item.Id);
            string containerUri      = HelperUtils.GetContainerUri(uriDict, item.Id);
            string protectedItemName = HelperUtils.GetProtectedItemUri(uriDict, item.Id);

            //we need to fetch the list of RPs
            var queryFilterString = QueryBuilder.Instance.GetQueryString(new BMSRPQueryObject()
            {
                ExtendedInfo          = true,
                StartDate             = startDate,
                EndDate               = endDate,
                RestorePointQueryType = restorePointQueryType
            });

            List <PointInTimeBase> timeRanges = new List <PointInTimeBase>();

            if (secondaryRegion)
            {
                ODataQuery <CrrModel.BMSRPQueryObject> queryFilter = new ODataQuery <CrrModel.BMSRPQueryObject>();
                queryFilter.Filter = queryFilterString;

                //fetch recovery points Log Chain from secondary region
                List <CrrModel.RecoveryPointResource> rpListResponse = ServiceClientAdapter.GetRecoveryPointsFromSecondaryRegion(
                    containerUri,
                    protectedItemName,
                    queryFilter,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);

                foreach (CrrModel.RecoveryPointResource rp in rpListResponse)
                {
                    if (rp.Properties.GetType() == typeof(CrrModel.AzureWorkloadSQLPointInTimeRecoveryPoint))
                    {
                        CrrModel.AzureWorkloadSQLPointInTimeRecoveryPoint recoveryPoint =
                            rp.Properties as CrrModel.AzureWorkloadSQLPointInTimeRecoveryPoint;

                        foreach (CrrModel.PointInTimeRange timeRange in recoveryPoint.TimeRanges)
                        {
                            timeRanges.Add(new PointInTimeBase()
                            {
                                StartTime = timeRange.StartTime,
                                EndTime   = timeRange.EndTime,
                                ItemName  = item.Name
                            });
                        }
                    }
                }
            }
            else
            {
                ODataQuery <BMSRPQueryObject> queryFilter = new ODataQuery <BMSRPQueryObject>();
                queryFilter.Filter = queryFilterString;

                List <RecoveryPointResource> rpListResponse = ServiceClientAdapter.GetRecoveryPoints(
                    containerUri,
                    protectedItemName,
                    queryFilter,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);

                foreach (RecoveryPointResource rp in rpListResponse)
                {
                    if (rp.Properties.GetType() == typeof(AzureWorkloadSQLPointInTimeRecoveryPoint))
                    {
                        AzureWorkloadSQLPointInTimeRecoveryPoint recoveryPoint =
                            rp.Properties as AzureWorkloadSQLPointInTimeRecoveryPoint;
                        foreach (PointInTimeRange timeRange in recoveryPoint.TimeRanges)
                        {
                            timeRanges.Add(new PointInTimeBase()
                            {
                                StartTime = timeRange.StartTime,
                                EndTime   = timeRange.EndTime,
                                ItemName  = item.Name
                            });
                        }
                    }
                }
            }

            return(timeRanges);
        }
        private RestAzureNS.AzureOperationResponse <ProtectedItemResource> EnableOrModifyProtection(bool disableWithRetentionData = false)
        {
            string vaultName = (string)ProviderData[VaultParams.VaultName];
            string vaultResourceGroupName = (string)ProviderData[VaultParams.ResourceGroupName];
            string azureFileShareName     = ProviderData.ContainsKey(ItemParams.ItemName) ?
                                            (string)ProviderData[ItemParams.ItemName] : null;
            string storageAccountName = ProviderData.ContainsKey(ItemParams.StorageAccountName) ?
                                        (string)ProviderData[ItemParams.StorageAccountName] : null;
            string parameterSetName = ProviderData.ContainsKey(ItemParams.ParameterSetName) ?
                                      (string)ProviderData[ItemParams.ParameterSetName] : null;

            PolicyBase policy = ProviderData.ContainsKey(ItemParams.Policy) ?
                                (PolicyBase)ProviderData[ItemParams.Policy] : null;

            ItemBase itemBase = (ItemBase)ProviderData[ItemParams.Item];

            AzureFileShareItem item = (AzureFileShareItem)ProviderData[ItemParams.Item];

            string containerUri     = "";
            string protectedItemUri = "";
            string sourceResourceId = null;
            AzureFileshareProtectedItem properties = new AzureFileshareProtectedItem();

            if (itemBase == null)
            {
                //Enable protection
                ValidateAzureFilesWorkloadType(policy.WorkloadType);

                ValidateFileShareEnableProtectionRequest(
                    azureFileShareName,
                    storageAccountName);

                WorkloadProtectableItemResource protectableObjectResource =
                    GetAzureFileShareProtectableObject(
                        azureFileShareName,
                        storageAccountName,
                        vaultName: vaultName,
                        vaultResourceGroupName: vaultResourceGroupName);

                Dictionary <UriEnums, string> keyValueDict =
                    HelperUtils.ParseUri(protectableObjectResource.Id);
                containerUri = HelperUtils.GetContainerUri(
                    keyValueDict, protectableObjectResource.Id);
                protectedItemUri = HelperUtils.GetProtectableItemUri(
                    keyValueDict, protectableObjectResource.Id);

                AzureFileShareProtectableItem azureFileShareProtectableItem =
                    (AzureFileShareProtectableItem)protectableObjectResource.Properties;
                if (azureFileShareProtectableItem != null)
                {
                    sourceResourceId = azureFileShareProtectableItem.ParentContainerFabricId;
                }
                // construct Service Client protectedItem request
                properties.PolicyId         = policy.Id;
                properties.SourceResourceId = sourceResourceId;
            }
            else if (itemBase != null && !disableWithRetentionData)
            {
                //modify policy with new policy
                ValidateAzureFilesWorkloadType(item.WorkloadType, policy.WorkloadType);
                ValidateAzureFilesModifyProtectionRequest(itemBase, policy);

                Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(item.Id);
                containerUri     = HelperUtils.GetContainerUri(keyValueDict, item.Id);
                protectedItemUri = HelperUtils.GetProtectedItemUri(keyValueDict, item.Id);
                sourceResourceId = item.SourceResourceId;
                // construct Service Client protectedItem request
                properties.PolicyId         = policy.Id;
                properties.SourceResourceId = sourceResourceId;
            }
            else if (disableWithRetentionData)
            {
                //Disable protection while retaining backup data
                ValidateAzureFileShareDisableProtectionRequest(itemBase);

                Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(item.Id);
                containerUri                = HelperUtils.GetContainerUri(keyValueDict, item.Id);
                protectedItemUri            = HelperUtils.GetProtectedItemUri(keyValueDict, item.Id);
                properties.PolicyId         = string.Empty;
                properties.ProtectionState  = ProtectionState.ProtectionStopped;
                properties.SourceResourceId = item.SourceResourceId;
            }

            ProtectedItemResource serviceClientRequest = new ProtectedItemResource()
            {
                Properties = properties
            };

            return(ServiceClientAdapter.CreateOrUpdateProtectedItem(
                       containerUri,
                       protectedItemUri,
                       serviceClientRequest,
                       vaultName: vaultName,
                       resourceGroupName: vaultResourceGroupName));
        }
        // filter items from secondary region
        public List <CmdletModel.ItemBase> ListProtectedItemsByItemNameCrr(
            List <CrrModel.ProtectedItemResource> protectedItems,
            string itemName,
            string vaultName,
            string resourceGroupName,
            Action <CmdletModel.ItemBase, ProtectedItemResource> extendedInfoProcessor, string friendlyName = null)
        {
            List <ProtectedItemResource> protectedItemGetResponses = new List <ProtectedItemResource>();

            if (!string.IsNullOrEmpty(itemName) || !string.IsNullOrEmpty(friendlyName))
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <CmdletModel.UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItem.Id);

                    string protectedItemUri = HelperUtils.GetProtectedItemUri(dictionary, protectedItem.Id);

                    bool filteredByUniqueName   = itemName != null && (protectedItemUri.ToLower().Contains(itemName.ToLower()));
                    bool filteredByFriendlyName = false;

                    if (protectedItem.Properties.BackupManagementType == "AzureStorage" && protectedItem.Properties.WorkloadType == "AzureFileShare")
                    {
                        // code should never reach here, as CRR is not supported for azure files yet
                        string protectedItemFriendlyName = (protectedItem.Properties as CrrModel.AzureFileshareProtectedItem).FriendlyName;
                        filteredByUniqueName             = filteredByUniqueName || (itemName != null && protectedItemFriendlyName.ToLower() == itemName.ToLower());
                        filteredByFriendlyName           = friendlyName != null && protectedItemFriendlyName.ToLower() == friendlyName.ToLower();
                    }

                    return(filteredByUniqueName || filteredByFriendlyName);
                }).ToList();

                // bug: below API calls should be made to secondary region
                ODataQuery <GetProtectedItemQueryObject> getItemQueryParams =
                    new ODataQuery <GetProtectedItemQueryObject>(q => q.Expand == "extendedinfo");

                for (int i = 0; i < protectedItems.Count; i++)
                {
                    Dictionary <CmdletModel.UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItems[i].Id);
                    string containerUri     = HelperUtils.GetContainerUri(dictionary, protectedItems[i].Id);
                    string protectedItemUri = HelperUtils.GetProtectedItemUri(dictionary, protectedItems[i].Id);

                    var getResponse = ServiceClientAdapter.GetProtectedItem(
                        containerUri,
                        protectedItemUri,
                        getItemQueryParams,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);
                    protectedItemGetResponses.Add(getResponse.Body);
                }
            }

            List <CmdletModel.ItemBase> itemModels = ConversionHelpers.GetItemModelListCrr(protectedItems);

            if (!string.IsNullOrEmpty(itemName))
            {
                for (int i = 0; i < itemModels.Count; i++)
                {
                    extendedInfoProcessor(itemModels[i], protectedItemGetResponses[i]);
                }
            }
            return(itemModels);
        }
예제 #10
0
        public List <PointInTimeBase> ListLogChains(Dictionary <Enum, object> ProviderData)
        {
            string   vaultName             = (string)ProviderData[VaultParams.VaultName];
            string   resourceGroupName     = (string)ProviderData[VaultParams.ResourceGroupName];
            DateTime startDate             = (DateTime)(ProviderData[RecoveryPointParams.StartDate]);
            DateTime endDate               = (DateTime)(ProviderData[RecoveryPointParams.EndDate]);
            string   restorePointQueryType = (string)ProviderData[RecoveryPointParams.RestorePointQueryType];

            ItemBase item = ProviderData[RecoveryPointParams.Item] as ItemBase;

            Dictionary <UriEnums, string> uriDict = HelperUtils.ParseUri(item.Id);
            string containerUri      = HelperUtils.GetContainerUri(uriDict, item.Id);
            string protectedItemName = HelperUtils.GetProtectedItemUri(uriDict, item.Id);

            TimeSpan duration = endDate - startDate;

            if (duration.TotalDays > 30)
            {
                throw new Exception(Resources.RestoreDiskTimeRangeError);
            }

            //we need to fetch the list of RPs
            var queryFilterString = QueryBuilder.Instance.GetQueryString(new BMSRPQueryObject()
            {
                ExtendedInfo          = true,
                StartDate             = startDate,
                EndDate               = endDate,
                RestorePointQueryType = restorePointQueryType
            });

            ODataQuery <BMSRPQueryObject> queryFilter = new ODataQuery <BMSRPQueryObject>();

            queryFilter.Filter = queryFilterString;

            List <RecoveryPointResource> rpListResponse = ServiceClientAdapter.GetRecoveryPoints(
                containerUri,
                protectedItemName,
                queryFilter,
                vaultName: vaultName,
                resourceGroupName: resourceGroupName);

            List <PointInTimeBase> timeRanges = new List <PointInTimeBase>();

            foreach (RecoveryPointResource rp in rpListResponse)
            {
                if (rp.Properties.GetType() == typeof(AzureWorkloadSQLPointInTimeRecoveryPoint))
                {
                    AzureWorkloadSQLPointInTimeRecoveryPoint recoveryPoint =
                        rp.Properties as AzureWorkloadSQLPointInTimeRecoveryPoint;
                    foreach (PointInTimeRange timeRange in recoveryPoint.TimeRanges)
                    {
                        timeRanges.Add(new PointInTimeBase()
                        {
                            StartTime = timeRange.StartTime,
                            EndTime   = timeRange.EndTime,
                            ItemName  = item.Name
                        });
                    }
                }
            }
            return(timeRanges);
        }
        public AzureWorkloadRecoveryConfig GetConfigObject()
        {
            string            targetServer       = "";
            string            parentName         = "";
            string            restoreRequestType = "";
            RecoveryPointBase recoveryPoint      = RecoveryPoint;
            DateTime          pointInTime        = PointInTime;

            if (ParameterSetName == RpParameterSet)
            {
                Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(RecoveryPoint.Id);
                string containerUri = HelperUtils.GetContainerUri(keyValueDict, RecoveryPoint.Id);
                try
                {
                    targetServer = containerUri.Split(new string[] { ";" }, StringSplitOptions.None)[3];
                }
                catch
                {
                    targetServer = containerUri.Split(new string[] { ";" }, StringSplitOptions.None)[1];
                }

                string itemUri = HelperUtils.GetProtectedItemUri(keyValueDict, RecoveryPoint.Id);
                parentName = itemUri.Split(new string[] { ";" }, StringSplitOptions.None)[1];
            }

            if (OriginalWorkloadRestore.IsPresent)
            {
                restoreRequestType = "Original WL Restore";
                if (Item != null)
                {
                    targetServer = ((AzureWorkloadSQLDatabaseProtectedItem)Item).ServerName;
                    parentName   = ((AzureWorkloadSQLDatabaseProtectedItem)Item).ParentName;
                }
                if (RecoveryPoint == null)
                {
                    Models.AzureWorkloadRecoveryPoint azureWorkloadRecoveryPoint = new Models.AzureWorkloadRecoveryPoint()
                    {
                        Id = Item.Id + "/recoveryPoints/DefaultRangeRecoveryPoint",
                        RecoveryPointId = "DefaultRangeRecoveryPoint"
                    };
                    recoveryPoint = azureWorkloadRecoveryPoint;
                }
            }
            else if (AlternateWorkloadRestore.IsPresent && Item == null)
            {
                restoreRequestType = "Alternate WL Restore";
                targetServer       = ((AzureWorkloadProtectableItem)TargetItem).ServerName;
                parentName         = ((AzureWorkloadProtectableItem)TargetItem).ParentName;
            }
            else if (Item != null && TargetItem != null)
            {
                restoreRequestType = "Alternate WL Restore to diff item";
                targetServer       = ((AzureWorkloadProtectableItem)TargetItem).ServerName;
                parentName         = ((AzureWorkloadProtectableItem)TargetItem).ParentName;

                Models.AzureWorkloadRecoveryPoint azureWorkloadRecoveryPoint = new Models.AzureWorkloadRecoveryPoint()
                {
                    Id = Item.Id + "/recoveryPoints/DefaultRangeRecoveryPoint",
                    RecoveryPointId = "DefaultRangeRecoveryPoint"
                };
                recoveryPoint = azureWorkloadRecoveryPoint;
            }
            else if (RestoreAsFiles.IsPresent)
            {
                restoreRequestType = "Alternate WL Restore";
                targetServer       = TargetContainer.Name;
                if (recoveryPoint == null && FromFull == null)
                {
                    Models.AzureWorkloadRecoveryPoint azureWorkloadRecoveryPoint = new Models.AzureWorkloadRecoveryPoint()
                    {
                        Id = Item.Id + "/recoveryPoints/DefaultRangeRecoveryPoint",
                        RecoveryPointId = "DefaultRangeRecoveryPoint"
                    };
                    recoveryPoint = azureWorkloadRecoveryPoint;
                }
                else if (FromFull != null)
                {
                    recoveryPoint = FromFull;
                }
            }

            return(new AzureWorkloadRecoveryConfig(targetServer, parentName, restoreRequestType, recoveryPoint, pointInTime));
        }
예제 #12
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName         = resourceIdentifier.ResourceName;
                string resourceGroupName = resourceIdentifier.ResourceGroupName;

                string backupManagementType = "";
                string workloadType         = "";
                ODataQuery <BMSPOQueryObject> queryParam = null;
                if (ParameterSetName == IdParamSet)
                {
                    string containerName = "";
                    Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(ParentID);
                    containerName = HelperUtils.GetContainerUri(keyValueDict, ParentID);
                    if (containerName.Split(new string[] { ";" }, System.StringSplitOptions.None)[0].ToLower() == "vmappcontainer")
                    {
                        backupManagementType = ServiceClientModel.BackupManagementType.AzureWorkload;
                    }
                    string protectableItem = HelperUtils.GetProtectableItemUri(keyValueDict, ParentID);
                    if (protectableItem.Split(new string[] { ";" }, System.StringSplitOptions.None)[0].ToLower() == "sqlinstance" ||
                        protectableItem.Split(new string[] { ";" }, System.StringSplitOptions.None)[0].ToLower() == "sqlavailabilitygroupcontainer")
                    {
                        workloadType = ServiceClientModel.WorkloadType.SQLDataBase;
                    }
                    queryParam = new ODataQuery <BMSPOQueryObject>(
                        q => q.BackupManagementType
                        == backupManagementType &&
                        q.WorkloadType == workloadType &&
                        q.ContainerName == containerName);
                }
                else
                {
                    if (Container != null)
                    {
                        string containerName = "";
                        backupManagementType = Container.BackupManagementType.ToString();
                        workloadType         = ConversionUtils.GetServiceClientWorkloadType(WorkloadType.ToString());
                        containerName        = Container.Name;
                        queryParam           = new ODataQuery <BMSPOQueryObject>(
                            q => q.BackupManagementType
                            == backupManagementType &&
                            q.WorkloadType == workloadType &&
                            q.ContainerName == containerName);
                    }
                    else
                    {
                        backupManagementType = "AzureWorkload";
                        workloadType         = ConversionUtils.GetServiceClientWorkloadType(WorkloadType.ToString());
                        queryParam           = new ODataQuery <BMSPOQueryObject>(
                            q => q.BackupManagementType
                            == backupManagementType &&
                            q.WorkloadType == workloadType);
                    }
                }


                WriteDebug("going to query service to get list of protectable items");
                List <WorkloadProtectableItemResource> protectableItems =
                    ServiceClientAdapter.ListProtectableItem(
                        queryParam,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);
                WriteDebug("Successfully got response from service");
                List <ProtectableItemBase> itemModels = ConversionHelpers.GetProtectableItemModelList(protectableItems);

                if (ParameterSetName == FilterParamSet)
                {
                    string protectableItemType = ItemType.ToString();
                    itemModels = itemModels.Where(itemModel =>
                    {
                        return(((AzureWorkloadProtectableItem)itemModel).ProtectableItemType == protectableItemType);
                    }).ToList();
                }
                WriteObject(itemModels, enumerateCollection: true);
            });
        }
예제 #13
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName               = resourceIdentifier.ResourceName;
                string resourceGroupName       = resourceIdentifier.ResourceGroupName;
                string targetVaultName         = "";
                string targetResourceGroupName = "";

                if (!OriginalWorkloadRestore.IsPresent && !AlternateWorkloadRestore.IsPresent && !RestoreAsFiles.IsPresent)
                {
                    throw new ArgumentException(string.Format(Resources.AzureWorkloadRestoreLocationException));
                }

                AzureWorkloadRecoveryConfig azureWorkloadRecoveryConfig = GetConfigObject();
                azureWorkloadRecoveryConfig.SourceResourceId            = Item != null ? Item.SourceResourceId : GetResourceId();
                DateTime currentTime = DateTime.Now;
                TimeSpan timeSpan    = DateTime.UtcNow - new DateTime(1970, 1, 1);
                int offset           = (int)timeSpan.TotalSeconds;
                string targetDb      = "";

                if (AlternateWorkloadRestore.IsPresent || RestoreAsFiles.IsPresent)
                {
                    if (TargetContainer == null)
                    {
                        throw new ArgumentNullException("TargetContainer", Resources.TargetContainerRequiredException);
                    }

                    azureWorkloadRecoveryConfig.TargetVirtualMachineId = (TargetContainer as AzureVmWorkloadContainer).SourceResourceId;
                }

                if (TargetItem != null)
                {
                    // getting Target vault/RG for TargetPhysicalPath in CRR
                    Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(TargetItem.Id);
                    targetResourceGroupName = HelperUtils.GetResourceGroupNameFromId(keyValueDict, TargetItem.Id);
                    targetVaultName         = HelperUtils.GetVaultNameFromId(keyValueDict, TargetItem.Id);

                    // check if the TragetItem provided is of workload type
                    if (!string.Equals(((AzureWorkloadProtectableItem)TargetItem).ProtectableItemType,
                                       ProtectableItemType.SQLInstance.ToString()))
                    {
                        throw new ArgumentException(string.Format(Resources.AzureWorkloadRestoreProtectableItemException));
                    }
                }

                if (ParameterSetName == RpParameterSet)
                {
                    Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(RecoveryPoint.Id);
                    string itemUri = HelperUtils.GetProtectedItemUri(keyValueDict, RecoveryPoint.Id);
                    targetDb       = itemUri.Split(new string[] { ";" }, StringSplitOptions.None)[2];
                }

                if (OriginalWorkloadRestore.IsPresent)
                {
                    azureWorkloadRecoveryConfig.RestoredDBName = Item != null ?
                                                                 ((AzureWorkloadSQLDatabaseProtectedItem)Item).FriendlyName : targetDb;
                    azureWorkloadRecoveryConfig.OverwriteWLIfpresent = "No";
                    azureWorkloadRecoveryConfig.NoRecoveryMode       = "Disabled";
                    azureWorkloadRecoveryConfig.ContainerId          = Item != null ?
                                                                       GetContainerId(Item.Id) : GetContainerId(GetItemId(RecoveryPoint.Id));
                }
                else if (AlternateWorkloadRestore.IsPresent && Item == null)
                {
                    azureWorkloadRecoveryConfig.RestoredDBName =
                        GetRestoredDBName(RecoveryPoint.ItemName, currentTime);
                    azureWorkloadRecoveryConfig.OverwriteWLIfpresent  = "No";
                    azureWorkloadRecoveryConfig.NoRecoveryMode        = "Disabled";
                    List <SQLDataDirectoryMapping> targetPhysicalPath = new List <SQLDataDirectoryMapping>();

                    //Get target workload item
                    ODataQuery <BMSWorkloadItemQueryObject> queryParams = null;
                    string backupManagementType = ServiceClientModel.BackupManagementType.AzureWorkload;
                    queryParams = new ODataQuery <BMSWorkloadItemQueryObject>(
                        q => q.WorkloadItemType == WorkloadItemType.SQLInstance &&
                        q.BackupManagementType == backupManagementType);

                    List <WorkloadItemResource> itemResponses;
                    if (targetVaultName != "" && targetResourceGroupName != "")
                    {
                        itemResponses = ServiceClientAdapter.ListWorkloadItem(
                            TargetItem.ContainerName,
                            queryParams,
                            vaultName: targetVaultName,
                            resourceGroupName: targetResourceGroupName);
                    }
                    else
                    {
                        itemResponses = ServiceClientAdapter.ListWorkloadItem(
                            TargetItem.ContainerName,
                            queryParams,
                            vaultName: vaultName,
                            resourceGroupName: resourceGroupName);
                    }

                    foreach (var itemResponse in itemResponses)
                    {
                        if (string.Compare(((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).FriendlyName,
                                           ((AzureWorkloadProtectableItem)TargetItem).FriendlyName) == 0 &&
                            string.Compare(((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).ServerName,
                                           ((AzureWorkloadProtectableItem)TargetItem).ServerName) == 0)
                        {
                            string itemId = GetItemId(RecoveryPoint.Id);
                            IList <SQLDataDirectory> dataDirectoryPaths = GetRpDetails(vaultName, resourceGroupName);
                            foreach (var dataDirectoryPath in dataDirectoryPaths)
                            {
                                targetPhysicalPath.Add(new SQLDataDirectoryMapping()
                                {
                                    MappingType       = dataDirectoryPath.Type,
                                    SourceLogicalName = dataDirectoryPath.LogicalName,
                                    SourcePath        = dataDirectoryPath.Path,
                                    TargetPath        = GetTargetPath(dataDirectoryPath.Path, dataDirectoryPath.LogicalName, dataDirectoryPath.Type,
                                                                      ((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).DataDirectoryPaths
                                                                      as List <SQLDataDirectory>, offset)
                                });
                            }
                            break;
                        }
                    }
                    azureWorkloadRecoveryConfig.targetPhysicalPath = targetPhysicalPath;
                    azureWorkloadRecoveryConfig.ContainerId        = GetContainerId(TargetItem.Id);
                }
                else if (Item != null && TargetItem != null)
                {
                    azureWorkloadRecoveryConfig.RestoredDBName =
                        GetRestoredDBName(Item.Name, currentTime);
                    azureWorkloadRecoveryConfig.OverwriteWLIfpresent  = "No";
                    azureWorkloadRecoveryConfig.NoRecoveryMode        = "Disabled";
                    List <SQLDataDirectoryMapping> targetPhysicalPath = new List <SQLDataDirectoryMapping>();

                    //Get target workload item
                    ODataQuery <BMSWorkloadItemQueryObject> queryParams = null;
                    string backupManagementType = ServiceClientModel.BackupManagementType.AzureWorkload;
                    queryParams = new ODataQuery <BMSWorkloadItemQueryObject>(
                        q => q.WorkloadItemType == WorkloadItemType.SQLInstance &&
                        q.BackupManagementType == backupManagementType);

                    List <WorkloadItemResource> itemResponses;
                    if (targetVaultName != "" && targetResourceGroupName != "")
                    {
                        itemResponses = ServiceClientAdapter.ListWorkloadItem(
                            TargetItem.ContainerName,
                            queryParams,
                            vaultName: targetVaultName,
                            resourceGroupName: targetResourceGroupName);
                    }
                    else
                    {
                        itemResponses = ServiceClientAdapter.ListWorkloadItem(
                            TargetItem.ContainerName,
                            queryParams,
                            vaultName: vaultName,
                            resourceGroupName: resourceGroupName);
                    }

                    foreach (var itemResponse in itemResponses)
                    {
                        if (string.Compare(((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).FriendlyName,
                                           ((AzureWorkloadProtectableItem)TargetItem).FriendlyName) == 0 &&
                            string.Compare(((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).ServerName,
                                           ((AzureWorkloadProtectableItem)TargetItem).ServerName) == 0)
                        {
                            List <SQLDataDirectory> dataDirectory = GetDataDirectory(vaultName, resourceGroupName, Item.Id, PointInTime);
                            foreach (var dataDirectoryPath in dataDirectory)
                            {
                                targetPhysicalPath.Add(new SQLDataDirectoryMapping()
                                {
                                    MappingType       = dataDirectoryPath.Type,
                                    SourceLogicalName = dataDirectoryPath.LogicalName,
                                    SourcePath        = dataDirectoryPath.Path,
                                    TargetPath        = GetTargetPath(dataDirectoryPath.Path, dataDirectoryPath.LogicalName, dataDirectoryPath.Type,
                                                                      ((AzureVmWorkloadSQLInstanceWorkloadItem)itemResponse.Properties).DataDirectoryPaths
                                                                      as List <SQLDataDirectory>, offset)
                                });
                            }
                            break;
                        }
                    }
                    azureWorkloadRecoveryConfig.targetPhysicalPath = targetPhysicalPath;
                    azureWorkloadRecoveryConfig.ContainerId        = GetContainerId(TargetItem.Id);
                }
                else if (RestoreAsFiles.IsPresent)
                {
                    azureWorkloadRecoveryConfig.OverwriteWLIfpresent = "No";
                    azureWorkloadRecoveryConfig.NoRecoveryMode       = "Disabled";
                    azureWorkloadRecoveryConfig.ContainerId          = (TargetContainer as AzureVmWorkloadContainer).Id;
                    azureWorkloadRecoveryConfig.RestoreRequestType   = "Alternate WL Restore";
                    azureWorkloadRecoveryConfig.RecoveryMode         = "FileRecovery";
                    azureWorkloadRecoveryConfig.FilePath             = FilePath;
                    azureWorkloadRecoveryConfig.FullRP = FromFull;
                }
                RecoveryConfigBase baseobj = azureWorkloadRecoveryConfig;
                WriteObject(baseobj);
            });
        }
        public void FetchNodesListAndAutoProtectionPolicy(List <ProtectableItemBase> itemModels, string vaultName, string resourceGroupName)
        {
            foreach (var itemModel in itemModels)
            {
                AzureWorkloadProtectableItem protectableItem = ((AzureWorkloadProtectableItem)itemModel);

                string itemType             = "";
                string itemName             = "";
                string containerUri         = "";
                string backupManagementType = "";

                Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(protectableItem.Id);

                itemType     = HelperUtils.GetProtectableItemUri(keyValueDict, protectableItem.Id).Split(';')[0];
                itemName     = HelperUtils.GetProtectableItemUri(keyValueDict, protectableItem.Id).Split(';')[1];
                containerUri = HelperUtils.GetContainerUri(keyValueDict, protectableItem.Id);

                // fetch AutoProtectionPolicy for non DBs
                if (protectableItem.ProtectableItemType != "SQLDataBase")
                {
                    // fetch the policy using backup intent
                    ODataQuery <ServiceClientModel.ProtectionIntentQueryObject> queryParams = null;
                    backupManagementType = ServiceClientModel.BackupManagementType.AzureWorkload;

                    queryParams = new ODataQuery <ServiceClientModel.ProtectionIntentQueryObject>(
                        q => q.ItemType == itemType &&
                        q.ItemName == itemName &&
                        q.ParentName == containerUri &&
                        q.BackupManagementType == backupManagementType);

                    var intentList = ServiceClientAdapter.ListProtectionIntent(
                        queryParams,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);

                    foreach (var intent in intentList)
                    {
                        protectableItem.AutoProtectionPolicy = intent.Properties.PolicyId;
                    }
                }

                //  fetch Nodelist for SQLAGs
                if (protectableItem.ProtectableItemType == "SQLAvailabilityGroup")
                {
                    try
                    {
                        // add the NodeList
                        ProtectionContainerResource sqlAGContainer = ServiceClientAdapter.GetContainer(vaultName, resourceGroupName, containerUri);

                        if (sqlAGContainer != null)
                        {
                            AzureSQLAGWorkloadContainerProtectionContainer protectionContainer = (AzureSQLAGWorkloadContainerProtectionContainer)sqlAGContainer.Properties;

                            if (protectionContainer != null && protectionContainer.ExtendedInfo != null)
                            {
                                protectableItem.NodesList = protectionContainer.ExtendedInfo.NodesList;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        WriteDebug(e.Message);
                    }
                }
            }
        }
        /// <summary>
        /// Lists protected items protected by the recovery services vault according to the provider data
        /// </summary>
        /// <returns>List of protected items</returns>
        public List <ItemBase> ListProtectedItems()
        {
            ContainerBase container =
                (ContainerBase)this.ProviderData[ItemParams.Container];
            string name = (string)this.ProviderData[ItemParams.AzureVMName];
            ItemProtectionStatus protectionStatus =
                (ItemProtectionStatus)this.ProviderData[ItemParams.ProtectionStatus];
            ItemProtectionState status =
                (ItemProtectionState)this.ProviderData[ItemParams.ProtectionState];

            Models.WorkloadType workloadType =
                (Models.WorkloadType) this.ProviderData[ItemParams.WorkloadType];

            ProtectedItemListQueryParam queryParams = new ProtectedItemListQueryParam();

            queryParams.DatasourceType       = ServiceClientModel.WorkloadType.VM;
            queryParams.BackupManagementType = ServiceClientModel.BackupManagementType.AzureIaasVM.ToString();

            List <ProtectedItemResource> protectedItems = new List <ProtectedItemResource>();
            string            skipToken         = null;
            PaginationRequest paginationRequest = null;

            do
            {
                var listResponse = ServiceClientAdapter.ListProtectedItem(queryParams, paginationRequest);
                protectedItems.AddRange(listResponse.ItemList.Value);

                ServiceClientHelpers.GetSkipTokenFromNextLink(listResponse.ItemList.NextLink, out skipToken);
                if (skipToken != null)
                {
                    paginationRequest           = new PaginationRequest();
                    paginationRequest.SkipToken = skipToken;
                }
            } while (skipToken != null);

            // 1. Filter by container
            if (container != null)
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItem.Id);
                    string containerUri = HelperUtils.GetContainerUri(dictionary, protectedItem.Id);
                    return(containerUri.Contains(container.Name));
                }).ToList();
            }

            List <ProtectedItemResponse> protectedItemGetResponses = new List <ProtectedItemResponse>();

            // 2. Filter by item's friendly name
            if (!string.IsNullOrEmpty(name))
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItem.Id);
                    string protectedItemUri = HelperUtils.GetProtectedItemUri(dictionary, protectedItem.Id);
                    return(protectedItemUri.ToLower().Contains(name.ToLower()));
                }).ToList();

                GetProtectedItemQueryParam getItemQueryParams = new GetProtectedItemQueryParam();
                getItemQueryParams.Expand = "extendedinfo";

                for (int i = 0; i < protectedItems.Count; i++)
                {
                    Dictionary <UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItems[i].Id);
                    string containerUri     = HelperUtils.GetContainerUri(dictionary, protectedItems[i].Id);
                    string protectedItemUri = HelperUtils.GetProtectedItemUri(dictionary, protectedItems[i].Id);

                    var getResponse = ServiceClientAdapter.GetProtectedItem(containerUri, protectedItemUri, getItemQueryParams);
                    protectedItemGetResponses.Add(getResponse);
                }
            }

            List <ItemBase> itemModels = ConversionHelpers.GetItemModelList(protectedItems);

            if (!string.IsNullOrEmpty(name))
            {
                for (int i = 0; i < itemModels.Count; i++)
                {
                    AzureVmItemExtendedInfo extendedInfo = new AzureVmItemExtendedInfo();
                    var serviceClientExtendedInfo        = ((AzureIaaSVMProtectedItem)protectedItemGetResponses[i].Item.Properties).ExtendedInfo;
                    if (serviceClientExtendedInfo.OldestRecoveryPoint.HasValue)
                    {
                        extendedInfo.OldestRecoveryPoint = serviceClientExtendedInfo.OldestRecoveryPoint;
                    }
                    extendedInfo.PolicyState                  = serviceClientExtendedInfo.PolicyInconsistent.ToString();
                    extendedInfo.RecoveryPointCount           = serviceClientExtendedInfo.RecoveryPointCount;
                    ((AzureVmItem)itemModels[i]).ExtendedInfo = extendedInfo;
                }
            }

            // 3. Filter by item's Protection Status
            if (protectionStatus != 0)
            {
                itemModels = itemModels.Where(itemModel =>
                {
                    return(((AzureVmItem)itemModel).ProtectionStatus == protectionStatus);
                }).ToList();
            }

            // 4. Filter by item's Protection State
            if (status != 0)
            {
                itemModels = itemModels.Where(itemModel =>
                {
                    return(((AzureVmItem)itemModel).ProtectionState == status);
                }).ToList();
            }

            // 5. Filter by workload type
            if (workloadType != 0)
            {
                itemModels = itemModels.Where(itemModel =>
                {
                    return(itemModel.WorkloadType == workloadType);
                }).ToList();
            }

            return(itemModels);
        }
        public List <RecoveryPointBase> ListRecoveryPoints(Dictionary <Enum, object> ProviderData)
        {
            string   vaultName             = (string)ProviderData[VaultParams.VaultName];
            string   resourceGroupName     = (string)ProviderData[VaultParams.ResourceGroupName];
            DateTime startDate             = (DateTime)(ProviderData[RecoveryPointParams.StartDate]);
            DateTime endDate               = (DateTime)(ProviderData[RecoveryPointParams.EndDate]);
            string   restorePointQueryType = ProviderData.ContainsKey(RecoveryPointParams.RestorePointQueryType) ?
                                             (string)ProviderData[RecoveryPointParams.RestorePointQueryType] : "All";
            bool secondaryRegion         = (bool)ProviderData[CRRParams.UseSecondaryRegion];
            RecoveryPointTier targetTier = (RecoveryPointTier)ProviderData[RecoveryPointParams.TargetTier];
            bool isReadyForMove          = (bool)ProviderData[RecoveryPointParams.IsReadyForMove];
            RecoveryPointTier tier       = (RecoveryPointTier)ProviderData[RecoveryPointParams.Tier];

            ItemBase item = ProviderData[RecoveryPointParams.Item] as ItemBase;

            Dictionary <UriEnums, string> uriDict = HelperUtils.ParseUri(item.Id);
            string containerUri      = HelperUtils.GetContainerUri(uriDict, item.Id);
            string protectedItemName = HelperUtils.GetProtectedItemUri(uriDict, item.Id);

            //we need to fetch the list of RPs
            var queryFilterString = "null";

            if (string.Compare(restorePointQueryType, "All") == 0)
            {
                queryFilterString = QueryBuilder.Instance.GetQueryString(new BMSRPQueryObject()
                {
                    StartDate = startDate,
                    EndDate   = endDate,
                });
            }
            else
            {
                queryFilterString = QueryBuilder.Instance.GetQueryString(new BMSRPQueryObject()
                {
                    StartDate             = startDate,
                    EndDate               = endDate,
                    RestorePointQueryType = restorePointQueryType,
                    ExtendedInfo          = true
                });
            }

            List <RecoveryPointBase> recoveryPointList;

            if (secondaryRegion)
            {
                ODataQuery <CrrModel.BMSRPQueryObject> queryFilter = new ODataQuery <CrrModel.BMSRPQueryObject>();
                queryFilter.Filter = queryFilterString;

                //fetch recovery points from secondary region
                List <CrrModel.RecoveryPointResource> rpListResponseCrr;
                rpListResponseCrr = ServiceClientAdapter.GetRecoveryPointsFromSecondaryRegion(
                    containerUri,
                    protectedItemName,
                    queryFilter,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);

                recoveryPointList = RecoveryPointConversions.GetPSAzureRecoveryPointsForSecondaryRegion(rpListResponseCrr, item);
            }
            else
            {
                ODataQuery <BMSRPQueryObject> queryFilter = new ODataQuery <BMSRPQueryObject>();
                queryFilter.Filter = queryFilterString;

                List <RecoveryPointResource> rpListResponse;
                rpListResponse = ServiceClientAdapter.GetRecoveryPoints(
                    containerUri,
                    protectedItemName,
                    queryFilter,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);

                recoveryPointList = RecoveryPointConversions.GetPSAzureRecoveryPoints(rpListResponse, item);
            }

            //filter out archived recovery points for secondary region
            if (secondaryRegion)
            {
                recoveryPointList = recoveryPointList.Where(
                    recoveryPoint =>
                {
                    if (recoveryPoint.GetType() == typeof(AzureVmRecoveryPoint))
                    {
                        return(((AzureVmRecoveryPoint)recoveryPoint).RecoveryPointTier != RecoveryPointTier.VaultArchive);
                    }

                    if (recoveryPoint.GetType() == typeof(CmdletModel.AzureWorkloadRecoveryPoint))
                    {
                        return(((CmdletModel.AzureWorkloadRecoveryPoint)recoveryPoint).RecoveryPointTier != RecoveryPointTier.VaultArchive);
                    }

                    return(false);
                }).ToList();
            }

            // filter move readness based on target tier
            recoveryPointList = RecoveryPointConversions.CheckRPMoveReadiness(recoveryPointList, targetTier, isReadyForMove);

            //filter RPs based on tier
            return(RecoveryPointConversions.FilterRPsBasedOnTier(recoveryPointList, tier));
        }
        /// <summary>
        /// Triggers the enable protection operation for the given item
        /// </summary>
        /// <returns>The job response returned from the service</returns>
        public BaseRecoveryServicesJobResponse EnableProtection()
        {
            string azureVMName              = (string)ProviderData[ItemParams.AzureVMName];
            string azureVMCloudServiceName  = (string)ProviderData[ItemParams.AzureVMCloudServiceName];
            string azureVMResourceGroupName = (string)ProviderData[ItemParams.AzureVMResourceGroupName];
            string parameterSetName         = (string)ProviderData[ItemParams.ParameterSetName];

            PolicyBase policy = (PolicyBase)
                                ProviderData[ItemParams.Policy];

            ItemBase itemBase = (ItemBase)
                                ProviderData[ItemParams.Item];

            AzureVmItem item = (AzureVmItem)
                               ProviderData[ItemParams.Item];
            // do validations

            string containerUri     = "";
            string protectedItemUri = "";
            bool   isComputeAzureVM = false;
            string sourceResourceId = null;

            if (itemBase == null)
            {
                isComputeAzureVM = string.IsNullOrEmpty(azureVMCloudServiceName) ? true : false;
                string azureVMRGName = (isComputeAzureVM) ?
                                       azureVMResourceGroupName : azureVMCloudServiceName;

                ValidateAzureVMWorkloadType(policy.WorkloadType);

                ValidateAzureVMEnableProtectionRequest(
                    azureVMName,
                    azureVMCloudServiceName,
                    azureVMResourceGroupName,
                    policy);

                ProtectableObjectResource protectableObjectResource =
                    GetAzureVMProtectableObject(azureVMName, azureVMRGName, isComputeAzureVM);

                Dictionary <UriEnums, string> keyValueDict =
                    HelperUtils.ParseUri(protectableObjectResource.Id);
                containerUri     = HelperUtils.GetContainerUri(keyValueDict, protectableObjectResource.Id);
                protectedItemUri = HelperUtils.GetProtectableItemUri(keyValueDict, protectableObjectResource.Id);

                AzureIaaSVMProtectableItem iaasVmProtectableItem = (AzureIaaSVMProtectableItem)protectableObjectResource.Properties;
                if (iaasVmProtectableItem != null)
                {
                    sourceResourceId = iaasVmProtectableItem.VirtualMachineId;
                }
            }
            else
            {
                ValidateAzureVMWorkloadType(item.WorkloadType, policy.WorkloadType);
                ValidateAzureVMModifyProtectionRequest(itemBase, policy);

                isComputeAzureVM = IsComputeAzureVM(item.VirtualMachineId);
                Dictionary <UriEnums, string> keyValueDict = HelperUtils.ParseUri(item.Id);
                containerUri     = HelperUtils.GetContainerUri(keyValueDict, item.Id);
                protectedItemUri = HelperUtils.GetProtectedItemUri(keyValueDict, item.Id);
                sourceResourceId = item.SourceResourceId;
            }

            // construct Service Client protectedItem request

            AzureIaaSVMProtectedItem properties;

            if (isComputeAzureVM == false)
            {
                properties = new AzureIaaSClassicComputeVMProtectedItem();
            }
            else
            {
                properties = new AzureIaaSComputeVMProtectedItem();
            }

            properties.PolicyId         = policy.Id;
            properties.SourceResourceId = sourceResourceId;

            ProtectedItemCreateOrUpdateRequest serviceClientRequest = new ProtectedItemCreateOrUpdateRequest()
            {
                Item = new ProtectedItemResource()
                {
                    Properties = properties,
                }
            };

            return(ServiceClientAdapter.CreateOrUpdateProtectedItem(
                       containerUri,
                       protectedItemUri,
                       serviceClientRequest));
        }
        public List <ProtectedItemResource> ListProtectedItemsByContainer(
            string vaultName,
            string resourceGroupName,
            CmdletModel.ContainerBase container,
            CmdletModel.PolicyBase policy,
            string backupManagementType,
            string dataSourceType,
            bool UseSecondaryRegion = false)
        {
            ODataQuery <ProtectedItemQueryObject> queryParams = policy != null ?
                                                                new ODataQuery <ProtectedItemQueryObject>(
                q => q.BackupManagementType
                == backupManagementType &&
                q.ItemType == dataSourceType &&
                q.PolicyName == policy.Name) :
                                                                new ODataQuery <ProtectedItemQueryObject>(
                q => q.BackupManagementType
                == backupManagementType &&
                q.ItemType == dataSourceType);

            List <ProtectedItemResource> protectedItems = new List <ProtectedItemResource>();
            string skipToken = null;

            // fetching backup items from secondary region
            if (UseSecondaryRegion)
            {
                var listResponse = ServiceClientAdapter.ListCrrProtectedItem(
                    queryParams,
                    skipToken,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);
                protectedItems.AddRange(listResponse);
            }
            else
            {
                var listResponse = ServiceClientAdapter.ListProtectedItem(
                    queryParams,
                    skipToken,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);
                protectedItems.AddRange(listResponse);
            }

            if (container != null)
            {
                protectedItems = protectedItems.Where(protectedItem =>
                {
                    Dictionary <CmdletModel.UriEnums, string> dictionary = HelperUtils.ParseUri(protectedItem.Id);
                    string containerUri = HelperUtils.GetContainerUri(dictionary, protectedItem.Id);

                    var delimIndex       = containerUri.IndexOf(';');
                    string containerName = null;
                    if (string.Compare(protectedItem.Properties.BackupManagementType,
                                       ServiceClientModel.BackupManagementType.AzureWorkload) == 0)
                    {
                        containerName = containerUri;
                    }
                    else
                    {
                        containerName = containerUri.Substring(delimIndex + 1);
                    }
                    return(containerName.ToLower().Equals(container.Name.ToLower()));
                }).ToList();
            }

            return(protectedItems);
        }