public void Execute_Retry_LoginIssue()
        {
            //Arrange
            var firstAttemptResults = new MigrationResultSet(false, new List <LogMessage>()
            {
                new LogMessage(LogSeverity.Error, @"SqlException: Cannot open database ""EDDSPerformance"" requested by the login. The login failed.")
            });
            var secondAttemptResults = new MigrationResultSet(true,
                                                              new List <LogMessage>()
            {
                new LogMessage(LogSeverity.Info, "msg 2")
            });
            var expectedMessageCount = firstAttemptResults.Messages.Count + secondAttemptResults.Messages.Count + 1;

            _roundhouseManager.SetupSequence(
                rm => rm.Run(It.IsAny <string>(), path, "create script", "EDDS", "server", It.IsAny <int>()))
            .Returns(firstAttemptResults)
            .Returns(secondAttemptResults);

            //Act
            var results = this.databaseMigrator.Execute(path, false);

            //Assert
            Assert.That(results.Success, Is.True);
            Assert.That(results.Messages.Count, Is.GreaterThanOrEqualTo(expectedMessageCount), "final merged message count must be greater than or equal to both first and second attempt and any additional messages logged when re-trying");
        }
Exemplo n.º 2
0
        /// <summary>
        /// Unzip the migration files, replace storage paths, and run deployment
        /// </summary>
        /// <returns>result set</returns>
        public MigrationResultSet Deploy()
        {
            var workingDirectory        = FetchZippedResource();
            var workingDirectoryScripts = Directory.GetFiles(workingDirectory, "*.sql", SearchOption.AllDirectories);

            sqlScriptTokenService.Replace(workingDirectoryScripts);
            var result = new MigrationResultSet()
            {
                Success = true, Messages = new List <LogMessage>()
            };

            RunCreateDatabaseScript(workingDirectory, result);
            if (result.Success)
            {
                var rhResult = Execute(workingDirectory);
                foreach (var rhResultsMessage in rhResult.Messages)
                {
                    result.Messages.Add(rhResultsMessage);
                }

                result.Success = result.Success && rhResult.Success;
                return(result);
            }
            else
            {
                return(result);
            }
        }
        public void MockDeploy_UpdatesScriptsInstalledVersion()
        {
            //Arrange
            var creds   = new GenericCredentialInfo();
            var servers = new[] { new ResourceServer()
                                  {
                                      Name = "localhost"
                                  } };
            var deploymentResults = new MigrationResultSet()
            {
                Success = true, Messages = new List <LogMessage>()
                {
                    new LogMessage(LogSeverity.Info, "abc")
                }
            };

            _serverRepositoryMock.Setup(x => x.ReadAllActive())
            .Returns(servers.Select(s => new Server()
            {
                ServerName = s.Name, ServerType = ServerType.Database
            }).ToArray());
            _databaseDeployer.Setup(ds => ds.DeployResource(It.IsAny <Server>(), creds)).Returns(deploymentResults);
            _refreshServerService.Setup(rss => rss.GetServerList()).Returns(servers);
            _refreshServerService.Setup(rss => rss.UpdateServerList(servers));
            this.administrationInstallationRepositoryMock.Setup(x => x.UpdateAdminScriptsRun());

            //Act
            var results = this.administrationInstallationService.InstallScripts(creds);

            //Assert
            Assert.IsTrue(results.Success);
            this.administrationInstallationRepositoryMock.Verify(x => x.UpdateAdminScriptsRun(), Times.Exactly(1));
        }
        public void Execute_Retry_AoagIssue()
        {
            //Arrange
            var firstAttemptResults = new MigrationResultSet(false, new List <LogMessage>()
            {
                new LogMessage(LogSeverity.Error, "SqlException: involved in a database mirroring session or an availability group")
            });
            var secondAttemptResults = new MigrationResultSet(true,
                                                              new List <LogMessage>()
            {
                new LogMessage(LogSeverity.Info, "msg 2")
            });
            var expectedMessageCount = firstAttemptResults.Messages.Count + secondAttemptResults.Messages.Count + 1;

            _availabilityGroupRepo.Setup(r => r.RemoveFromAvailabilityGroup("EDDS")).Returns(true);
            _roundhouseManager.SetupSequence(
                rm => rm.Run(It.IsAny <string>(), path, "create script", "EDDS", "server", It.IsAny <int>()))
            .Returns(firstAttemptResults)
            .Returns(secondAttemptResults);

            //Act
            var results = this.databaseMigrator.Execute(path, false);

            //Assert
            Assert.That(results.Success, Is.True);
            Assert.That(results.Messages.Count, Is.GreaterThanOrEqualTo(expectedMessageCount), "final merged message count must be greater than or equal to both first and second attempt and any additional messages logged when re-trying");
            _availabilityGroupRepo.Verify(r => r.RemoveFromAvailabilityGroup("EDDS"), Times.Once);
        }
        public void Execute_Success_LogMuting()
        {
            //Arrange
            var migrationResults = new MigrationResultSet(true, new List <LogMessage>()
            {
                new LogMessage(LogSeverity.Info, "msg 1"),
                new LogMessage(LogSeverity.Warning, "msg 2"),
                new LogMessage(LogSeverity.Debug, "msg 3")
            });

            var migrationResultsMuted = new MigrationResultSet(true, new List <LogMessage>())
            {
                Messages = migrationResults.Messages.Select(m =>
                {
                    m.Message  = $"[{m.Severity}] -- {m.Message}";
                    m.Severity = LogSeverity.Debug;
                    return(m);
                }).ToList()
            };


            _roundhouseManager.Setup(
                rm => rm.Run(It.IsAny <string>(), path, "create script", "EDDS", "server", It.IsAny <int>()))
            .Returns(migrationResults);

            //Act
            var results = this.databaseMigrator.Execute(path, false);

            //Assert
            Assert.That(results.Success, Is.True);
            Assert.That(results.Messages, Is.EquivalentTo(migrationResultsMuted.Messages));
        }
 public static void HandleDeploymentResponse(MigrationResultSet deploymentResults, ScriptInstallationResults installResults)
 {
     deploymentResults.Messages
     .Where(m => m.Severity != LogSeverity.Debug)
     .Select(m => m.Message)
     .ForEach(m => installResults.AppendMessage(
                  "Deploying " + Names.Database.PdbResource + $" script message: {m}"));
 }
Exemplo n.º 7
0
 internal void RunCreateDatabaseScript(string workingDirectoryScripts, MigrationResultSet resultSet)
 {
     try
     {
         var createScriptPath = Path.Combine(workingDirectoryScripts, "Create_Database.sql");
         deploymentRepo.RunCreateDatabaseScripts(deploymentSettings, createScriptPath, resultSet);
     }
     catch (Exception ex)
     {
         resultSet.Success = false;
         resultSet.Messages.Add(new LogMessage(LogSeverity.Error, $"Error creating database: {ex.ToString()}"));
     }
 }
Exemplo n.º 8
0
        public MigrationResultSet HandleDeploymentResponse(MigrationResultSet results)
        {
            var errors = from message in results.Messages
                         where message.Severity != LogSeverity.Debug &&
                         (!results.Success || message.Severity != LogSeverity.Info)                                        //Give us more detailed logs when this thing fails
                         select message.ToString();

            foreach (var error in errors)
            {
                this.logger.LogError(error);
            }

            return(results);
        }
        public void RunSqlScripts_ConnectionError()
        {
            var settings = TestUtilities.GetDeploymentSettings();

            settings.Server = "SomeServerThatDoesntExist";
            var resultSet = new MigrationResultSet(true, new List <LogMessage>());
            var sprocText = "select 1";
            var path      = Path.GetTempFileName();

            File.WriteAllText(path, sprocText);

            // Act
            this.deploymentRepository.RunSqlScripts(settings, path, resultSet);

            // Assert
            Assert.That(resultSet.Messages.Count, Is.EqualTo(0));
        }
        public void RunSqlScripts_Success()
        {
            var settings  = TestUtilities.GetDeploymentSettings();
            var resultSet = new MigrationResultSet(true, new List <LogMessage>());
            var sprocText = "select 1";
            var path      = Path.GetTempPath();

            path = Path.Combine(path, Guid.NewGuid().ToString());
            Directory.CreateDirectory(path);
            File.WriteAllText(Path.Combine(path, "test_sproc.sql"), sprocText);

            //create repository
            this.deploymentRepository.RunSqlScripts(settings, path, resultSet);

            //Assert
            Assert.That(resultSet.Messages.Count, Is.EqualTo(1));
        }
        public void HandleDeploymentResponse()
        {
            var resultSet = new MigrationResultSet()
            {
                Success  = true,
                Messages = new[]
                {
                    new LogMessage(LogSeverity.Debug, "a"),
                    new LogMessage(LogSeverity.Info, "b"),
                    new LogMessage(LogSeverity.Warning, "c")
                }
            };

            var result = this.handler.HandleDeploymentResponse(resultSet);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Success, Is.True);
        }
        public MigrationResultSet HandleDeploymentResponse(MigrationResultSet results)
        {
            results.Messages.ForEach(this.LogMessage);

            if (results.Success)
            {
                return(results);
            }

            var errorMessage =
                results.Messages
                .Where(m => m.Severity == LogSeverity.Error)
                .Select(m => m.Message)
                .Join("{0}\r\n{1}")
                .Truncate(5000);

            throw new Exception($"Error redeploying services - {errorMessage}");
        }
        public void HandleDeploymentResponse_Success()
        {
            //Arrange
            var installResults    = new ScriptInstallationResults();
            var deploymentResults = new MigrationResultSet()
            {
                Success = true, Messages = new List <LogMessage>()
                {
                    new LogMessage(LogSeverity.Info, "abc")
                }
            };

            //Act
            AdministrationInstallationService.HandleDeploymentResponse(deploymentResults, installResults);

            //Assert
            Assert.That(installResults.Messages, Is.Not.Empty);
        }
Exemplo n.º 14
0
        public MigrationResultSet ReDeployScripts()
        {
            var result = new MigrationResultSet
            {
                Success  = true,
                Messages = new List <LogMessage>()
            };

            if (string.IsNullOrEmpty(cachedWorkingDirectory))
            {
                cachedWorkingDirectory = FetchZippedResource();
            }

            var workingDirectoryScripts = Directory.GetFiles(cachedWorkingDirectory, "*.sql", SearchOption.AllDirectories);

            sqlScriptTokenService.Replace(workingDirectoryScripts);

            try
            {
                var spocsScriptPath = Path.Combine(cachedWorkingDirectory, DeploymentDirectoryStructureConstants.SprocsFolderName);
                if (Directory.Exists(spocsScriptPath))
                {
                    var msg = new LogMessage(LogSeverity.Info, $"Redeploying stored procedures {spocsScriptPath}");
                    result.Messages.Add(msg);
                    deploymentRepo.RunSqlScripts(deploymentSettings, spocsScriptPath, result);
                }

                var functionsScriptPath = Path.Combine(cachedWorkingDirectory, DeploymentDirectoryStructureConstants.FunctionsFolderName);
                if (Directory.Exists(functionsScriptPath))
                {
                    var msg = new LogMessage(LogSeverity.Info, $"Redeploying stored procedures {functionsScriptPath}");
                    result.Messages.Add(msg);
                    deploymentRepo.RunSqlScripts(deploymentSettings, functionsScriptPath, result);
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                var msg = new LogMessage(LogSeverity.Error, $"Error redeploying scripts /n {ex.ToString()}");
                result.Messages.Add(msg);
            }

            return(result);
        }
        public void Execute_Success()
        {
            //Arrange
            var migrationResults = new MigrationResultSet(true, new List <LogMessage>()
            {
                new LogMessage(LogSeverity.Info, "msg 1")
            });

            _roundhouseManager.Setup(
                rm => rm.Run(It.IsAny <string>(), path, "create script", "EDDS", "server", It.IsAny <int>()))
            .Returns(migrationResults);

            //Act
            var results = this.databaseMigrator.Execute(path, false);

            //Assert
            Assert.That(results.Success, Is.True);
            Assert.That(results.Messages, Is.EquivalentTo(migrationResults.Messages));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Re-runs the deployment and merges the result set from the first attempt
        /// </summary>
        /// <param name="workingDirectory">the directory with the scripts</param>
        /// <param name="results">the first attempts result set</param>
        /// <returns>the merged migration result set</returns>
        internal MigrationResultSet RetryDeployment(string workingDirectory, MigrationResultSet results)
        {
            this.timeService.Sleep(DatabaseConstants.DeploymentRetrySleepTimeoutSeconds);

            // execute the deployment again
            var retryResults = this.Execute(workingDirectory, true);

            // mark the success from the retry results overwriting the first attempts success result.
            results.Success = retryResults.Success;
            results.Messages.Add(new LogMessage(LogSeverity.Warning, $"Retrying database deployment."));

            // append the retry result messages to the first attempts messages
            foreach (var retryResultsMessage in retryResults.Messages.ToList())
            {
                results.Messages.Add(retryResultsMessage);
            }

            return(results);
        }
Exemplo n.º 17
0
        public void Setup()
        {
            this.logger = TestUtilities.GetMockLogger().Object;
            this.databaseMigratorFactory = new Mock <IDatabaseMigratorFactory>();
            this.databaseMigrator        = new Mock <IDatabaseMigrator>();
            this.migrationResultHandler  = new Mock <IMigrationResultHandler>();
            this.migrationResultHandler.Setup(h => h.HandleDeploymentResponse(It.IsAny <MigrationResultSet>()))
            .Returns <MigrationResultSet>(mrs => mrs);
            var resultSet = new MigrationResultSet()
            {
                Success = true, Messages = new[]
                {
                    new LogMessage(LogSeverity.Debug, "a"),
                    new LogMessage(LogSeverity.Info, "b"),
                    new LogMessage(LogSeverity.Warning, "c")
                }
            };

            this.databaseMigrator.Setup(s => s.Deploy()).Returns(resultSet);
            this.databaseDeployer = new DatabaseDeployer(databaseMigratorFactory.Object, this.migrationResultHandler.Object);
        }
        public void RunCreateDatabaseScripts()
        {
            // Arrange
            var settings = new DeploymentSettings {
                Server = Config.Server, DatabaseName = Names.Database.EddsPerformance
            };
            var resultSet = new MigrationResultSet(true, new List <LogMessage>());
            var sprocText = "select 1";
            var path      = Path.GetTempPath();

            path = Path.Combine(path, Guid.NewGuid().ToString());
            Directory.CreateDirectory(path);
            var file = Path.Combine(path, "test_sproc.sql");

            File.WriteAllText(file, sprocText);

            // Act
            this.deploymentRepository.RunCreateDatabaseScripts(settings, file, resultSet);

            // Assert
            Assert.That(resultSet.Success, Is.True);
            Assert.That(resultSet.Messages.Count, Is.EqualTo(5));
        }
        public void RetryDeployment()
        {
            //Arrange
            var firstAttemptResults = new MigrationResultSet(false, new List <LogMessage>()
            {
                new LogMessage(LogSeverity.Info, "msg 1")
            });
            var secondAttemptResults = new MigrationResultSet(true, new List <LogMessage>()
            {
                new LogMessage(LogSeverity.Info, "msg 2")
            });
            var expectedMessageCount = firstAttemptResults.Messages.Count + secondAttemptResults.Messages.Count + 1;

            _roundhouseManager.Setup(
                rm => rm.Run(It.IsAny <string>(), path, "create script", "EDDS", "server", It.IsAny <int>()))
            .Returns(secondAttemptResults);

            //Act
            var results = this.databaseMigrator.RetryDeployment(path, firstAttemptResults);

            //Assert
            Assert.That(results.Success, Is.True);
            Assert.That(results.Messages.Count, Is.GreaterThanOrEqualTo(expectedMessageCount), "final merged message count must be greater than or equal to both first and second attempt and any additional messages logged when re-trying");
        }
        public void RunCreateDatabaseScripts(DeploymentSettings settings, string createScriptPath, MigrationResultSet result)
        {
            if (!File.Exists(createScriptPath))
            {
                return;
            }
            using (var conn = this.connectionFactory.GetMasterConnection(settings.Server, settings.CredentialInfo))
            {
                var scriptText = File.ReadAllText(createScriptPath);
                result.Messages.Add(new LogMessage(LogSeverity.Info, $"Creating database started."));
                string[] commandTexts = Regex.Split(scriptText + "\n", @"^\s*GO\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                foreach (var commandText in commandTexts)
                {
                    if (string.IsNullOrWhiteSpace(commandText))
                    {
                        continue;
                    }

                    result.Messages.Add(new LogMessage(LogSeverity.Info, $"Create database script {commandText}"));
                    conn.Execute(commandText);
                }
            }

            // Test to see if we can connect to new database before finishing
            result.Messages.Add(new LogMessage(LogSeverity.Info, $"Testing to see if we can connect to database."));
            var stop    = 0;
            var timeout = DateTime.UtcNow.AddSeconds(120);

            while (stop == 0 && timeout > DateTime.UtcNow)
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    using (var conn = this.connectionFactory.GetTargetConnection(settings.DatabaseName, settings.Server, settings.CredentialInfo))
                    {
                        stop = conn.ExecuteScalar <int>("select top(1) 1 FROM [sys].[objects]");
                    }
                }
                catch { /* -- Intentionally eating exception -- */ }
            }

            // Create initial roundhouse databases if they don't exist
            using (var conn = this.connectionFactory.GetTargetConnection(settings.DatabaseName, settings.Server, settings.CredentialInfo))
            {
                result.Messages.Add(new LogMessage(LogSeverity.Info, $"Creating Roundhouse Tables if they don't exist."));
                conn.Execute(Resources.CreateRoundHouseTables);
            }

            result.Messages.Add(new LogMessage(LogSeverity.Info, "Creating database completed."));
        }
        public void RunSqlScripts(DeploymentSettings settings, string spocsScriptPath, MigrationResultSet result)
        {
            try
            {
                using (var conn = this.connectionFactory.GetTargetConnection(settings.DatabaseName, settings.Server, settings.CredentialInfo))
                {
                    foreach (var sqlFile in Directory.GetFiles(spocsScriptPath, "*.sql"))
                    {
                        //This is a non-critical procedure, and replacing it could interrupt a VARSCAT call
                        if (sqlFile.Contains("LogAppend"))
                        {
                            continue;
                        }

                        var msg = new LogMessage(LogSeverity.Info, $"Redeploying script {sqlFile}");
                        result.Messages.Add(msg);
                        string   scriptText   = File.ReadAllText(sqlFile);
                        string[] commandTexts = Regex.Split(scriptText + "\n", @"^\s*GO\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                        foreach (string commandText in commandTexts)
                        {
                            if (!string.IsNullOrWhiteSpace(commandText))
                            {
                                conn.Execute(commandText);
                            }
                        }
                    }
                }
            }
            catch (SqlException)
            {
                //eddsdbo can't connect to this case - it doesn't exist or isn't accessible
                //throw; // Used for integration tests
                return;                 // Do we really not want to throw in this case?  We'd be swallowing errors and progressing as successful anyway. :/
            }
        }