Gabriel39 commented on code in PR #71174:
URL: https://github.com/apache/doris/pull/71174#discussion_r4795627341


##########
regression-test/suites/rpc_p0/test_internal_rpc_request_auth_lifecycle.groovy:
##########
@@ -0,0 +1,280 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+import 
org.apache.arrow.driver.jdbc.shaded.org.apache.arrow.memory.RootAllocator
+import 
org.apache.arrow.driver.jdbc.shaded.org.apache.arrow.vector.ipc.ArrowStreamReader
+import org.apache.doris.regression.suite.ConnectionInfo
+import org.apache.doris.regression.util.Http
+import org.apache.doris.thrift.BackendService
+import org.apache.doris.thrift.FrontendService
+import org.apache.doris.thrift.TScanCloseParams
+import org.apache.doris.thrift.TScanNextBatchParams
+import org.apache.doris.thrift.TScanOpenParams
+import org.apache.doris.thrift.TStatusCode
+import org.apache.thrift.protocol.TBinaryProtocol
+import org.apache.thrift.server.TThreadPoolServer
+import org.apache.thrift.transport.TServerSocket
+import org.apache.thrift.transport.TSocket
+
+import java.lang.reflect.InvocationTargetException
+import java.nio.file.Files
+import java.sql.DriverManager
+import java.sql.SQLException
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicBoolean
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.atomic.AtomicLong
+
+suite("test_internal_rpc_request_auth_lifecycle", "p0,nonConcurrent") {
+    // Owned PID checks require procfs; return before launching helpers on 
unsupported hosts.
+    if 
(!System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("linux")) {
+        logger.info("RPC authentication lifecycle fixture requires Linux; 
skipping on this host")
+        return
+    }
+    def logRoot = new File(System.getProperty("DORIS_HOME"), 
"regression-test/log").toPath()
+    Files.createDirectories(logRoot)
+    def logs = Files.createTempDirectory(logRoot, "request-auth-").toFile()
+    def helper = new File(context.file.parentFile, "request_auth_fixture.py")
+    def fixtureTestLog = new File(logs, "fixture-tests.log")
+    def fixtureTests = new ProcessBuilder("python3", "-m", "unittest", 
"discover", "-s", helper.parent,
+            "-p", "test_request_auth_fixture.py", 
"-v").redirectErrorStream(true)
+            .redirectOutput(fixtureTestLog).start()
+    try {
+        assertTrue(fixtureTests.waitFor(30, TimeUnit.SECONDS), "Fixture unit 
tests timed out; see ${logs}")
+        assertEquals(0, fixtureTests.exitValue(),
+                "Fixture unit tests failed; see 
${logs}\n${fixtureTestLog.getText('UTF-8')}")
+    } finally { fixtureTests.destroyForcibly() }
+    def process = new ProcessBuilder("python3", helper.absolutePath, 
"--package-home",
+            getConf("requestAuthPackageHome", 
System.getProperty("DORIS_HOME")), "--log-dir", logs.absolutePath)
+            .redirectError(new File(logs, "fixture.log")).start()
+    def reader = process.inputStream.newReader("UTF-8")
+    def writer = process.outputStream.newWriter("UTF-8")
+    def receive = { long seconds ->
+        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds)
+        while (!reader.ready() && process.isAlive() && System.nanoTime() < 
deadline) { Thread.sleep(100) }
+        assertTrue(reader.ready(), "Authentication fixture did not respond; 
see ${logs}")
+        new JsonSlurper().parseText(reader.readLine())
+    }
+    TThreadPoolServer metadataProxy = null
+    TServerSocket metadataTransport = null
+    def metadataExecutor = Executors.newSingleThreadExecutor()
+    def legacyMetadata = new AtomicBoolean(true)
+    def legacyResponses = new AtomicInteger()
+    def lastLegacyReplyNanos = new AtomicLong()
+    def legacyReplyGapNanos = new AtomicLong()
+    def upgradedResponses = new AtomicInteger()
+    try {
+        def endpoints = receive(450)
+        // Keep the origin FE/catalog and backend IDs unchanged while the 
remote metadata gains its identity.
+        def handler = 
java.lang.reflect.Proxy.newProxyInstance(FrontendService.Iface.classLoader,
+                [FrontendService.Iface] as Class[], { proxy, method, arguments 
->
+                    def socket = new TSocket("127.0.0.1", 
endpoints.remote.ports.fe.rpc_port as int, 10000)
+                    socket.open()
+                    try {
+                        def result = method.invoke(new 
FrontendService.Client(new TBinaryProtocol(socket)), arguments)
+                        if (method.name == "getBackendMeta") {
+                            if (legacyMetadata.get()) {
+                                result.unsetClusterId()
+                                long now = System.nanoTime()
+                                legacyReplyGapNanos.set(now - 
lastLegacyReplyNanos.getAndSet(now))
+                                legacyResponses.incrementAndGet()
+                            } else {
+                                upgradedResponses.incrementAndGet()
+                            }
+                        }
+                        return result
+                    } catch (InvocationTargetException failure) {
+                        throw failure.cause
+                    } finally { socket.close() }
+                } as java.lang.reflect.InvocationHandler)
+        metadataTransport = new TServerSocket(new ServerSocket(0, 50, 
InetAddress.loopbackAddress))
+        int metadataPort = metadataTransport.serverSocket.localPort
+        metadataProxy = new TThreadPoolServer(new 
TThreadPoolServer.Args(metadataTransport)
+                .processor(new 
FrontendService.Processor(handler)).minWorkerThreads(1).maxWorkerThreads(4))
+        def servingProxy = metadataProxy
+        metadataExecutor.submit({ servingProxy.serve() } as Runnable)
+        def withCluster = { ports, Closure action ->
+            String url = 
"jdbc:mysql://127.0.0.1:${ports.query_port}/?useLocalSessionState=true&useSSL=false"
 +
+                    "&connectTimeout=2000&socketTimeout=60000"
+            def previous = context.threadLocalConn.get()
+            try {
+                DriverManager.getConnection(url, "root", "").withCloseable { 
connection ->
+                    context.threadLocalConn.set(new ConnectionInfo(conn: 
connection, username: "root", password: ""))
+                    action.call()
+                }
+            } finally {
+                if (previous == null) { context.threadLocalConn.remove() }
+                else { context.threadLocalConn.set(previous) }
+            }
+        }
+        def waitReady = { Closure condition ->
+            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(120)
+            while (true) {
+                try { if (condition.call()) { return } } catch (SQLException 
pending) {
+                    if (System.nanoTime() >= deadline) { throw pending }
+                }
+                assertTrue(System.nanoTime() < deadline, "Fixture backends did 
not become ready; see ${logs}")
+                Thread.sleep(100)
+            }
+        }
+        [endpoints.local, endpoints.remote].each { endpoint ->
+            waitReady {
+                withCluster(endpoint.ports.fe) {
+                    sql_return_maparray("SHOW BACKENDS").count {
+                        it.Alive.toString().equalsIgnoreCase("true")
+                    } == endpoint.backends.size()
+                }
+            }
+            withCluster(endpoint.ports.fe) {
+                assertEquals("true", sql("ADMIN SHOW FRONTEND CONFIG LIKE 
'%enable_all_http_auth'")[0][1])
+                sql "CREATE DATABASE IF NOT EXISTS rpc_auth_fixture"
+                sql "DROP TABLE IF EXISTS rpc_auth_fixture.rpc_auth_source"
+                sql """CREATE TABLE rpc_auth_fixture.rpc_auth_source (id INT, 
value STRING)
+                       DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 8
+                       PROPERTIES ("replication_num"="1")"""
+            }
+        }
+        withCluster(endpoints.remote.ports.fe) {
+            sql "INSERT INTO rpc_auth_fixture.rpc_auth_source VALUES 
(10,'ten'),(20,'twenty')"
+            assertEquals(2, endpoints.remote.backends.size())
+            assertEquals(2, sql_return_maparray("SHOW TABLETS FROM 
rpc_auth_fixture.rpc_auth_source")
+                    .collect { it.BackendId }.toSet().size())
+        }
+        withCluster(endpoints.local.ports.fe) {
+            sql "INSERT INTO rpc_auth_fixture.rpc_auth_source VALUES 
(1,'one'),(2,'two')"
+            sql "DROP CATALOG IF EXISTS rpc_auth_remote"
+            sql """CREATE CATALOG rpc_auth_remote PROPERTIES (
+                   "type"="doris", 
"fe_http_hosts"="http://127.0.0.1:${endpoints.remote.ports.fe.http_port}";,
+                   "fe_thrift_hosts"="127.0.0.1:${metadataPort}",
+                   
"fe_arrow_hosts"="127.0.0.1:${endpoints.remote.ports.fe.arrow_flight_sql_port}",
+                   "user"="root", "password"="", "use_arrow_flight"="false")"""
+            // An enforcing upgraded worker rejects the legacy metadata's 
unknown destination namespace.
+            test {
+                sql "SELECT id,value FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source ORDER BY id"
+                exception "NOT_AUTHORIZED"
+            }
+            assertTrue(legacyResponses.get() > 0)
+            int warmMetadataRequests = legacyResponses.get()
+            test {
+                sql "SELECT id,value FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source ORDER BY id"
+                exception "NOT_AUTHORIZED"
+            }
+            // Recent unknown identities are shared across queries; a slow 
query may span the cooldown.
+            int refreshed = legacyResponses.get() - warmMetadataRequests
+            assertTrue(refreshed <= 1, "Identity resolution must remain 
independent of worker count")
+            if (refreshed > 0) {
+                assertTrue(legacyReplyGapNanos.get() >= 
TimeUnit.SECONDS.toNanos(5),
+                        "Legacy metadata was polled before the 
unknown-identity cooldown expired")
+            }
+            legacyMetadata.set(false)
+            // Wait out the five-second negative cache; the first upgraded 
query must succeed without retries.
+            TimeUnit.SECONDS.sleep(6)
+            qt_remote_native "SELECT id,value FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source ORDER BY id"
+            qt_cross_cluster_join """SELECT l.id,r.value FROM 
rpc_auth_fixture.rpc_auth_source l
+                    JOIN rpc_auth_remote.rpc_auth_fixture.rpc_auth_source r ON 
r.id=l.id*10 ORDER BY l.id"""
+            sql "CREATE TABLE rpc_auth_fixture.rpc_auth_copy LIKE 
rpc_auth_fixture.rpc_auth_source"
+            sql """INSERT INTO rpc_auth_fixture.rpc_auth_copy
+                   SELECT id,value FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source"""
+            qt_cross_cluster_insert "SELECT id,value FROM 
rpc_auth_fixture.rpc_auth_copy ORDER BY id"
+        }
+        assertTrue(upgradedResponses.get() > 0, "The live origin must refresh 
legacy destination metadata")
+        def probe = { String key ->
+            def connection = new 
URL("http://127.0.0.1:${endpoints.remote.ports.be.brpc_port}/"; +
+                    
"doris.PBackendService/hand_shake").openConnection(Proxy.NO_PROXY)
+            connection.requestMethod = "POST"
+            connection.connectTimeout = 5000
+            connection.readTimeout = 5000
+            connection.doOutput = true
+            connection.setRequestProperty("Content-Type", "application/json")
+            try {
+                connection.outputStream.withCloseable {
+                    it.write(JsonOutput.toJson([frontend_public_key: 
key]).getBytes("UTF-8"))
+                }
+                assertEquals(200, connection.responseCode)
+                connection.inputStream.withCloseable { new 
JsonSlurper().parse(it).frontend_key_registered }
+            } finally { connection.disconnect() }
+        }
+        assertEquals(false, probe("unregistered authority"), "Remote BE must 
keep authentication enabled")
+        assertEquals(true, probe(endpoints.local.public_key))
+
+        def exported = 
Http.POST("http://127.0.0.1:${endpoints.local.ports.fe.http_port}/"; +
+                "api/rpc_auth_fixture/rpc_auth_source/_query_plan",
+                [sql: "SELECT id FROM rpc_auth_fixture.rpc_auth_source"], 
true, "root", "")
+        assertEquals(0, exported.code, exported.toString())
+        assertEquals(200, exported.data.status, exported.data.toString())
+        // Trust in an issuing FE must not make a plan valid in a different 
destination cluster.
+        def remoteSocket = new TSocket("127.0.0.1", 
endpoints.remote.ports.be.be_port as int, 10000)
+        remoteSocket.open()
+        try {
+            def remoteClient = new BackendService.Client(new 
TBinaryProtocol(remoteSocket))
+            def wrongCluster = new 
TScanOpenParams().setCluster("default_cluster").setDatabase("rpc_auth_fixture")
+                    
.setTable("rpc_auth_source").setTabletIds(exported.data.partitions.keySet().collect
 { it as long })
+                    
.setOpaquedQueryPlan(exported.data.opaqued_query_plan).setUser("root").setPasswd("")
+            assertEquals(TStatusCode.NOT_AUTHORIZED, 
remoteClient.openScanner(wrongCluster).status.statusCode)
+        } finally { remoteSocket.close() }
+        // Reopen exactly the same snapshot bytes after the issuer restarts 
and heartbeats again.
+        writer.write("restart-local\n"); writer.flush()
+        assertEquals(true, receive(180).ok)
+        withCluster(endpoints.local.ports.fe) {
+            qt_after_master_restart "SELECT count(*) FROM 
rpc_auth_remote.rpc_auth_fixture.rpc_auth_source"
+        }
+        Thread.sleep(3000)
+        String route = 
exported.data.partitions.values().first().routings.first()
+        String host = route.substring(0, route.lastIndexOf(':')).replace('[', 
'').replace(']', '')
+        int port = route.substring(route.lastIndexOf(':') + 1) as int
+        def socket = new TSocket(host, port, 10000)
+        socket.open()
+        def allocator = new RootAllocator()
+        try {
+            def client = new BackendService.Client(new TBinaryProtocol(socket))
+            def params = new 
TScanOpenParams().setCluster("default_cluster").setDatabase("rpc_auth_fixture")
+                    
.setTable("rpc_auth_source").setTabletIds(exported.data.partitions.keySet().collect
 { it as long })
+                    
.setOpaquedQueryPlan(exported.data.opaqued_query_plan).setUser("root").setPasswd("")
+            def opened = client.openScanner(params)
+            assertEquals(TStatusCode.OK, opened.status.statusCode, 
opened.toString())
+            long rows = 0
+            try {
+                while (true) {
+                    def batch = client.getNext(new 
TScanNextBatchParams().setContextId(opened.contextId).setOffset(rows))
+                    assertEquals(TStatusCode.OK, batch.status.statusCode, 
batch.toString())
+                    if (batch.eos) { break }
+                    def arrow = new ArrowStreamReader(new 
ByteArrayInputStream(batch.rows), allocator)
+                    try { while (arrow.loadNextBatch()) { rows += 
arrow.vectorSchemaRoot.rowCount } }
+                    finally { arrow.close() }
+                }
+            } finally { client.closeScanner(new 
TScanCloseParams().setContextId(opened.contextId)) }
+            assertEquals(2L, rows)
+        } finally { allocator.close(); socket.close() }
+
+    } finally {
+        try {
+            // Stop the origin first so its pooled metadata sockets cannot 
keep the proxy workers blocked.
+            try { writer.close() } catch (IOException ignored) { }
+            try { assertTrue(process.waitFor(60, TimeUnit.SECONDS), "Fixture 
did not stop; see ${logs}") }
+            finally { process.destroyForcibly(); reader.close() }

Review Comment:
   Fixed in f2850cae26d7. Teardown first closes stdin, then sends SIGTERM and 
waits for Python cleanup before escalating. Launch bookkeeping also protects 
the fork-to-PID-publication window: the fixture records the launcher process 
group before unblocking SIGTERM and revalidates ownership before stopping its 
daemons. Private key roots are removed in finally.
   
   The regression preflight interrupts startup before PID publication and while 
readiness is pending, then checks daemon termination and key removal. Nested 
test budgets now include those bounded cleanup waits; the final packaged 
lifecycle and TLS suites pass with the cleanup assertions intact.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to