Skip to content

Commit

Permalink
#8 Добавил получение контейнера AD-сервиса
Browse files Browse the repository at this point in the history
  • Loading branch information
GregoryGhost committed Apr 15, 2020
1 parent 0cfcf36 commit 61c93ba
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 33 deletions.
1 change: 1 addition & 0 deletions Idone/Idone.Security/Services/AdService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public AdService(string domain)
{
throw new NullReferenceException($"Пустой аргумент {nameof(domain)}");
}

if (!Dns.GetHostAddresses(domain).Any())
{
var msg = $"Не найден домен сервиса Active Directory для переданного аргумента {nameof(domain)}";
Expand Down
34 changes: 31 additions & 3 deletions Idone/Idone.Tests/Constants.fs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
namespace Idone.Tests.Constants

open Idone.DAL.DTO
open Idone.Tests.Types

[<AutoOpen>]
module Constants =
open Idone.DAL.DTO
open Idone.Tests.Types
open Docker.DotNet

let FIRST_PAGE = new Pagination(10, 1)

let ADMIN_AND_USER_ROLES : Role list =
Expand Down Expand Up @@ -52,4 +53,31 @@ module Constants =
SaPswd = SA_PSWD
Database = DATABASE_TESTS
}.toEnv

let makeDbContainerSettings (client : DockerClient) : ContainerSettings =
{
Client = client
Image = "mcr.microsoft.com/mssql/server"
Tag = "2019-CU3-ubuntu-18.04"
Port = "1433"
Env = DOCKER_DB_ENV
}

let SETTINGS_FILE_NAME = "appsettings.Development.json"

let DOCKER_AD_ENV : ResizeArray<string> =
{
AcceptEula = true
SaPswd = SA_PSWD
Database = DATABASE_TESTS
}.toEnv

let makeAdContainerSettings (client : DockerClient) : ContainerSettings =
{
Client = client
Image = "osixia/openldap"
Tag = "1.3.0"
Port = "1434"
Env = DOCKER_AD_ENV
}

8 changes: 8 additions & 0 deletions Idone/Idone.Tests/Helpers/FakeStartup.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Idone.Tests.Helpers

open Microsoft.Extensions.Configuration
open Idone.Back

type FakeStartup(config: IConfiguration) =
inherit Startup(config)

1 change: 1 addition & 0 deletions Idone/Idone.Tests/Idone.Tests.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<Compile Include="Helpers\TypeWorkers\RoleWorker.fs" />
<Compile Include="Helpers\TypeWorkers\PermissionWorker.fs" />
<Compile Include="Helpers\IdoneApiWrapper.fs" />
<Compile Include="Helpers\FakeStartup.fs" />
<Compile Include="Startup.fs" />
<Content Include="appsettings.Development.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
Expand Down
62 changes: 37 additions & 25 deletions Idone/Idone.Tests/Sample.fs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,14 @@ module Tests =
let inline toDict (map : ('a * 'b) list) : IDictionary<'a, 'b> =
map |> Map.ofList |> Map.toSeq |> dict

let private getContainer (client : DockerClient) (image : string) (tag : string) : ContainerResponse =
let private getContainer (containerSettings: ContainerSettings) : ContainerResponse =
let imagesList = new ImagesListParameters()
let (client, image, tag, env, port) =
(containerSettings.Client,
containerSettings.Image,
containerSettings.Tag,
containerSettings.Env,
containerSettings.Port)
let imageMatchName = sprintf "%s:%s" image tag
imagesList.MatchName <- imageMatchName

Expand All @@ -47,14 +53,14 @@ module Tests =

let containerParameters : ContainerParams =
let cp = new CreateContainerParameters()
cp.Env <- DOCKER_DB_ENV
cp.ExposedPorts <- [DEFAULT_DOCKER_DB_PORT, new EmptyStruct()] |> toDict
cp.Env <- env
cp.ExposedPorts <- [port, new EmptyStruct()] |> toDict
let hostConfig = new HostConfig()
let portBind = new PortBinding()
let localIp = "0.0.0.0"
portBind.HostIP <- localIp
portBind.HostPort <- sprintf "%s/tcp" DEFAULT_DOCKER_DB_PORT
hostConfig.PortBindings <- [DEFAULT_DOCKER_DB_PORT, [portBind] |> ResizeArray<PortBinding> :> IList<PortBinding> ] |> toDict
portBind.HostPort <- sprintf "%s/tcp" port
hostConfig.PortBindings <- [port, [portBind] |> ResizeArray<PortBinding> :> IList<PortBinding> ] |> toDict
cp.HostConfig <- hostConfig
cp.Image <- imageMatchName

Expand Down Expand Up @@ -90,60 +96,66 @@ module Tests =
return ipDb
}

return { Response = container; HostPort = DEFAULT_DOCKER_DB_PORT; Ip = dataBaseIp }
return { Response = container; HostPort = port; Ip = dataBaseIp }
}
Async.RunSynchronously <| containerResponse()

let private removeDockerContainer (docker : Docker) : Async<unit> =
async {
let! stopContainerResult =
docker.Client.Containers.StopContainerAsync(docker.ContainerResponse.ID,
new ContainerStopParameters(),
CancellationToken.None) |> Async.AwaitTask
if stopContainerResult then
return! docker.Client.Containers.RemoveContainerAsync(docker.ContainerResponse.ID,
new ContainerRemoveParameters(),
CancellationToken.None) |> Async.AwaitTask
for container in docker.Containers do
let! stopContainerResult =
docker.Client.Containers.StopContainerAsync(container.ID,
new ContainerStopParameters(),
CancellationToken.None) |> Async.AwaitTask
if stopContainerResult then
return! docker.Client.Containers.RemoveContainerAsync(container.ID,
new ContainerRemoveParameters(),
CancellationToken.None) |> Async.AwaitTask
if docker.Client <> null then
docker.Client.Dispose()
}

let private initDi (connString : string) : ServiceProvider =
let private initDi (connString : string) (domain : string) : ServiceProvider =
let services = new ServiceCollection()
let config = (new ConfigurationBuilder())(*.AddJsonFile(SETTINGS_FILE_NAME, false, true)*).Build()
let _ = new FakeStartup(config)
config.GetSection("ActiveDirectory").GetSection("domain").Value <- domain
services.AddIdoneIdentity()
.AddIdoneDb(connString)
.AddSecurityDi() |> ignore
.AddSecurityDi(config) |> ignore
let rootServiceProvider = services.BuildServiceProvider()
use scope = rootServiceProvider.CreateScope()
scope.ServiceProvider.GetRequiredService<AppContext>().InitTest()

rootServiceProvider

let private initTestEnviroment() : TestEnviroment =
//TODO: создать контейнер для AD сервера
//TODO: зарегать тестового пользователя в AD
let private initTestEnviroment() : TestEnvironment =
let dockerClient =
// let url = new Uri("npipe://./pipe/docker_engine") for windows
let url = new Uri("unix:///var/run/docker.sock") //for unix
let config = new DockerClientConfiguration(url, credentials = null, defaultTimeout = TimeSpan.FromSeconds 10000.)
config.CreateClient()
let (containerResponse, hostPort, dbIp) =
let containerInfo = getContainer dockerClient "mcr.microsoft.com/mssql/server" "2019-CU3-ubuntu-18.04"
let (dbContainer, hostPort, dbIp) =
let containerInfo = getContainer <| makeDbContainerSettings dockerClient
(containerInfo.Response, containerInfo.HostPort, containerInfo.Ip)

let (adContainer, adIp) =
let containerInfo = getContainer <| makeAdContainerSettings dockerClient
(containerInfo.Response, containerInfo.Ip)
let containers = [dbContainer; adContainer]
let connString = makeDatabaseSettings { IpAddress = dbIp; Port = hostPort }

let di =
try
initDi connString
initDi connString adIp
with
| :? Exception as ex ->
let docker = { ContainerResponse = containerResponse; Client = dockerClient }
let docker = { Containers = containers; Client = dockerClient }
eprintf "connstring = %s" connString
eprintf "ad domain = %s" adIp
removeDockerContainer docker |> Async.RunSynchronously
raise ex

let dbEnv = TestEnviroment.create di dockerClient containerResponse
let dbEnv = TestEnvironment.create di dockerClient containers

dbEnv

Expand Down
36 changes: 31 additions & 5 deletions Idone/Idone.Tests/Types.fs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ open Docker.DotNet.Models
open Microsoft.Extensions.DependencyInjection


module Helpers =
let (^) param value = sprintf "%s=%s" param value

open Helpers

type Role =
{
Name : string
Expand Down Expand Up @@ -55,7 +60,6 @@ type DockerDatabaseEnv =
Database : string
}
member __.toEnv : ResizeArray<string> =
let (^) param value = sprintf "%s=%s" param value
let ae = if __.AcceptEula then "Y" else "F"

[
Expand All @@ -64,26 +68,39 @@ type DockerDatabaseEnv =
"Database" ^ __.Database
] |> ResizeArray<string>

type DockerActiveDirectoryEnv =
{
Organisation : string
Domain : string
AdminPassword : string
}
member __.toEnv : ResizeArray<string> =
[
"LDAP_ORGANISATION" ^ __.Organisation
"LDAP_DOMAIN" ^ __.Domain
"LDAP_ADMIN_PASSWORD" ^ __.AdminPassword
] |> ResizeArray<string>

type Docker =
{
Client : DockerClient
ContainerResponse: CreateContainerResponse
Containers: CreateContainerResponse list
}

type TestEnviroment =
type TestEnvironment =
{
ServiceProvider : ServiceProvider
Docker : Docker
}
static member create (provider : ServiceProvider)
(dockerClient : DockerClient)
(containerResponse : CreateContainerResponse) : TestEnviroment =
(containers : CreateContainerResponse list) : TestEnvironment =
{
ServiceProvider = provider
Docker =
{
Client = dockerClient
ContainerResponse = containerResponse
Containers = containers
}
}

Expand All @@ -98,4 +115,13 @@ type ContainerParams =
{
ContainerParameters : CreateContainerParameters
LocalIp : string
}

type ContainerSettings =
{
Client : DockerClient
Image : string
Tag : string
Port : string
Env : ResizeArray<string>
}

0 comments on commit 61c93ba

Please sign in to comment.