Строка подключения AWS Codebuild для SQL Server Linux - PullRequest
0 голосов
/ 20 мая 2019

Я пытаюсь создать приложение ASP.NET Core 2.2 с использованием AWS Codebuild

. Для этого я использую Dockerfile для выполнения следующих действий:

  • восстановление dotnet
  • Сборка
  • Модульные тесты (xUnit)
  • Интеграционные тесты (xUnit) с SQL Server

Для выполнения SQLЗависимость от сервера для интеграционных тестов позволяет AWS Codebuild запускать док-контейнер под управлением SQL Server Linux (это можно увидеть как часть фазы pre_build в файле buildspec.yml ниже

Проблема Iу меня есть то, что CodeBuild говорит, что приложение ASP.NET Core не может подключиться к контейнеру SQL Server Linux во время интеграционных тестов.

Я пробовал много разных комбинаций строки подключения, все из которых нене работает:

"Server=127.0.0.1,1433;Database=My.Database;User Id=sa;Password=SecurePassword!"
"Server=localhost,1433;Database=My.Database;User Id=sa;Password=SecurePassword!"
"Server=host.docker.internal,1433;Database=My.Database;User Id=sa;Password=SecurePassword!"

У меня есть Codebuild для запуска команды docker ps -a, поэтому я могу убедиться, что контейнер SQL Server Linux действительно работает на хосте сборки, и это так.

Пожалуйста, дайте мне знать, если какая-либо дополнительная информация будетбыть полезным.

Ошибка Codebuild возвращает:

Starting test execution, please wait... 
Master ConnectionString => Data Source=mssql,1433;Initial Catalog=master;User ID=sa;Password=*************** 
·[91m[xUnit.net 00:00:16.82]     MyApp.IntegrationTests.JobScenarios.Get_JobAsync_HappyPath_ReturnsOKStatusCode [FAIL] 
·[0mFailed   MyApp.IntegrationTests.JobScenarios.Get_JobAsync_HappyPath_ReturnsOKStatusCode 
Error Message: 
 System.Data.SqlClient.SqlException : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 35 - An internal exception was caught) 
---- System.Net.Internals.SocketExceptionFactory+ExtendedSocketException : No such device or address 
Stack Trace: 
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken) 
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) 
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) 
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) 
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) 
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) 
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) 
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) 
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) 
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) 
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) 
   at System.Data.SqlClient.SqlConnection.Open() 
   at SqlServerExtensions.SqlDatabase(SupportedDatabasesForEnsureDatabase supported, String connectionString, IUpgradeLog logger, Int32 timeout, AzureDatabaseEdition azureDatabaseEdition, String collation) 
   at MyApp.DBDeploy.DbUpDeploy.DeployDatabase(String connectionString) in /src/src/MyApp/DBDeploy/DbUpDeploy.cs:line 11 
   at MyApp.IntegrationTests.ScenariosBase`1.CreateTestServer() in /src/tests/MyApp.IntegrationTests/ScenariosBase.cs:line 56 
   at MyApp.IntegrationTests.Scenarios.Get_MyMethodAsync_HappyPath_ReturnsOKStatusCode() in /src/tests/MyApp.IntegrationTests/Scenarios.cs:line 98 
--- End of stack trace from previous location where exception was thrown --- 
----- Inner Stack Trace ----- 
   at System.Net.Dns.InternalGetHostByName(String hostName) 
   at System.Net.Dns.GetHostAddresses(String hostNameOrAddress) 
   at System.Data.SqlClient.SNI.SNITCPHandle.Connect(String serverName, Int32 port, TimeSpan timeout) 
   at System.Data.SqlClient.SNI.SNITCPHandle..ctor(String serverName, Int32 port, Int64 timerExpire, Object callbackObject, Boolean parallel) 

Моя конфигурация Codebuild выглядит следующим образом:

"projects": [
    {
        "logsConfig": {
            "s3Logs": {
                "status": "DISABLED"
            },
            "cloudWatchLogs": {
                "status": "ENABLED",
                "groupName": "/codebuild/test/"
            }
        },
        "timeoutInMinutes": 60,
        "name": "TestCodeBuildProject",
        "serviceRole": "arn:aws:iam::<account_id>:role/service-role/codebuild-TestCodeBuildProject-service-role",
        "tags": [],
        "artifacts": {
            "type": "NO_ARTIFACTS"
        },
        "lastModified": 1558382502.768,
        "cache": {
            "type": "NO_CACHE"
        },
        "created": 1558295505.314,
        "environment": {
            "computeType": "BUILD_GENERAL1_MEDIUM",
            "privilegedMode": true,
            "image": "aws/codebuild/standard:2.0",
            "type": "LINUX_CONTAINER",
            "environmentVariables": []
        },
        "source": {
            "buildspec": <buildspec.yml>,
            "insecureSsl": false,
            "location": "https://github.com/MyGitRepo.git",
            "gitCloneDepth": 1,
            "type": "GITHUB",
            "reportBuildStatus": false
        },
        "badge": {
            "badgeEnabled": false
        },
        "queuedTimeoutInMinutes": 480,
        "secondaryArtifacts": [],
        "secondarySources": [],
        "encryptionKey": "arn:aws:kms:<aws_region>:<account_id>:alias/aws/s3",
        "arn": "arn:aws:codebuild:<aws_region>:<account_id>:project/TestCodeBuildProject"
    }
]

Мой buildspec.yml файл выглядит следующим образом:

version: 0.2

env:
  variables:
    AWS_ACCOUNT_ID:     "<account_id>"
    AWS_DEFAULT_REGION: "<aws_region>"
    IMAGE_REPO_NAME:    "my-repo"
    IMAGE_TAG:          "my-tag"
    CONNECTION_STRING:  "Server=mssql,1433;Database=My.Database;User Id=sa;Password=SecurePassword!"
    DB_PASSWORD:        "SecurePassword!"

phases:
  install:
    runtime-versions:
      docker: 18
  pre_build:
    commands:
      - echo Logging into Amazon ECR...
      - $(aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION)
      - echo Spinning up database for integration tests...
      - docker run --name mssql -e ACCEPT_EULA=Y -e SA_PASSWORD="$DB_PASSWORD" -p 1433:1433 -d mcr.microsoft.com/mssql/server:2017-latest
  build:
    commands:
      - echo Building the Docker images
      - docker build --build-arg ENVIRONMENT=Development --build-arg CONNECTION_STRING="$CONNECTION_STRING" -t $IMAGE_REPO_NAME:$IMAGE_TAG --target final .
      - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazon.aws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
  post_build:
    commands:
      - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
...