DEV Community

Query Filter
Query Filter

Posted on

gradle7

plugins {
    id 'java'
}

// ---------------------------
// 1️⃣ Repositories and dependencies
// ---------------------------
repositories {
    maven { url "https://your-artifactory/repo" } // replace with your Artifactory
    mavenCentral()
}

dependencies {
    implementation 'net.bytebuddy:byte-buddy:1.11.13'
    implementation 'net.bytebuddy:byte-buddy-agent:1.11.13'
}

// ---------------------------
// 2️⃣ JavaExec task for your external main
// ---------------------------
task runQuantum(type: JavaExec, dependsOn: [compileJava, buildAgent]) {
    group = 'instances'
    description = 'Run Quantum Server with forced hostname and username'

    mainClass = 'bootstrap.BootstrapServer'
    classpath = sourceSets.main.runtimeClasspath + files('libs/external-jars')

    // JVM args: attach agent and other properties
    def forcedHostname = "egtpsga56.nam.nsroot.net"
    def forcedUserName = "forcedUser"
    jvmArgs(
        "-javaagent:${buildAgent.archiveFile.get().asFile}=${forcedHostname};${forcedUserName}",
        "-Ddds.tmpdir=${buildDir}/dds_tmp"
    )

    args "file://src/main/config/quantum/\$asset/\$region/\$env", instanceName, "dummy"
    standardInput = System.in

    doFirst {
        println "=== JVM Args ==="
        println jvmArgs
        println "=== Agent JAR ==="
        println buildAgent.archiveFile.get().asFile
    }
}

// ---------------------------
// 3️⃣ Agent tasks (all encapsulated in a subroutine at the end)
// ---------------------------
def configureAgentTasks() {
    def agentSrcDir = file("$buildDir/agent-src/agent")
    agentSrcDir.mkdirs()

    // Subroutine to generate agent source code
    def generateAgentSource = {
        def agentJava = new File(agentSrcDir, "ForceHostnameAgent.java")
        agentJava.text = """
package agent;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import java.lang.instrument.Instrumentation;
import static net.bytebuddy.matcher.ElementMatchers.*;

public class ForceHostnameAgent {

    public static void premain(String agentArgs, Instrumentation inst) {
        String[] parts = agentArgs != null ? agentArgs.split(";") : new String[0];
        final String forcedHost = parts.length > 0 ? parts[0] : "forced-hostname";
        final String forcedUser = parts.length > 1 ? parts[1] : "forced-user";

        new AgentBuilder.Default()
            .type(named("com.citi.rio.umb")) // target class
            .transform((builder, typeDescription, classLoader, module) ->
                builder
                    .method(named("getCurrentCanonicalHostname"))
                        .intercept(Advice.to(HostnameAdvice.class))
                    .method(named("getCurrentUserName"))
                        .intercept(Advice.to(UserNameAdvice.class))
            ).installOn(inst);

        HostnameAdvice.forcedHost = forcedHost;
        UserNameAdvice.forcedUser = forcedUser;
    }

    public static class HostnameAdvice {
        public static String forcedHost;
        @Advice.OnMethodExit
        static void exit(@Advice.Return(readOnly = false) String returned) {
            returned = forcedHost;
        }
    }

    public static class UserNameAdvice {
        public static String forcedUser;
        @Advice.OnMethodExit
        static void exit(@Advice.Return(readOnly = false) String returned) {
            returned = forcedUser;
        }
    }
}
"""
    }

    // 3a. Task to generate agent source
    task generateAgentSourceTask {
        doLast { generateAgentSource() }
    }

    // 3b. Compile agent
    task compileAgent(type: JavaCompile, dependsOn: generateAgentSourceTask) {
        source = fileTree(agentSrcDir)
        classpath = sourceSets.main.runtimeClasspath
        destinationDir = file("$buildDir/agent-classes")
    }

    // 3c. Build agent JAR
    task buildAgent(type: Jar, dependsOn: compileAgent) {
        archiveBaseName = 'force-hostname-agent'
        from compileAgent.destinationDir
        manifest {
            attributes(
                'Premain-Class': 'agent.ForceHostnameAgent',
                'Can-Redefine-Classes': 'true'
            )
        }
    }
}

// Call the subroutine to define agent tasks
configureAgentTasks()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)