Search in sources :

Example 21 with TestingTrinoServer

use of io.trino.server.testing.TestingTrinoServer in project trino by trinodb.

the class DistributedQueryRunner method createTestingTrinoServer.

private static TestingTrinoServer createTestingTrinoServer(URI discoveryUri, boolean coordinator, Map<String, String> extraProperties, String environment, Module additionalModule, Optional<Path> baseDataDir, List<SystemAccessControl> systemAccessControls, List<EventListener> eventListeners) {
    long start = System.nanoTime();
    ImmutableMap.Builder<String, String> propertiesBuilder = ImmutableMap.<String, String>builder().put("internal-communication.shared-secret", "test-secret").put("query.client.timeout", "10m").put("discovery.http-client.min-threads", // default 8
    "1").put("exchange.http-client.min-threads", // default 8
    "1").put("node-manager.http-client.min-threads", // default 8
    "1").put("exchange.page-buffer-client.max-callback-threads", // default 25
    "5").put("exchange.http-client.idle-timeout", "1h").put("task.max-index-memory", // causes index joins to fault load
    "16kB").put("distributed-index-joins-enabled", "true");
    if (coordinator) {
        propertiesBuilder.put("node-scheduler.include-coordinator", "true");
        propertiesBuilder.put("join-distribution-type", "PARTITIONED");
        // Use few threads in tests to preserve resources on CI
        // default 8
        propertiesBuilder.put("failure-detector.http-client.min-threads", "1");
        // default 8
        propertiesBuilder.put("memoryManager.http-client.min-threads", "1");
        // default 8
        propertiesBuilder.put("scheduler.http-client.min-threads", "1");
        // default 8
        propertiesBuilder.put("workerInfo.http-client.min-threads", "1");
    }
    HashMap<String, String> properties = new HashMap<>(propertiesBuilder.buildOrThrow());
    properties.putAll(extraProperties);
    TestingTrinoServer server = TestingTrinoServer.builder().setCoordinator(coordinator).setProperties(properties).setEnvironment(environment).setDiscoveryUri(discoveryUri).setAdditionalModule(additionalModule).setBaseDataDir(baseDataDir).setSystemAccessControls(systemAccessControls).setEventListeners(eventListeners).build();
    String nodeRole = coordinator ? "coordinator" : "worker";
    log.info("Created %s TestingTrinoServer in %s: %s", nodeRole, nanosSince(start).convertToMostSuccinctTimeUnit(), server.getBaseUrl());
    return server;
}
Also used : HashMap(java.util.HashMap) ImmutableMap(com.google.common.collect.ImmutableMap) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer)

Example 22 with TestingTrinoServer

use of io.trino.server.testing.TestingTrinoServer in project trino by trinodb.

the class TestMemoryWorkerCrash method closeWorker.

private void closeWorker() throws Exception {
    int nodeCount = getNodeCount();
    TestingTrinoServer worker = getDistributedQueryRunner().getServers().stream().filter(server -> !server.isCoordinator()).findAny().orElseThrow(() -> new IllegalStateException("No worker nodes"));
    worker.close();
    waitForNodes(nodeCount - 1);
}
Also used : TestingTrinoServer(io.trino.server.testing.TestingTrinoServer)

Example 23 with TestingTrinoServer

use of io.trino.server.testing.TestingTrinoServer in project trino by trinodb.

the class TestMemoryManager method testOutOfMemoryKiller.

@Test(timeOut = 240_000, expectedExceptions = ExecutionException.class, expectedExceptionsMessageRegExp = ".*Query killed because the cluster is out of memory. Please try again in a few minutes.")
public void testOutOfMemoryKiller() throws Exception {
    Map<String, String> properties = ImmutableMap.<String, String>builder().put("query.low-memory-killer.delay", "5s").put("query.low-memory-killer.policy", "total-reservation").buildOrThrow();
    try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) {
        // Reserve all the memory
        QueryId fakeQueryId = new QueryId("fake");
        for (TestingTrinoServer server : queryRunner.getServers()) {
            MemoryPool memoryPool = server.getLocalMemoryManager().getMemoryPool();
            assertTrue(memoryPool.tryReserve(fakeQueryId, "test", memoryPool.getMaxBytes()));
        }
        List<Future<?>> queryFutures = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk")));
        }
        // Wait for one of the queries to die
        waitForQueryToBeKilled(queryRunner);
        for (TestingTrinoServer server : queryRunner.getServers()) {
            MemoryPool pool = server.getLocalMemoryManager().getMemoryPool();
            assertTrue(pool.getReservedBytes() > 0);
            // Free up the entire pool
            pool.free(fakeQueryId, "test", pool.getMaxBytes());
            assertTrue(pool.getFreeBytes() > 0);
        }
        for (Future<?> query : queryFutures) {
            query.get();
        }
    }
}
Also used : DistributedQueryRunner(io.trino.testing.DistributedQueryRunner) QueryId(io.trino.spi.QueryId) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Test(org.testng.annotations.Test)

Example 24 with TestingTrinoServer

use of io.trino.server.testing.TestingTrinoServer in project trino by trinodb.

the class TestMemoryManager method testNoLeak.

private void testNoLeak(@Language("SQL") String query) throws Exception {
    Map<String, String> properties = ImmutableMap.<String, String>builder().put("task.verbose-stats", "true").buildOrThrow();
    try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) {
        executor.submit(() -> queryRunner.execute(query)).get();
        for (BasicQueryInfo info : queryRunner.getCoordinator().getQueryManager().getQueries()) {
            assertEquals(info.getState(), FINISHED);
        }
        // Make sure we didn't leak any memory on the workers
        for (TestingTrinoServer worker : queryRunner.getServers()) {
            MemoryPool pool = worker.getLocalMemoryManager().getMemoryPool();
            assertEquals(pool.getMaxBytes(), pool.getFreeBytes());
        }
    }
}
Also used : DistributedQueryRunner(io.trino.testing.DistributedQueryRunner) BasicQueryInfo(io.trino.server.BasicQueryInfo) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer)

Example 25 with TestingTrinoServer

use of io.trino.server.testing.TestingTrinoServer in project trino by trinodb.

the class TestResourceSecurity method testPasswordAuthenticatorUserMapping.

@Test
public void testPasswordAuthenticatorUserMapping() throws Exception {
    try (TestingTrinoServer server = TestingTrinoServer.builder().setProperties(ImmutableMap.<String, String>builder().putAll(SECURE_PROPERTIES).put("password-authenticator.config-files", passwordConfigDummy.toString()).put("http-server.authentication.type", "password").put("http-server.authentication.password.user-mapping.pattern", ALLOWED_USER_MAPPING_PATTERN).buildOrThrow()).setAdditionalModule(binder -> jaxrsBinder(binder).bind(TestResource.class)).build()) {
        server.getInstance(Key.get(PasswordAuthenticatorManager.class)).setAuthenticators(TestResourceSecurity::authenticate);
        server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(TestSystemAccessControl.WITH_IMPERSONATION);
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        // Test sets basic auth user and X-Trino-User, and the authenticator is performing user mapping.
        // Normally this would result in an impersonation check to the X-Trino-User, but the password
        // authenticator has a hack to clear X-Trino-User in this case.
        Request request = new Request.Builder().url(getLocation(httpServerInfo.getHttpsUri(), "/protocol/identity")).addHeader("Authorization", Credentials.basic(TEST_USER_LOGIN, TEST_PASSWORD)).addHeader("X-Trino-User", TEST_USER_LOGIN).build();
        try (Response response = client.newCall(request).execute()) {
            assertEquals(response.code(), SC_OK);
            assertEquals(response.header("user"), TEST_USER);
            assertEquals(response.header("principal"), TEST_USER_LOGIN);
        }
    }
}
Also used : AccessDeniedException.denyReadSystemInformationAccess(io.trino.spi.security.AccessDeniedException.denyReadSystemInformationAccess) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) AccessControlManager(io.trino.security.AccessControlManager) ZonedDateTime(java.time.ZonedDateTime) NodeInfo(io.airlift.node.NodeInfo) Test(org.testng.annotations.Test) HttpServerConfig(io.airlift.http.server.HttpServerConfig) SystemSecurityContext(io.trino.spi.security.SystemSecurityContext) JwsHeader(io.jsonwebtoken.JwsHeader) HttpCookie(java.net.HttpCookie) Matcher(java.util.regex.Matcher) JwtBuilder(io.jsonwebtoken.JwtBuilder) Map(java.util.Map) Path(java.nio.file.Path) Assert.assertEquals(io.trino.testing.assertions.Assert.assertEquals) PemReader(io.airlift.security.pem.PemReader) CookieJar(okhttp3.CookieJar) Request(okhttp3.Request) HttpServlet(javax.servlet.http.HttpServlet) SET_COOKIE(javax.ws.rs.core.HttpHeaders.SET_COOKIE) JavaNetCookieJar(okhttp3.JavaNetCookieJar) Set(java.util.Set) PreparedStatementEncoder(io.trino.server.protocol.PreparedStatementEncoder) BasicPrincipal(io.trino.spi.security.BasicPrincipal) HttpServerInfo(io.airlift.http.server.HttpServerInfo) AccessControl(io.trino.security.AccessControl) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) ProtocolConfig(io.trino.server.ProtocolConfig) AccessDeniedException(io.trino.spi.security.AccessDeniedException) NONCE(io.trino.server.security.oauth2.OAuth2Service.NONCE) GET(javax.ws.rs.GET) OkHttpUtil.setupSsl(io.trino.client.OkHttpUtil.setupSsl) MINUTES(java.util.concurrent.TimeUnit.MINUTES) LOCATION(javax.ws.rs.core.HttpHeaders.LOCATION) HttpServletRequest(javax.servlet.http.HttpServletRequest) Identity(io.trino.spi.security.Identity) Response(okhttp3.Response) SC_UNAUTHORIZED(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) IOException(java.io.IOException) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) File(java.io.File) WWW_AUTHENTICATE(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE) OkHttpClient(okhttp3.OkHttpClient) ChronoUnit(java.time.temporal.ChronoUnit) Paths(java.nio.file.Paths) OAUTH2_COOKIE(io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE) AllowAllSystemAccessControl(io.trino.plugin.base.security.AllowAllSystemAccessControl) Module(com.google.inject.Module) AUTHENTICATED_USER(io.trino.server.security.ResourceSecurity.AccessType.AUTHENTICATED_USER) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Key(com.google.inject.Key) AUTHORIZATION(com.google.common.net.HttpHeaders.AUTHORIZATION) SC_SEE_OTHER(javax.servlet.http.HttpServletResponse.SC_SEE_OTHER) URI(java.net.URI) WEB_UI(io.trino.server.security.ResourceSecurity.AccessType.WEB_UI) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) OptionalBinder.newOptionalBinder(com.google.inject.multibindings.OptionalBinder.newOptionalBinder) ImmutableSet(com.google.common.collect.ImmutableSet) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) BeforeClass(org.testng.annotations.BeforeClass) Assert.assertNotNull(org.testng.Assert.assertNotNull) Credentials(okhttp3.Credentials) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Base64(java.util.Base64) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Principal(java.security.Principal) CookieManager(java.net.CookieManager) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) HttpUriBuilder.uriBuilderFrom(io.airlift.http.client.HttpUriBuilder.uriBuilderFrom) JaxrsBinder.jaxrsBinder(io.airlift.jaxrs.JaxrsBinder.jaxrsBinder) MetadataManager.createTestMetadataManager(io.trino.metadata.MetadataManager.createTestMetadataManager) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) Pattern(java.util.regex.Pattern) HttpUrl(okhttp3.HttpUrl) Instant.now(java.time.Instant.now) DataProvider(org.testng.annotations.DataProvider) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) OAuth2Client(io.trino.server.security.oauth2.OAuth2Client) Headers(okhttp3.Headers) AtomicReference(java.util.concurrent.atomic.AtomicReference) Inject(javax.inject.Inject) Cookie(okhttp3.Cookie) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpRequestSessionContextFactory(io.trino.server.HttpRequestSessionContextFactory) UI_LOCATION(io.trino.server.ui.FormWebUiAuthenticationFilter.UI_LOCATION) TestingHttpServer(io.airlift.http.server.testing.TestingHttpServer) Keys.hmacShaKeyFor(io.jsonwebtoken.security.Keys.hmacShaKeyFor) AccessDeniedException.denyImpersonateUser(io.trino.spi.security.AccessDeniedException.denyImpersonateUser) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) SC_FORBIDDEN(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN) Assert.assertTrue(org.testng.Assert.assertTrue) TRINO_HEADERS(io.trino.client.ProtocolHeaders.TRINO_HEADERS) Response(okhttp3.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) JwtBuilder(io.jsonwebtoken.JwtBuilder) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) Request(okhttp3.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServerInfo(io.airlift.http.server.HttpServerInfo) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Test(org.testng.annotations.Test)

Aggregations

TestingTrinoServer (io.trino.server.testing.TestingTrinoServer)41 Test (org.testng.annotations.Test)33 HttpServerInfo (io.airlift.http.server.HttpServerInfo)28 ImmutableMap (com.google.common.collect.ImmutableMap)16 ImmutableSet (com.google.common.collect.ImmutableSet)14 Iterables.getOnlyElement (com.google.common.collect.Iterables.getOnlyElement)14 Resources (com.google.common.io.Resources)14 AUTHORIZATION (com.google.common.net.HttpHeaders.AUTHORIZATION)14 Key (com.google.inject.Key)14 OptionalBinder.newOptionalBinder (com.google.inject.multibindings.OptionalBinder.newOptionalBinder)14 HttpUriBuilder.uriBuilderFrom (io.airlift.http.client.HttpUriBuilder.uriBuilderFrom)14 HttpServerConfig (io.airlift.http.server.HttpServerConfig)14 TestingHttpServer (io.airlift.http.server.testing.TestingHttpServer)14 JaxrsBinder.jaxrsBinder (io.airlift.jaxrs.JaxrsBinder.jaxrsBinder)14 NodeInfo (io.airlift.node.NodeInfo)14 PemReader (io.airlift.security.pem.PemReader)14 JwsHeader (io.jsonwebtoken.JwsHeader)14 JwtBuilder (io.jsonwebtoken.JwtBuilder)14 Keys.hmacShaKeyFor (io.jsonwebtoken.security.Keys.hmacShaKeyFor)14 OkHttpUtil.setupSsl (io.trino.client.OkHttpUtil.setupSsl)14