示例#1
0
        public void FailoverReadableSecondaryInstance()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                var             rg = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                ManagedInstance managedInstance = context.CreateManagedInstance(rg);
                Assert.NotNull(managedInstance);
                var resourceGroupName = rg.Name;

                // Wait for first full backup to finish
                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    Thread.Sleep(TimeSpan.FromMinutes(6));
                }
                try
                {
                    sqlClient.ManagedInstances.Failover(resourceGroupName, managedInstance.Name, ReplicaType.ReadableSecondary);
                }
                catch (Exception ex)
                {
                    Assert.Contains("failover is not supported", ex.Message);
                }
            }
        }
示例#2
0
        public async void TestCreateUpdateGetDeleteDatabaseVulnerabilityAssessmentBaselines()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                string testPrefix = "sqlvulnerabilityassessmentbaselinetest-";

                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                var resourceGroup             = context.CreateResourceGroup();
                var managedInstance           = context.CreateManagedInstance(resourceGroup);

                // Create managed database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
                var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(db1);

                // Set policy
                await SetPolicy(context, sqlClient, resourceGroup, managedInstance, dbName);

                // Test baseline for database level rule
                ValidateBaselineRule(sqlClient, resourceGroup, managedInstance, dbName, isServerLevelRule: true);

                // Test baseline for server level rule
                ValidateBaselineRule(sqlClient, resourceGroup, managedInstance, dbName, isServerLevelRule: false);
            }
        }
示例#3
0
        public async void TestExportDatabaseVulnerabilityAssessmentScans()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                string testPrefix = "sqlvulnerabilityassessmentexportscantest-";

                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                var resourceGroup             = context.CreateResourceGroup();
                var managedInstance           = context.CreateManagedInstance(resourceGroup);

                // Create managed database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
                var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(db1);

                // Set policy
                await SetPolicy(context, sqlClient, resourceGroup, managedInstance, dbName);

                // Run some scans
                string scanId = string.Format("scan1_{0}", testPrefix);
                sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.InitiateScan(resourceGroup.Name, managedInstance.Name, dbName, scanId);
                sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.Export(resourceGroup.Name, managedInstance.Name, dbName, scanId);
            }
        }
        public async void TestCreateUpdateGetManagedInstanceVulnerabilityAssessments()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                var resourceGroup             = context.CreateResourceGroup();
                var managedInstance           = context.CreateManagedInstance(resourceGroup);

                // Verify Policy is empty to begin with
                ManagedInstanceVulnerabilityAssessment policyThatWasReceived = sqlClient.ManagedInstanceVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name);
                Assert.Null(policyThatWasReceived.StorageContainerPath);
                Assert.Null(policyThatWasReceived.StorageAccountAccessKey);
                Assert.False(policyThatWasReceived.RecurringScans.IsEnabled);

                // Set policy and then get policy and verify correctness
                ManagedInstanceVulnerabilityAssessment policyThatWasSet = await SetPolicy(context, sqlClient, resourceGroup, managedInstance);

                policyThatWasReceived = sqlClient.ManagedInstanceVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name);
                Assert.Equal(policyThatWasSet.StorageContainerPath, policyThatWasReceived.StorageContainerPath);
                Assert.Null(policyThatWasSet.StorageAccountAccessKey);
                Assert.Equal(policyThatWasSet.RecurringScans.IsEnabled, policyThatWasReceived.RecurringScans.IsEnabled);
                SqlManagementTestUtilities.AssertCollection(policyThatWasSet.RecurringScans.Emails, policyThatWasReceived.RecurringScans.Emails);
                Assert.Equal(policyThatWasSet.RecurringScans.EmailSubscriptionAdmins, policyThatWasReceived.RecurringScans.EmailSubscriptionAdmins);

                // Delete policy and then get policy and verify correctness
                sqlClient.ManagedInstanceVulnerabilityAssessments.Delete(resourceGroup.Name, managedInstance.Name);

                // Get policy after deletion
                policyThatWasReceived = sqlClient.ManagedInstanceVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name);
                Assert.Null(policyThatWasReceived.StorageContainerPath);
                Assert.Null(policyThatWasReceived.StorageAccountAccessKey);
                Assert.False(policyThatWasReceived.RecurringScans.IsEnabled);
            }
        }
示例#5
0
 private void createManagedInstances(SqlManagementTestContext context, ResourceGroup resourceGroup, IList <string> managedInstanceNames)
 {
     foreach (string miName in managedInstanceNames)
     {
         ManagedInstance managedInstance = context.CreateManagedInstance(resourceGroup, miName);
         Assert.NotNull(managedInstance);
     }
 }
示例#6
0
        public void TestUpdateEncryptionProtector()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient      sqlClient      = context.GetClient <SqlManagementClient>();
                ResourceManagementClient resourceClient = context.GetClient <ResourceManagementClient>();
                ResourceGroup            resourceGroup  = context.CreateResourceGroup();
                string resourceGroupName = resourceGroup.Name;

                ManagedInstance managedInstance = context.CreateManagedInstance(resourceGroup, new ManagedInstance()
                {
                    Identity = new ResourceIdentity()
                    {
                        Type = IdentityType.SystemAssignedUserAssigned,
                        UserAssignedIdentities = ManagedInstanceTestUtilities.UserIdentity
                    },
                    PrimaryUserAssignedIdentityId = ManagedInstanceTestUtilities.UAMI
                });
                managedInstance = sqlClient.ManagedInstances.Get(resourceGroupName, managedInstance.Name);

                var keyBundle = SqlManagementTestUtilities.CreateKeyVaultKeyWithManagedInstanceAccess(context, resourceGroup, managedInstance);

                // Create server key
                string serverKeyName      = SqlManagementTestUtilities.GetServerKeyNameFromKeyBundle(keyBundle);
                string serverKeyUri       = keyBundle.Key.Kid;
                var    managedInstanceKey = sqlClient.ManagedInstanceKeys.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, serverKeyName, new ManagedInstanceKey()
                {
                    ServerKeyType = "AzureKeyVault",
                    Uri           = serverKeyUri
                });
                SqlManagementTestUtilities.ValidateManagedInstanceKey(managedInstanceKey, serverKeyName, "AzureKeyVault", serverKeyUri);

                // Update to Key Vault
                sqlClient.ManagedInstanceEncryptionProtectors.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, new ManagedInstanceEncryptionProtector()
                {
                    ServerKeyName = serverKeyName,
                    ServerKeyType = "AzureKeyVault"
                });

                ManagedInstanceEncryptionProtector encProtector1 = sqlClient.ManagedInstanceEncryptionProtectors.Get(resourceGroup.Name, managedInstance.Name);
                Assert.Equal("AzureKeyVault", encProtector1.ServerKeyType);
                Assert.Equal(serverKeyName, encProtector1.ServerKeyName);

                // Update to Service Managed
                sqlClient.ManagedInstanceEncryptionProtectors.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, new ManagedInstanceEncryptionProtector()
                {
                    ServerKeyName = "ServiceManaged",
                    ServerKeyType = "ServiceManaged"
                });

                ManagedInstanceEncryptionProtector encProtector2 = sqlClient.ManagedInstanceEncryptionProtectors.Get(resourceGroup.Name, managedInstance.Name);
                Assert.Equal("ServiceManaged", encProtector2.ServerKeyType);
                Assert.Equal("ServiceManaged", encProtector2.ServerKeyName);
            }
        }
        public void TestEndpointCertificates()
        {
            string suiteName = this.GetType().Name;

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                // Test setup (rg, mi):
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                //ResourceGroup rg = new ResourceGroup(location: "eastus2euap", id: "/subscriptions/8313371e-0879-428e-b1da-6353575a9192/resourceGroups/CustomerExperienceTeam_RG", name: "CustomerExperienceTeam_RG");
                //ManagedInstance managedInstance = sqlClient.ManagedInstances.Get(rg.Name, "chimera-ps-cli-v2");
                ResourceGroup   rg = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                ManagedInstance managedInstance = context.CreateManagedInstance(rg);
                Assert.NotNull(managedInstance);

                var resourceGroupName   = rg.Name;
                var managedInstanceName = managedInstance.Name;

                var exceptionGet = Assert.Throws <CloudException>(() => sqlClient.EndpointCertificates.Get(resourceGroupName, managedInstanceName, "invalid_endpoint_type"));
                Assert.Equal("ResourceNotFound", exceptionGet.Body.Code);

                var certServiceBroker = sqlClient.EndpointCertificates.Get(resourceGroupName, managedInstanceName, endpointTypeServiceBroker);
                Assert.NotNull(certServiceBroker);
                Assert.NotNull(certServiceBroker.PublicBlob);
                Assert.True(Regex.Match(certServiceBroker.PublicBlob, @"^[0-9a-fA-F]+$").Success);
                Assert.Equal(endpointTypeServiceBroker, certServiceBroker.Name);
                Assert.Equal(makeEndpointCertID(managedInstance.Id, endpointTypeServiceBroker), certServiceBroker.Id);
                Assert.Equal(endpointCertType, certServiceBroker.Type);

                var certDatabaseMirroring = sqlClient.EndpointCertificates.Get(resourceGroupName, managedInstanceName, endpointTypeDatabaseMirroring);
                Assert.NotNull(certDatabaseMirroring);
                Assert.NotNull(certDatabaseMirroring.PublicBlob);
                Assert.True(Regex.Match(certDatabaseMirroring.PublicBlob, @"^[0-9a-fA-F]+$").Success);
                Assert.Equal(endpointTypeDatabaseMirroring, certDatabaseMirroring.Name);
                Assert.Equal(makeEndpointCertID(managedInstance.Id, endpointTypeDatabaseMirroring), certDatabaseMirroring.Id);
                Assert.Equal(endpointCertType, certDatabaseMirroring.Type);

                var certList = sqlClient.EndpointCertificates.ListByInstance(resourceGroupName, managedInstanceName);
                Assert.NotNull(certList);
                var listCertDBM = certList.Where(cert => cert.Name.Equals(endpointTypeDatabaseMirroring)).FirstOrDefault();
                var listCertSB  = certList.Where(cert => cert.Name.Equals(endpointTypeServiceBroker)).FirstOrDefault();
                Assert.NotNull(listCertDBM.PublicBlob);
                Assert.True(Regex.Match(listCertDBM.PublicBlob, @"^[0-9a-fA-F]+$").Success);
                Assert.Equal(endpointTypeDatabaseMirroring, listCertDBM.Name);
                Assert.Equal(makeEndpointCertID(managedInstance.Id, endpointTypeDatabaseMirroring), listCertDBM.Id);
                Assert.Equal(endpointCertType, listCertDBM.Type);
                Assert.NotNull(listCertSB.PublicBlob);
                Assert.True(Regex.Match(listCertSB.PublicBlob, @"^[0-9a-fA-F]+$").Success);
                Assert.Equal(endpointTypeServiceBroker, listCertSB.Name);
                Assert.Equal(makeEndpointCertID(managedInstance.Id, endpointTypeServiceBroker), listCertSB.Id);
                Assert.Equal(endpointCertType, listCertSB.Type);
            }
        }
示例#8
0
        public async void TestExecuteGetListDatabaseVulnerabilityAssessmentScans()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                string testPrefix = "sqlvulnerabilityassessmentscantest-";

                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                var resourceGroup             = context.CreateResourceGroup();
                var managedInstance           = context.CreateManagedInstance(resourceGroup);

                // Create managed database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
                var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(db1);

                // Set policy
                await SetPolicy(context, sqlClient, resourceGroup, managedInstance, dbName);

                // Run some scans
                string scanId = string.Format("scantest1_{0}", testPrefix);
                sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.InitiateScan(resourceGroup.Name, managedInstance.Name, dbName, scanId);

                string scanId1 = string.Format("scantest2_{0}", testPrefix);
                sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.InitiateScan(resourceGroup.Name, managedInstance.Name, dbName, scanId1);

                // Verify get scan and list scans
                VulnerabilityAssessmentScanRecord scanRecord = sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.Get(resourceGroup.Name, managedInstance.Name, dbName, scanId);
                Assert.Equal(scanId, scanRecord.ScanId);

                IPage <VulnerabilityAssessmentScanRecord> scanRecords = sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.ListByDatabase(resourceGroup.Name, managedInstance.Name, dbName);
                Assert.Equal(2, scanRecords.ToList().Count);
                Assert.Contains(scanRecords.ToList(), item => item.ScanId == scanId);
                Assert.Contains(scanRecords.ToList(), item => item.ScanId == scanId1);

                VulnerabilityAssessmentScanRecord scanId1Record         = sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.Get(resourceGroup.Name, managedInstance.Name, dbName, scanId1);
                VulnerabilityAssessmentScanRecord scanId1RecordFromList = scanRecords.FirstOrDefault(item => item.ScanId == scanId1);
                Assert.Equal(scanId1Record.ScanId, scanId1RecordFromList.ScanId);
                Assert.Equal(scanId1Record.TriggerType, scanId1RecordFromList.TriggerType);
                Assert.Equal(scanId1Record.State, scanId1RecordFromList.State);
                Assert.Equal(scanId1Record.StartTime, scanId1RecordFromList.StartTime);
                Assert.Equal(scanId1Record.EndTime, scanId1RecordFromList.EndTime);
                Assert.Equal(scanId1Record.Errors, scanId1RecordFromList.Errors);
                Assert.Equal(scanId1Record.StorageContainerPath, scanId1RecordFromList.StorageContainerPath);
                Assert.Equal(scanId1Record.NumberOfFailedSecurityChecks, scanId1RecordFromList.NumberOfFailedSecurityChecks);
            }
        }
        public void TestCreateUpdateDropManagedInstanceKeys()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient      sqlClient      = context.GetClient <SqlManagementClient>();
                ResourceManagementClient resourceClient = context.GetClient <ResourceManagementClient>();
                var             resourceGroup           = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                ManagedInstance managedInstance         = context.CreateManagedInstance(resourceGroup, new ManagedInstance()
                {
                    Identity = new ResourceIdentity()
                    {
                        Type = IdentityType.SystemAssignedUserAssigned,
                        UserAssignedIdentities = ManagedInstanceTestUtilities.UserIdentity,
                    },
                    PrimaryUserAssignedIdentityId = ManagedInstanceTestUtilities.UAMI
                });

                var    keyBundle          = SqlManagementTestUtilities.CreateKeyVaultKeyWithManagedInstanceAccess(context, resourceGroup, managedInstance);
                string serverKeyName      = SqlManagementTestUtilities.GetServerKeyNameFromKeyBundle(keyBundle);
                string keyUri             = keyBundle.Key.Kid;
                var    managedInstanceKey = sqlClient.ManagedInstanceKeys.CreateOrUpdate(
                    resourceGroupName: resourceGroup.Name,
                    managedInstanceName: managedInstance.Name,
                    keyName: serverKeyName,
                    parameters: new ManagedInstanceKey()
                {
                    ServerKeyType = "AzureKeyVault",
                    Uri           = keyUri
                });

                SqlManagementTestUtilities.ValidateManagedInstanceKey(managedInstanceKey, serverKeyName, "AzureKeyVault", keyUri);


                // Validate key exists by getting key
                var key1 = sqlClient.ManagedInstanceKeys.Get(
                    resourceGroupName: resourceGroup.Name,
                    managedInstanceName: managedInstance.Name,
                    keyName: serverKeyName);

                SqlManagementTestUtilities.ValidateManagedInstanceKey(key1, serverKeyName, "AzureKeyVault", keyUri);

                // Validate key exists by listing keys
                var keyList = sqlClient.ManagedInstanceKeys.ListByInstance(
                    resourceGroupName: resourceGroup.Name,
                    managedInstanceName: managedInstance.Name);

                Assert.True(keyList.Count() > 0);
            }
        }
示例#10
0
        public ManagedInstanceTestFixture()
        {
            Context = new SqlManagementTestContext(this);

            try
            {
                SqlManagementClient sqlClient = Context.GetClient <SqlManagementClient>();

                ResourceGroup   = Context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                ManagedInstance = Context.CreateManagedInstance(ResourceGroup);
            }
            catch (Exception ex)
            {
                Context.Dispose();
            }
        }
        public void TestGetAndListManagedDatabase()
        {
            string testPrefix = "sqlcrudtest-";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                var resourceGroup   = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                var managedInstance = context.CreateManagedInstance(resourceGroup);

                // Create some small databases to run the get/List tests on.
                ManagedDatabase[] mngdDatabases = SqlManagementTestUtilities.CreateManagedDatabasesAsync(
                    sqlClient, resourceGroup.Name, managedInstance, testPrefix, 4).Result;

                // Organize into a dictionary for better lookup later
                IDictionary <string, ManagedDatabase> inputs = mngdDatabases.ToDictionary(
                    keySelector: d => d.Name,
                    elementSelector: d => d);

                // Get each database and compare to the results of create database
                //
                foreach (var db in inputs)
                {
                    var response = sqlClient.ManagedDatabases.Get(resourceGroup.Name, managedInstance.Name, db.Key);
                    SqlManagementTestUtilities.ValidateManagedDatabaseEx(db.Value, response);
                }

                // List all databases
                //
                var listResponse = sqlClient.ManagedDatabases.ListByInstance(resourceGroup.Name, managedInstance.Name);

                // Check that all created Managed Databases are created
                foreach (var db in inputs.Keys)
                {
                    var actualDbList = listResponse.Where(d => d.Name.Equals(db));
                    Assert.True(actualDbList.Count() == 1);
                    ManagedDatabase actualDb = actualDbList.FirstOrDefault();
                    SqlManagementTestUtilities.ValidateManagedDatabase(inputs[db], actualDb, db);
                }

                foreach (var db in inputs.Keys)
                {
                    sqlClient.ManagedDatabases.Delete(resourceGroup.Name, managedInstance.Name, db);
                }
            }
        }
示例#12
0
        public async void TestCreateUpdateGetDatabaseVulnerabilityAssessments()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                string testPrefix = "sqlvulnerabilityassessmentcrudtest-";

                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                var resourceGroup             = context.CreateResourceGroup();
                var managedInstance           = context.CreateManagedInstance(resourceGroup);

                // Create managed database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
                var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(db1);

                // Verify Policy is empty to begin with
                DatabaseVulnerabilityAssessment policyThatWasReceived = sqlClient.ManagedDatabaseVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name, dbName);
                Assert.Null(policyThatWasReceived.StorageContainerPath);
                Assert.Null(policyThatWasReceived.StorageContainerSasKey);
                Assert.False(policyThatWasReceived.RecurringScans.IsEnabled);

                // Set policy and then get policy and verify correctness
                DatabaseVulnerabilityAssessment policyThatWasSet = await SetPolicy(context, sqlClient, resourceGroup, managedInstance, dbName);

                policyThatWasReceived = sqlClient.ManagedDatabaseVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name, dbName);
                Assert.Equal(policyThatWasSet.StorageContainerPath, policyThatWasReceived.StorageContainerPath);
                Assert.Null(policyThatWasSet.StorageContainerSasKey);
                Assert.Equal(policyThatWasSet.RecurringScans.IsEnabled, policyThatWasReceived.RecurringScans.IsEnabled);
                SqlManagementTestUtilities.AssertCollection(policyThatWasSet.RecurringScans.Emails, policyThatWasReceived.RecurringScans.Emails);
                Assert.Equal(policyThatWasSet.RecurringScans.EmailSubscriptionAdmins, policyThatWasReceived.RecurringScans.EmailSubscriptionAdmins);

                // Delete policy and then get policy and verify correctness
                sqlClient.ManagedDatabaseVulnerabilityAssessments.Delete(resourceGroup.Name, managedInstance.Name, dbName);

                // Get policy after deletion
                policyThatWasReceived = sqlClient.ManagedDatabaseVulnerabilityAssessments.Get(resourceGroup.Name, managedInstance.Name, dbName);
                Assert.Null(policyThatWasReceived.StorageContainerPath);
                Assert.Null(policyThatWasReceived.StorageContainerSasKey);
                Assert.False(policyThatWasReceived.RecurringScans.IsEnabled);
            }
        }
        public void TestCreateDropManagedDatabase()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                // Update with values from a current MI on the region
                //
                var resourceGroup = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);

                //Get MI
                var managedInstance = context.CreateManagedInstance(resourceGroup);

                Dictionary <string, string> tags = new Dictionary <string, string>()
                {
                    { "tagKey1", "TagValue1" }
                };

                // Create database only required parameters
                //
                string mdbName = SqlManagementTestUtilities.GenerateName();
                var    mdb1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, mdbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(mdb1);

                // Create a database with all parameters specified
                //
                mdbName = SqlManagementTestUtilities.GenerateName();
                var mdb2Input = new ManagedDatabase()
                {
                    Location   = managedInstance.Location,
                    Collation  = SqlTestConstants.DefaultCollation,
                    Tags       = tags,
                    CreateMode = "Default"
                };
                var mdb2 = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, mdbName, mdb2Input);
                Assert.NotNull(mdb2);
                SqlManagementTestUtilities.ValidateManagedDatabase(mdb2Input, mdb2, mdbName);

                sqlClient.ManagedDatabases.Delete(resourceGroup.Name, managedInstance.Name, mdb1.Name);
                sqlClient.ManagedDatabases.Delete(resourceGroup.Name, managedInstance.Name, mdb2.Name);
            }
        }
示例#14
0
        public void ShortTermRetentionOnLiveDatabase()
        {
            using (SqlManagementTestContext Context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient       = Context.GetClient <SqlManagementClient>();
                ResourceGroup       resourceGroup   = Context.CreateResourceGroup();
                ManagedInstance     managedInstance = Context.CreateManagedInstance(resourceGroup);

                // Create managed database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(_testPrefix);
                var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(db1);

                int basicRetention = 7;
                int smallValue     = 3;
                int validValue     = 20;

                // Attempt to increase retention period to 7 days and verfiy that the operation succeeded.
                ManagedBackupShortTermRetentionPolicy parameters0 = new ManagedBackupShortTermRetentionPolicy(retentionDays: basicRetention);
                sqlClient.ManagedBackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, managedInstance.Name, dbName, parameters0);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                ManagedBackupShortTermRetentionPolicy policy = sqlClient.ManagedBackupShortTermRetentionPolicies.Get(resourceGroup.Name, managedInstance.Name, dbName);
                Assert.Equal(basicRetention, policy.RetentionDays);

                // Attempt to decrease retention period to 3 days and verfiy that the operation succeeded.
                ManagedBackupShortTermRetentionPolicy parameters1 = new ManagedBackupShortTermRetentionPolicy(retentionDays: smallValue);
                sqlClient.ManagedBackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, managedInstance.Name, dbName, parameters1);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                policy = sqlClient.ManagedBackupShortTermRetentionPolicies.Get(resourceGroup.Name, managedInstance.Name, dbName);
                Assert.Equal(smallValue, policy.RetentionDays);

                // Attempt to increase retention period to 20 days and verfiy that the operation succeeded .
                ManagedBackupShortTermRetentionPolicy parameters2 = new ManagedBackupShortTermRetentionPolicy(retentionDays: validValue);
                sqlClient.ManagedBackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, managedInstance.Name, dbName, parameters2);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                policy = sqlClient.ManagedBackupShortTermRetentionPolicies.Get(resourceGroup.Name, managedInstance.Name, dbName);
                Assert.Equal(validValue, policy.RetentionDays);
            }
        }
示例#15
0
        public void FailoverPrimary()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                var             rg = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                ManagedInstance managedInstance = context.CreateManagedInstance(rg);
                Assert.NotNull(managedInstance);
                var resourceGroupName = rg.Name;

                // Wait for first full backup to finish
                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    Thread.Sleep(TimeSpan.FromMinutes(6));
                }
                sqlClient.ManagedInstances.Failover(resourceGroupName, managedInstance.Name, ReplicaType.Primary);
            }
        }
        public void TestSetManagedInstanceActiveDirectoryAdministrator()
        {
            string aadAdmin            = "aadadmin";
            string managedInstanceName = "miaadadmin";

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                Guid objectId = new Guid(TestEnvironmentUtilities.GetUserObjectId());
                Guid tenantId = new Guid(TestEnvironmentUtilities.GetTenantId());

                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                ResourceGroup       resourceGroup = context.CreateResourceGroup();

                ManagedInstance instance = context.CreateManagedInstance(resourceGroup);

                Assert.NotNull(instance);

                // Add new Active Directory Admin
                ManagedInstanceAdministrator newAdmin     = new ManagedInstanceAdministrator(login: aadAdmin, sid: objectId, tenantId: tenantId);
                ManagedInstanceAdministrator createResult = sqlClient.ManagedInstanceAdministrators.CreateOrUpdate(resourceGroup.Name, instance.Name, newAdmin);
                Assert.Equal(aadAdmin, createResult.Login);

                // Get the current Active Directory Admin
                ManagedInstanceAdministrator getResult = sqlClient.ManagedInstanceAdministrators.Get(resourceGroup.Name, instance.Name);
                Assert.Equal(aadAdmin, getResult.Login);
                Assert.Equal(objectId, getResult.Sid);
                Assert.Equal(tenantId, getResult.TenantId);

                // Delete the Active Directory Admin on server
                sqlClient.ManagedInstanceAdministrators.Delete(resourceGroup.Name, instance.Name);

                // List all Active Directory Admins for isntance.
                Microsoft.Azure.Management.Sql.Models.Page1 <ManagedInstanceAdministrator> admins = (Microsoft.Azure.Management.Sql.Models.Page1 <ManagedInstanceAdministrator>)sqlClient.ManagedInstanceAdministrators.ListByInstance(resourceGroup.Name, instance.Name);
                Assert.True(admins == null || !admins.GetEnumerator().MoveNext());
            }
        }
        public void TestDistributedAvailabilityGroup()
        {
            string suiteName = this.GetType().Name;

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                // Test setup (rg, mi):
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                //ResourceGroup rg = new ResourceGroup(location: "eastus2euap", id: "/subscriptions/8313371e-0879-428e-b1da-6353575a9192/resourceGroups/CustomerExperienceTeam_RG", name: "CustomerExperienceTeam_RG");
                //ManagedInstance managedInstance = sqlClient.ManagedInstances.Get(rg.Name, "chimera-ps-cli-v2");
                ResourceGroup   rg = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                ManagedInstance managedInstance = context.CreateManagedInstance(rg);
                Assert.NotNull(managedInstance);

                var resourceGroupName   = rg.Name;
                var managedInstanceName = managedInstance.Name;
                var dagName             = "TestDAG";
                var dagParams           = new DistributedAvailabilityGroup()
                {
                    TargetDatabase = "testdb",
                    SourceEndpoint = "TCP://SERVER:7022",
                    PrimaryAvailabilityGroupName   = "BoxLocalAg1",
                    SecondaryAvailabilityGroupName = "testcl",
                };
                var invalidDAG1 = new DistributedAvailabilityGroup()
                {
                    //TargetDatabase = "testdb",
                    SourceEndpoint = "TCP://SERVER:7022",
                    PrimaryAvailabilityGroupName   = "BoxLocalAg1",
                    SecondaryAvailabilityGroupName = "testcl",
                };
                var invalidDAG2 = new DistributedAvailabilityGroup()
                {
                    TargetDatabase = "testdb",
                    //SourceEndpoint = "TCP://SERVER:7022",
                    PrimaryAvailabilityGroupName   = "BoxLocalAg1",
                    SecondaryAvailabilityGroupName = "testcl",
                };
                var invalidDAG3 = new DistributedAvailabilityGroup()
                {
                    TargetDatabase = "testdb",
                    SourceEndpoint = "TCP://SERVER:7022",
                    //PrimaryAvailabilityGroupName = "BoxLocalAg1",
                    SecondaryAvailabilityGroupName = "testcl",
                };
                var invalidDAG4 = new DistributedAvailabilityGroup()
                {
                    TargetDatabase = "testdb",
                    SourceEndpoint = "TCP://SERVER:7022",
                    PrimaryAvailabilityGroupName = "BoxLocalAg1",
                    //SecondaryAvailabilityGroupName = "testcl",
                };
                var invalidDAG5 = new DistributedAvailabilityGroup();

                var exCreate1 = Assert.Throws <CloudException>(() => sqlClient.DistributedAvailabilityGroups.CreateOrUpdate(resourceGroupName, managedInstanceName, "invalid_dag1", invalidDAG1));
                var exCreate2 = Assert.Throws <CloudException>(() => sqlClient.DistributedAvailabilityGroups.CreateOrUpdate(resourceGroupName, managedInstanceName, "invalid_dag2", invalidDAG2));
                var exCreate3 = Assert.Throws <CloudException>(() => sqlClient.DistributedAvailabilityGroups.CreateOrUpdate(resourceGroupName, managedInstanceName, "invalid_dag3", invalidDAG3));
                var exCreate4 = Assert.Throws <CloudException>(() => sqlClient.DistributedAvailabilityGroups.CreateOrUpdate(resourceGroupName, managedInstanceName, "invalid_dag4", invalidDAG4));
                var exCreate5 = Assert.Throws <CloudException>(() => sqlClient.DistributedAvailabilityGroups.CreateOrUpdate(resourceGroupName, managedInstanceName, "invalid_dag5", invalidDAG5));
                Assert.Equal("InvalidParameterValue", exCreate1.Body.Code);
                Assert.Equal("InvalidParameterValue", exCreate2.Body.Code);
                Assert.Equal("InvalidParameterValue", exCreate3.Body.Code);
                Assert.Equal("InvalidParameterValue", exCreate4.Body.Code);

                var upsertResp = sqlClient.DistributedAvailabilityGroups.BeginCreateOrUpdate(resourceGroupName, managedInstanceName, dagName, dagParams);
                var listResp   = sqlClient.DistributedAvailabilityGroups.ListByInstance(resourceGroupName, managedInstanceName);

                var tries = 0;
                while (listResp.Count() == 0 && ++tries <= 3)
                {
                    TestUtilities.Wait(TimeSpan.FromSeconds(30));
                    listResp = sqlClient.DistributedAvailabilityGroups.ListByInstance(resourceGroupName, managedInstanceName);
                }

                var getResp = sqlClient.DistributedAvailabilityGroups.Get(resourceGroupName, managedInstanceName, dagName);
                Assert.NotNull(getResp);
                Assert.Single(listResp);
                Assert.Equal(dagParams.TargetDatabase, getResp.TargetDatabase);
                Assert.Equal(dagParams.SourceEndpoint, getResp.SourceEndpoint);
                Assert.Equal(dagParams.TargetDatabase, listResp.First().TargetDatabase);
                Assert.Equal(dagParams.SourceEndpoint, listResp.First().SourceEndpoint);

                sqlClient.DistributedAvailabilityGroups.Delete(resourceGroupName, managedInstanceName, dagName);
                var listRespEmpty = sqlClient.DistributedAvailabilityGroups.ListByInstance(resourceGroupName, managedInstanceName);
                Assert.Empty(listRespEmpty);
                var exceptionGet = Assert.Throws <CloudException>(() => sqlClient.DistributedAvailabilityGroups.Get(resourceGroupName, managedInstanceName, dagName));
                Assert.Equal("ResourceNotFound", exceptionGet.Body.Code);
            }
        }
示例#18
0
        public void TestCancelManagedInstanceOperation()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                var resourceGroup       = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                var managedInstance     = context.CreateManagedInstance(resourceGroup);
                var managedInstanceName = managedInstance.Name;
                var resourceGroupName   = resourceGroup.Name;

                // Old operations should be excluded from validation.
                var managedInstanceOperations = sqlClient.ManagedInstanceOperations.ListByManagedInstance(resourceGroupName, managedInstanceName);
                int oldOperations             = managedInstanceOperations.Count();

                // Sync update managed server.
                sqlClient.ManagedInstances.Update(resourceGroupName, managedInstanceName, new ManagedInstanceUpdate {
                    StorageSizeInGB = 128
                });

                managedInstanceOperations = sqlClient.ManagedInstanceOperations.ListByManagedInstance(resourceGroupName, managedInstanceName);
                var operationId = managedInstanceOperations.ElementAt(oldOperations).Name;

                var firstManagedInstanceOperation = sqlClient.ManagedInstanceOperations.Get(resourceGroupName, managedInstanceName, System.Guid.Parse(operationId));

                // Validate that operation finished successfully.
                SqlManagementTestUtilities.ValidateManagedInstanceOperation(firstManagedInstanceOperation, operationId, "UPDATE MANAGED SERVER", 100, "Succeeded", false);

                // Async update server
                var updateManagedInstance = sqlClient.ManagedInstances.UpdateAsync(resourceGroupName, managedInstanceName, new ManagedInstanceUpdate {
                    VCores = 16
                });

                do
                {
                    managedInstanceOperations = sqlClient.ManagedInstanceOperations.ListByManagedInstance(resourceGroupName, managedInstanceName);

                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(20000);
                    }
                } while (managedInstanceOperations.Count() < oldOperations + 2 || !managedInstanceOperations.ElementAt(oldOperations + 1).IsCancellable.Value);

                operationId = managedInstanceOperations.ElementAt(oldOperations + 1).Name;

                // Initiate cancel of second update which is in progress.
                sqlClient.ManagedInstanceOperations.Cancel(resourceGroupName, managedInstanceName, System.Guid.Parse(operationId));

                var secondManagedInstanceOperation = sqlClient.ManagedInstanceOperations.Get(resourceGroupName, managedInstanceName, System.Guid.Parse(operationId));

                while (!secondManagedInstanceOperation.State.Equals("Cancelled"))
                {
                    secondManagedInstanceOperation = sqlClient.ManagedInstanceOperations.Get(resourceGroupName, managedInstanceName, System.Guid.Parse(operationId));
                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(20000);
                    }
                }

                // Validate that operation was cancelled.
                SqlManagementTestUtilities.ValidateManagedInstanceOperation(secondManagedInstanceOperation, operationId, "UPDATE MANAGED SERVER", 100, "Cancelled", false);
            }
        }
示例#19
0
        public void RestorableDroppedManagedDatabasesTests()
        {
            using (SqlManagementTestContext Context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient       = Context.GetClient <SqlManagementClient>();
                ResourceGroup       resourceGroup   = Context.CreateResourceGroup();
                ManagedInstance     managedInstance = Context.CreateManagedInstance(resourceGroup);

                // Create managed database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(_testPrefix);
                var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(db1);

                // We need to wait for database to create its first backup. Currently if database drops too quickly it won't be restorable.
                // This will be changed in couple of weeks, howerver since building up Managed Instance takes over 60mins, this wait isn't not be a problem.
                // No need to sleep if we are playing back the recording.
                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    Thread.Sleep(TimeSpan.FromMinutes(10));
                }

                // Delete the original database
                sqlClient.ManagedDatabases.Delete(resourceGroup.Name, managedInstance.Name, db1.Name);

                // Wait until the final backup is created and the restorable dropped database exists.
                // This could be up to 10 minutes after the database is deleted, and the database must already
                // have a backup (which was accomplished by the previous wait period). Let's wait up to 15
                // just to give it a little more room.
                IEnumerable <RestorableDroppedManagedDatabase> droppedDatabases;
                DateTime startTime = DateTime.UtcNow;
                TimeSpan timeout   = TimeSpan.FromMinutes(15);
                do
                {
                    droppedDatabases = sqlClient.RestorableDroppedManagedDatabases.ListByInstance(resourceGroup.Name, managedInstance.Name);

                    if (droppedDatabases.Any())
                    {
                        // Dropped database now exists. Exit polling loop.
                        break;
                    }

                    // Sleep if we are running live to avoid hammering the server.
                    // No need to sleep if we are playing back the recording.
                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(30));
                    }
                } while (DateTime.UtcNow < startTime + timeout);

                // Assert that we found a restorable db before timeout ended.
                Assert.True(droppedDatabases.Any(), "No dropped databases were found after waiting for " + timeout);

                // The original database should now exist as a restorable dropped database
                var droppedDatabase = droppedDatabases.Single();
                Assert.StartsWith(db1.Name, droppedDatabase.Name);
                Assert.True(droppedDatabases.Count() == 1);

                // Test single get
                var getDroppedDatabase = sqlClient.RestorableDroppedManagedDatabases.Get(resourceGroup.Name, managedInstance.Name, droppedDatabase.Name);
                Assert.StartsWith(getDroppedDatabase.Name, droppedDatabase.Name);

                // Create another managed database
                //
                dbName = SqlManagementTestUtilities.GenerateName(_testPrefix);
                var db2 = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(db2);

                // We need to wait for database to create its first backup. Currently if database drops too quickly it won't be restorable.
                // This will be changed in couple of weeks, howerver since building up Managed Instance takes over 60mins, this wait isn't not be a problem.
                // No need to sleep if we are playing back the recording.
                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    Thread.Sleep(TimeSpan.FromMinutes(10));
                }

                // Delete the original database
                sqlClient.ManagedDatabases.Delete(resourceGroup.Name, managedInstance.Name, db2.Name);

                // Wait until the final backup is created and the restorable dropped database exists.
                // This could be up to 10 minutes after the database is deleted, and the database must already
                // have a backup (which was accomplished by the previous wait period). Let's wait up to 15
                // just to give it a little more room.
                do
                {
                    droppedDatabases = sqlClient.RestorableDroppedManagedDatabases.ListByInstance(resourceGroup.Name, managedInstance.Name);

                    if (droppedDatabases.Any())
                    {
                        // Dropped database now exists. Exit polling loop.
                        break;
                    }

                    // Sleep if we are running live to avoid hammering the server.
                    // No need to sleep if we are playing back the recording.
                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(30));
                    }
                } while (DateTime.UtcNow < startTime + timeout);

                // There should be 2 dropped databases now
                Assert.True(droppedDatabases.Count() == 2);
            }
        }
示例#20
0
        public void ManagedDatabaseExternalBackupRestoreTest()
        {
            using (SqlManagementTestContext Context = new SqlManagementTestContext(this))
            {
                SqlManagementClient     sqlClient     = Context.GetClient <SqlManagementClient>();
                StorageManagementClient storageClient = Context.GetClient <StorageManagementClient>();
                const string            AccountName   = "backupscxteam";

                string testStorageContainerUri      = "https://backupscxteam.blob.core.windows.net/clients";
                string testStorageContainerSasToken = string.Empty;
                StorageAccountListKeysResult keys   =
                    storageClient.StorageAccounts.ListKeys(ManagedInstanceTestUtilities.ResourceGroupName, AccountName);
                string key = keys.Keys.First().Value;

                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    CloudBlobContainer container = new CloudBlobContainer(
                        new Uri(testStorageContainerUri),
                        new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(AccountName, key));
                    SharedAccessBlobPolicy sharedAccessPolicy = new SharedAccessBlobPolicy
                    {
                        SharedAccessExpiryTime = new DateTimeOffset(DateTime.UtcNow.Add(TimeSpan.FromHours(1))),
                        Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List
                    };
                    testStorageContainerSasToken = container.GetSharedAccessSignature(sharedAccessPolicy);
                }

                ResourceGroup   resourceGroup   = Context.CreateResourceGroup();
                ManagedInstance managedInstance = Context.CreateManagedInstance(resourceGroup);
                string          databaseName    = SqlManagementTestUtilities.GenerateName(_testPrefix);

                // Start external backup restore.
                var db = sqlClient.ManagedDatabases.BeginCreateOrUpdateAsync(
                    resourceGroup.Name,
                    managedInstance.Name,
                    databaseName,
                    new ManagedDatabase()
                {
                    CreateMode               = "RestoreExternalBackup",
                    Location                 = managedInstance.Location,
                    Collation                = managedInstance.Collation,
                    StorageContainerUri      = testStorageContainerUri,
                    StorageContainerSasToken = testStorageContainerSasToken
                }).GetAwaiter().GetResult();

                RetryAction(() =>
                {
                    var success = false;
                    try
                    {
                        var dbs = sqlClient.ManagedDatabases.Get(resourceGroup.Name, managedInstance.Name, databaseName);

                        if (dbs != null)
                        {
                            success = true;
                        }
                    }
                    catch (Exception e)
                    {
                        success = false;
                    }

                    // Sleep if we are running live to avoid hammering the server.
                    // No need to sleep if we are playing back the recording.
                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(5));
                    }

                    return(success);
                });

                // Wait until restore state is Waiting - this means that all files have been restored from storage container.
                //
                RetryAction(() =>
                {
                    var restoreDetails = sqlClient.ManagedDatabaseRestoreDetails.Get(resourceGroup.Name, managedInstance.Name, databaseName);

                    if (restoreDetails.Status == "Waiting")
                    {
                        return(true);
                    }

                    // Sleep if we are running live to avoid hammering the server.
                    // No need to sleep if we are playing back the recording.
                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(60));
                    }

                    return(false);
                });

                // Initiate restore complete request.
                //
                sqlClient.ManagedDatabases.BeginCompleteRestore(resourceGroup.Name, managedInstance.Name, databaseName, new CompleteDatabaseRestoreDefinition()
                {
                    LastBackupName = "log2_0"
                });

                // Wait until restore state is Completed.
                //
                RetryAction(() =>
                {
                    var restoreDetails = sqlClient.ManagedDatabaseRestoreDetails.Get(resourceGroup.Name, managedInstance.Name, databaseName);

                    if (restoreDetails.Status == "Completed")
                    {
                        return(true);
                    }

                    // Sleep if we are running live to avoid hammering the server.
                    // No need to sleep if we are playing back the recording.
                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(30));
                    }

                    return(false);
                });
            }
        }
示例#21
0
        public void ShortTermRetentionOnDroppedDatabase()
        {
            using (SqlManagementTestContext Context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient       = Context.GetClient <SqlManagementClient>();
                ResourceGroup       resourceGroup   = Context.CreateResourceGroup();
                ManagedInstance     managedInstance = Context.CreateManagedInstance(resourceGroup);

                // Create managed database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(_testPrefix);
                var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(resourceGroup.Name, managedInstance.Name, dbName, new ManagedDatabase()
                {
                    Location = managedInstance.Location,
                });
                Assert.NotNull(db1);

                int startingRetention = 25;
                int invalidValue      = 35;
                int validValue        = 20;

                // Attempt to increase retention period to 25 days and verfiy that the operation succeeded. Since increasing of retention days for dropped database is disabled,
                // we need to increase retention beforehand, and test reducing it once database is dropped.
                ManagedBackupShortTermRetentionPolicy parameters0 = new ManagedBackupShortTermRetentionPolicy(retentionDays: startingRetention);
                sqlClient.ManagedBackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, managedInstance.Name, dbName, parameters0);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                ManagedBackupShortTermRetentionPolicy policy = sqlClient.ManagedBackupShortTermRetentionPolicies.Get(resourceGroup.Name, managedInstance.Name, dbName);
                Assert.Equal(startingRetention, policy.RetentionDays);

                // We need to wait for database to create its first backup. Currently if database drops too quickly it won't be restorable.
                // This will be changed in couple of weeks, howerver since building up Managed Instance takes over 60mins, this wait isn't not be a problem.
                // No need to sleep if we are playing back the recording.
                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    Thread.Sleep(TimeSpan.FromMinutes(10));
                }

                // Delete the original database
                sqlClient.ManagedDatabases.Delete(resourceGroup.Name, managedInstance.Name, db1.Name);

                // Wait until the final backup is created and the restorable dropped database exists.
                // This could be up to 10 minutes after the database is deleted, and the database must already
                // have a backup (which was accomplished by the previous wait period). Let's wait up to 15
                // just to give it a little more room.
                IEnumerable <RestorableDroppedManagedDatabase> droppedDatabases;
                DateTime startTime = DateTime.UtcNow;
                TimeSpan timeout   = TimeSpan.FromMinutes(15);
                do
                {
                    droppedDatabases = sqlClient.RestorableDroppedManagedDatabases.ListByInstance(resourceGroup.Name, managedInstance.Name);

                    if (droppedDatabases.Any())
                    {
                        // Dropped database now exists. Exit polling loop.
                        break;
                    }

                    // Sleep if we are running live to avoid hammering the server.
                    // No need to sleep if we are playing back the recording.
                    if (HttpMockServer.Mode == HttpRecorderMode.Record)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(30));
                    }
                } while (DateTime.UtcNow < startTime + timeout);

                // Assert that we found a restorable db before timeout ended.
                Assert.True(droppedDatabases.Any(), "No dropped databases were found after waiting for " + timeout);

                var rdmd = droppedDatabases.Single();

                // Attempt to increase retention period to 3 days and verfiy that the operation fails.
                ManagedBackupShortTermRetentionPolicy parameters1 = new ManagedBackupShortTermRetentionPolicy(retentionDays: invalidValue);
                sqlClient.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, managedInstance.Name, rdmd.Name, parameters1);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                policy = sqlClient.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPolicies.Get(resourceGroup.Name, managedInstance.Name, rdmd.Name);
                Assert.Equal(startingRetention, policy.RetentionDays);

                // Attempt to increase retention period to 20 days and verfiy that the operation succeeded .
                ManagedBackupShortTermRetentionPolicy parameters2 = new ManagedBackupShortTermRetentionPolicy(retentionDays: validValue);
                sqlClient.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPolicies.CreateOrUpdateWithHttpMessagesAsync(resourceGroup.Name, managedInstance.Name, rdmd.Name, parameters2);
                Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestUtilities.Wait(TimeSpan.FromSeconds(3));
                policy = sqlClient.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPolicies.Get(resourceGroup.Name, managedInstance.Name, rdmd.Name);
                Assert.Equal(validValue, policy.RetentionDays);
            }
        }
        public void TestServerTrustCertificates()
        {
            string suiteName = this.GetType().Name;

            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                // Test setup (rg, mi):
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();
                //ResourceGroup rg = new ResourceGroup(location: "eastus2euap", id: "/subscriptions/8313371e-0879-428e-b1da-6353575a9192/resourceGroups/CustomerExperienceTeam_RG", name: "CustomerExperienceTeam_RG");
                //ManagedInstance managedInstance = sqlClient.ManagedInstances.Get(rg.Name, "chimera-ps-cli-v2");
                ResourceGroup   rg = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                ManagedInstance managedInstance = context.CreateManagedInstance(rg);
                Assert.NotNull(managedInstance);

                // Test data:
                var resourceGroupName   = rg.Name;
                var managedInstanceName = managedInstance.Name;
                var expectedCert1       = new ServerTrustCertificate(makeId(managedInstance.Id, certificateName1), certificateName1, certType, publicBlob1, thumbprint1, certificateName1);
                var expectedCert2       = new ServerTrustCertificate(makeId(managedInstance.Id, certificateName2), certificateName2, certType, publicBlob2, thumbprint2, certificateName2);

                // Make API calls
                var upsertResp1 = sqlClient.ServerTrustCertificates.CreateOrUpdate(resourceGroupName, managedInstanceName, certificateName1, expectedCert1);
                var upsertResp2 = sqlClient.ServerTrustCertificates.CreateOrUpdate(resourceGroupName, managedInstanceName, certificateName2, expectedCert2);
                var getResp1    = sqlClient.ServerTrustCertificates.Get(resourceGroupName, managedInstanceName, certificateName1);
                var getResp2    = sqlClient.ServerTrustCertificates.Get(resourceGroupName, managedInstanceName, certificateName2);
                var listResp    = sqlClient.ServerTrustCertificates.ListByInstance(resourceGroupName, managedInstanceName);

                // Test all result fields
                var listRespCert1 = listResp.Where(cert => cert.Name.Equals(certificateName1)).FirstOrDefault();
                var listRespCert2 = listResp.Where(cert => cert.Name.Equals(certificateName2)).FirstOrDefault();
                var expected      = new[] { expectedCert1, expectedCert2, expectedCert1, expectedCert2, expectedCert1, expectedCert2 };
                var actual        = new[] { upsertResp1, upsertResp2, getResp1, getResp2, listRespCert1, listRespCert2 };
                var exp_act       = expected.Zip(actual, (e, a) => new { Expected = e, Actual = a });
                foreach (var ea in exp_act)
                {
                    Assert.NotNull(ea.Actual);
                    Assert.Equal(ea.Expected.CertificateName, ea.Actual.CertificateName);
                    Assert.Equal(ea.Expected.Id, ea.Actual.Id);
                    Assert.Equal(ea.Expected.Name, ea.Actual.Name);
                    Assert.Equal(ea.Expected.PublicBlob, "0x" + ea.Actual.PublicBlob);
                    Assert.Equal(ea.Expected.Thumbprint, "0x" + ea.Actual.Thumbprint);
                    Assert.Equal(ea.Expected.Type, ea.Actual.Type);
                }

                // cert with invalid public key blob
                var invalidCert1 = new ServerTrustCertificate(makeId(managedInstance.Id, invalidCertName1), invalidCertName1, certType, invalidPublicBlob, thumbprint1, invalidCertName1);
                // cert without public key blob
                var invalidCert2 = new ServerTrustCertificate(makeId(managedInstance.Id, invalidCertName2), invalidCertName2, certType, null, thumbprint2, invalidCertName2);
                // cert with a public blob that already exist on the instance under a different name
                var invalidCert3 = new ServerTrustCertificate(makeId(managedInstance.Id, invalidCertName3), invalidCertName3, certType, publicBlob1, thumbprint1, invalidCertName3);
                // cert blob empty
                var invalidCert4 = new ServerTrustCertificate(makeId(managedInstance.Id, invalidCertName3), invalidCertName3, certType, "", thumbprint1, invalidCertName3);
                // cert name exists, different blob
                var invalidCert5 = new ServerTrustCertificate(makeId(managedInstance.Id, certificateName1), certificateName1, certType, publicBlob3, thumbprint3, certificateName1);
                // cert name empty
                var invalidCert6 = new ServerTrustCertificate(makeId(managedInstance.Id, ""), "", certType, publicBlob1, thumbprint1, "");
                var exception1   = Assert.Throws <CloudException>(() => sqlClient.ServerTrustCertificates.CreateOrUpdate(resourceGroupName, managedInstanceName, invalidCertName1, invalidCert1));
                var exception2   = Assert.Throws <CloudException>(() => sqlClient.ServerTrustCertificates.CreateOrUpdate(resourceGroupName, managedInstanceName, invalidCertName2, invalidCert2));
                var exception3   = Assert.Throws <CloudException>(() => sqlClient.ServerTrustCertificates.CreateOrUpdate(resourceGroupName, managedInstanceName, invalidCertName3, invalidCert3));
                var exception4   = Assert.Throws <CloudException>(() => sqlClient.ServerTrustCertificates.CreateOrUpdate(resourceGroupName, managedInstanceName, invalidCertName3, invalidCert4));
                var exception5   = Assert.Throws <CloudException>(() => sqlClient.ServerTrustCertificates.CreateOrUpdate(resourceGroupName, managedInstanceName, certificateName1, invalidCert5));
                var exception6   = Assert.Throws <CloudException>(() => sqlClient.ServerTrustCertificates.CreateOrUpdate(resourceGroupName, managedInstanceName, "", invalidCert6));
                Assert.Contains("InvalidPublicBlob", exception1.Body.Code);
                Assert.Contains("MissingPublicBlob", exception4.Body.Code);
                Assert.Contains("MethodNotAllowed", exception6.Body.Code);

                sqlClient.ServerTrustCertificates.BeginDelete(resourceGroupName, managedInstanceName, certificateName1);
                sqlClient.ServerTrustCertificates.BeginDelete(resourceGroupName, managedInstanceName, certificateName2);
            }
        }
示例#23
0
        public void TestCreateUpdateGetDropManagedInstance()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                Dictionary <string, string> tags = new Dictionary <string, string>()
                {
                    { "tagKey1", "TagValue1" }
                };

                bool   publicDataEndpointEnabled = true;
                string proxyOverride             = ManagedInstanceProxyOverride.Proxy;
                string requestedBSR               = "Geo";
                string publicResourceName         = "SQL_Default";
                string maintenanceConfigurationId = ManagedInstanceTestUtilities.getManagedInstanceFullMaintenanceResourceid();

                // Create resource group
                var resourceGroup = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region);
                //Create server
                var managedInstance1 = context.CreateManagedInstance(resourceGroup, new ManagedInstance()
                {
                    Tags = tags,
                    MaintenanceConfigurationId = maintenanceConfigurationId
                });
                SqlManagementTestUtilities.ValidateManagedInstance(managedInstance1, tags, shouldCheckState: true);

                // Create second server
                var managedInstance2 = context.CreateManagedInstance(resourceGroup, new ManagedInstance()
                {
                    DnsZonePartner = string.Format(
                        "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Sql/managedInstances/{2}",
                        ManagedInstanceTestUtilities.SubscriptionId,
                        ManagedInstanceTestUtilities.ResourceGroupName,
                        managedInstance1.Name),
                    PublicDataEndpointEnabled = publicDataEndpointEnabled,
                    ProxyOverride             = proxyOverride
                });
                SqlManagementTestUtilities.ValidateManagedInstance(managedInstance2, shouldCheckState: true);

                // Get first server
                var getMI1 = sqlClient.ManagedInstances.Get(resourceGroup.Name, managedInstance1.Name);
                SqlManagementTestUtilities.ValidateManagedInstance(getMI1, tags, shouldCheckState: true);

                // Get second server
                var getMI2 = sqlClient.ManagedInstances.Get(resourceGroup.Name, managedInstance2.Name);
                SqlManagementTestUtilities.ValidateManagedInstance(getMI2, shouldCheckState: true);

                // Verify that maintenanceConfigurationId value is correctly set
                Assert.Contains(publicResourceName, getMI1.MaintenanceConfigurationId);

                // Verify that storageAccountType value is correctly set
                Assert.Equal(requestedBSR, getMI1.RequestedBackupStorageRedundancy);
                Assert.Equal(requestedBSR, getMI2.RequestedBackupStorageRedundancy);
                Assert.Equal(requestedBSR, getMI1.CurrentBackupStorageRedundancy);
                Assert.Equal(requestedBSR, getMI2.CurrentBackupStorageRedundancy);

                // Verify that dns zone value is correctly inherited from dns zone partner
                Assert.Equal(getMI1.DnsZone, getMI2.DnsZone);

                // Verify PublicDataEndpointEnabled value for second server
                Assert.Equal(publicDataEndpointEnabled, getMI2.PublicDataEndpointEnabled);

                // Verify ProxyOverride value for second server
                Assert.Equal(proxyOverride, getMI2.ProxyOverride);

                var listMI = context.ListManagedInstanceByResourceGroup(resourceGroup.Name);

                Assert.Equal(2, listMI.Count());

                // Update first server
                Dictionary <string, string> newTags = new Dictionary <string, string>()
                {
                    { "asdf", "zxcv" }
                };
                var updateMI1 = sqlClient.ManagedInstances.Update(resourceGroup.Name, getMI1.Name, new ManagedInstanceUpdate
                {
                    Tags        = newTags,
                    LicenseType = "LicenseIncluded"
                });
                SqlManagementTestUtilities.ValidateManagedInstance(updateMI1, newTags);

                // Drop server, update count
                sqlClient.ManagedInstances.Delete(resourceGroup.Name, getMI1.Name);

                var listMI2 = context.ListManagedInstanceByResourceGroup(resourceGroup.Name);
                Assert.Single(listMI2);

                sqlClient.ManagedInstances.Delete(resourceGroup.Name, managedInstance2.Name);
                var listMI3 = context.ListManagedInstanceByResourceGroup(resourceGroup.Name);
                Assert.Empty(listMI3);
            }
        }