public override void ExecuteCmdlet() { DatabaseAccountGetResults databaseAccountGetResults = null; try { databaseAccountGetResults = CosmosDBManagementClient.DatabaseAccounts.Get(ResourceGroupName, Name); } catch (CloudException e) { if (e.Response.StatusCode != System.Net.HttpStatusCode.NotFound) { throw; } } if (databaseAccountGetResults != null) { throw new ConflictingResourceException(message: string.Format(ExceptionMessage.Conflict, Name)); } ConsistencyPolicy consistencyPolicy = base.PopoulateConsistencyPolicy(DefaultConsistencyLevel, MaxStalenessIntervalInSeconds, MaxStalenessPrefix); string writeLocation = null; Collection <Location> LocationCollection = new Collection <Location>(); if (Location != null && Location.Length > 0) { int failoverPriority = 0; foreach (string l in Location) { Location loc = new Location(locationName: l, failoverPriority: failoverPriority); LocationCollection.Add(loc); if (failoverPriority == 0) { writeLocation = l; } failoverPriority++; } } else if (LocationObject != null && LocationObject.Length > 0) { if (writeLocation != null) { WriteWarning("Cannot accept Location and LocationObject simultaneously as parameters"); return; } foreach (PSLocation psLocation in LocationObject) { LocationCollection.Add(PSLocation.ToSDKModel(psLocation)); if (psLocation.FailoverPriority == 0) { writeLocation = psLocation.LocationName; } } } Dictionary <string, string> tags = new Dictionary <string, string>(); if (Tag != null) { tags = base.PopulateTags(Tag); } Collection <VirtualNetworkRule> virtualNetworkRule = new Collection <VirtualNetworkRule>(); if (VirtualNetworkRule != null && VirtualNetworkRule.Length > 0) { foreach (string id in VirtualNetworkRule) { virtualNetworkRule.Add(new VirtualNetworkRule(id: id)); } } if (VirtualNetworkRuleObject != null && VirtualNetworkRuleObject.Length > 0) { foreach (PSVirtualNetworkRule psVirtualNetworkRule in VirtualNetworkRuleObject) { virtualNetworkRule.Add(PSVirtualNetworkRule.ToSDKModel(psVirtualNetworkRule)); } } DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters(locations: LocationCollection, location: writeLocation, name: Name, tags: tags); if (FromPointInTimeBackup) { PSRestoreParameters restoreParameters = restoreContext.GetRestoreParameters(CosmosDBManagementClient); if (restoreParameters == null) { WriteWarning("Please provide valid parameters to restore"); return; } databaseAccountCreateUpdateParameters.CreateMode = CreateMode.Restore; databaseAccountCreateUpdateParameters.RestoreParameters = restoreParameters.ToSDKModel(); } databaseAccountCreateUpdateParameters.ConsistencyPolicy = consistencyPolicy; databaseAccountCreateUpdateParameters.EnableMultipleWriteLocations = EnableMultipleWriteLocations; databaseAccountCreateUpdateParameters.IsVirtualNetworkFilterEnabled = EnableVirtualNetwork; databaseAccountCreateUpdateParameters.EnableAutomaticFailover = EnableAutomaticFailover; databaseAccountCreateUpdateParameters.VirtualNetworkRules = virtualNetworkRule; databaseAccountCreateUpdateParameters.DisableKeyBasedMetadataWriteAccess = DisableKeyBasedMetadataWriteAccess; databaseAccountCreateUpdateParameters.PublicNetworkAccess = PublicNetworkAccess; databaseAccountCreateUpdateParameters.EnableFreeTier = EnableFreeTier; databaseAccountCreateUpdateParameters.EnableAnalyticalStorage = EnableAnalyticalStorage; Collection <string> networkAclBypassResourceId = NetworkAclBypassResourceId != null ? new Collection <string>(NetworkAclBypassResourceId) : new Collection <string>(); databaseAccountCreateUpdateParameters.NetworkAclBypassResourceIds = networkAclBypassResourceId; if (IpRule != null && IpRule.Length > 0) { databaseAccountCreateUpdateParameters.IpRules = base.PopulateIpRules(IpRule); } if (KeyVaultKeyUri != null) { databaseAccountCreateUpdateParameters.KeyVaultKeyUri = KeyVaultKeyUri; } if (NetworkAclBypass != null) { databaseAccountCreateUpdateParameters.NetworkAclBypass = NetworkAclBypass == "AzureServices" ? SDKModel.NetworkAclBypass.AzureServices : SDKModel.NetworkAclBypass.None; } if (!string.IsNullOrEmpty(ApiKind)) { if (ApiKind.Equals("MongoDB", StringComparison.OrdinalIgnoreCase)) { if (ServerVersion != null) { databaseAccountCreateUpdateParameters.ApiProperties = new ApiProperties { ServerVersion = ServerVersion }; } } else { switch (ApiKind) { case "Cassandra": databaseAccountCreateUpdateParameters.Capabilities = new List <Capability> { new Capability { Name = "EnableCassandra" } }; break; case "Gremlin": databaseAccountCreateUpdateParameters.Capabilities = new List <Capability> { new Capability { Name = "EnableGremlin" } }; break; case "Table": databaseAccountCreateUpdateParameters.Capabilities = new List <Capability> { new Capability { Name = "EnableTable" } }; break; case "Sql": break; } ApiKind = null; } } else { ApiKind = "GlobalDocumentDB"; } databaseAccountCreateUpdateParameters.Kind = ApiKind; if (!string.IsNullOrEmpty(BackupPolicyType)) { PSBackupPolicy backupPolicy = new PSBackupPolicy() { BackupType = BackupPolicyType, BackupIntervalInMinutes = BackupIntervalInMinutes, BackupRetentionIntervalInHours = BackupRetentionIntervalInHours, BackupStorageRedundancy = BackupStorageRedundancy }; if (BackupPolicyType.Equals(PSBackupPolicy.ContinuousModeBackupType, StringComparison.OrdinalIgnoreCase) && (BackupIntervalInMinutes.HasValue || BackupRetentionIntervalInHours.HasValue)) { WriteWarning("Cannot accept BackupInterval or BackupRetention parameters for ContinuousModeBackupType"); return; } databaseAccountCreateUpdateParameters.BackupPolicy = backupPolicy.ToSDKModel(); } else if (BackupIntervalInMinutes.HasValue || BackupRetentionIntervalInHours.HasValue || !string.IsNullOrEmpty(BackupStorageRedundancy)) { databaseAccountCreateUpdateParameters.BackupPolicy = new PeriodicModeBackupPolicy() { PeriodicModeProperties = new PeriodicModeProperties() { BackupIntervalInMinutes = BackupIntervalInMinutes, BackupRetentionIntervalInHours = BackupRetentionIntervalInHours, BackupStorageRedundancy = BackupStorageRedundancy } }; } // Update analytical storage schema type. databaseAccountCreateUpdateParameters.AnalyticalStorageConfiguration = CreateAnalyticalStorageConfiguration(AnalyticalStorageSchemaType); if (ShouldProcess(Name, "Creating Database Account")) { DatabaseAccountGetResults cosmosDBAccount = CosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(ResourceGroupName, Name, databaseAccountCreateUpdateParameters).GetAwaiter().GetResult().Body; WriteObject(new PSDatabaseAccountGetResults(cosmosDBAccount)); } return; }
public override void ExecuteCmdlet() { DateTime utcRestoreDateTime; if (RestoreTimestampInUtc.Kind == DateTimeKind.Unspecified) { utcRestoreDateTime = RestoreTimestampInUtc; } else { utcRestoreDateTime = RestoreTimestampInUtc.ToUniversalTime(); } // Fail if provided restoretimesamp is greater than current timestamp if (utcRestoreDateTime > DateTime.UtcNow) { WriteWarning($"Restore timestamp {utcRestoreDateTime} should be less than current timestamp {DateTime.UtcNow}"); return; } bool isSourceRestorableAccountDeleted = false; List <RestorableDatabaseAccountGetResult> restorableDatabaseAccounts = CosmosDBManagementClient.RestorableDatabaseAccounts.ListWithHttpMessagesAsync().GetAwaiter().GetResult().Body.ToList(); RestorableDatabaseAccountGetResult sourceAccountToRestore = null; List <RestorableDatabaseAccountGetResult> accountsWithMatchingName = restorableDatabaseAccounts.Where(databaseAccount => databaseAccount.AccountName.Equals(SourceDatabaseAccountName, StringComparison.OrdinalIgnoreCase)).ToList(); if (accountsWithMatchingName.Count > 0) { foreach (RestorableDatabaseAccountGetResult restorableAccount in accountsWithMatchingName) { if (restorableAccount.CreationTime.HasValue && restorableAccount.CreationTime < utcRestoreDateTime) { if (!restorableAccount.DeletionTime.HasValue || restorableAccount.DeletionTime > utcRestoreDateTime) { sourceAccountToRestore = restorableAccount; isSourceRestorableAccountDeleted = true; break; } } } } if (sourceAccountToRestore == null) { WriteWarning($"No database accounts found with matching account name {SourceDatabaseAccountName} that was alive at given utc-timestamp {utcRestoreDateTime}"); return; } // Validate if source account is empty if the source account is a live account. if (!isSourceRestorableAccountDeleted) { IEnumerable <DatabaseRestoreResource> restorableResources = null; if (sourceAccountToRestore.ApiType.Equals("Sql", StringComparison.OrdinalIgnoreCase)) { try { restorableResources = CosmosDBManagementClient.RestorableSqlResources.ListWithHttpMessagesAsync( sourceAccountToRestore.Location, sourceAccountToRestore.Name, Location, utcRestoreDateTime.ToString()).GetAwaiter().GetResult().Body; } catch (Exception) { WriteWarning($"No database accounts found with matching account name {SourceDatabaseAccountName} that was alive at given utc-timestamp {utcRestoreDateTime} in location {Location}"); return; } } else if (sourceAccountToRestore.ApiType.Equals("MongoDB", StringComparison.OrdinalIgnoreCase)) { try { restorableResources = CosmosDBManagementClient.RestorableMongodbResources.ListWithHttpMessagesAsync( sourceAccountToRestore.Location, sourceAccountToRestore.Name, Location, utcRestoreDateTime.ToString()).GetAwaiter().GetResult().Body; } catch (Exception) { WriteWarning($"No database accounts found with matching account name {SourceDatabaseAccountName} that was alive at given utc-timestamp {utcRestoreDateTime} in location {Location}"); return; } } else { WriteWarning($"Provided API Type {sourceAccountToRestore.ApiType} is not supported"); return; } if (restorableResources == null || !restorableResources.Any()) { WriteWarning($"Database account {SourceDatabaseAccountName} contains no restorable resources in location {Location} at given restore timestamp {utcRestoreDateTime} in location {Location}"); return; } } // Trigger restore PSRestoreParameters restoreParameters = new PSRestoreParameters() { RestoreSource = sourceAccountToRestore.Id, RestoreTimestampInUtc = utcRestoreDateTime, DatabasesToRestore = DatabasesToRestore }; Collection <Location> LocationCollection = new Collection <Location>(); Location loc = new Location(locationName: Location, failoverPriority: 0); LocationCollection.Add(loc); string apiKind = "GlobalDocumentDB"; if (sourceAccountToRestore.ApiType.Equals("MongoDB", StringComparison.OrdinalIgnoreCase)) { apiKind = "MongoDB"; } DatabaseAccountCreateUpdateParameters databaseAccountCreateUpdateParameters = new DatabaseAccountCreateUpdateParameters(locations: LocationCollection, location: sourceAccountToRestore.Location, name: TargetDatabaseAccountName) { Kind = apiKind, CreateMode = CreateMode.Restore, RestoreParameters = restoreParameters.ToSDKModel() }; if (ShouldProcess(TargetDatabaseAccountName, string.Format( "Creating Database Account by restoring Database Account with Name {0} and restorable database account Id {1} to the timestamp {2}", SourceDatabaseAccountName, sourceAccountToRestore.Id, RestoreTimestampInUtc))) { DatabaseAccountGetResults cosmosDBAccount = CosmosDBManagementClient.DatabaseAccounts.CreateOrUpdateWithHttpMessagesAsync(TargetResourceGroupName, TargetDatabaseAccountName, databaseAccountCreateUpdateParameters).GetAwaiter().GetResult().Body; WriteObject(new PSDatabaseAccountGetResults(cosmosDBAccount)); } return; }