/*
 * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */


/*
 * @test
 * @summary Test JFR network related events inside a container; make sure
 *          the reported host ip and host name are correctly reported within
 *          the container.
 * @requires docker.support
 * @library /test/lib
 * @modules java.base/jdk.internal.misc
 *          java.management
 *          jdk.jartool/sun.tools.jar
 * @build EventGeneratorLoop
 * @run driver TestJFRWithJMX
 */

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnector;

import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingFile;
import jdk.management.jfr.FlightRecorderMXBean;

import jdk.test.lib.containers.docker.Common;
import jdk.test.lib.containers.docker.DockerRunOptions;
import jdk.test.lib.containers.docker.DockerTestUtils;
import jdk.test.lib.Asserts;
import jdk.test.lib.Utils;
import jdk.test.lib.process.ProcessTools;

import jtreg.SkippedException;


public class TestJFRWithJMX {
    static final String imageName = Common.imageName("jfr-jmx");
    static final int PORT = 9010;

    static AtomicReference<String> ipAddr = new AtomicReference();

    public static void main(String[] args) throws Exception {
        if (!DockerTestUtils.canTestDocker()) {
            throw new SkippedException("Docker is not supported on this host");
        }

        DockerTestUtils.buildJdkDockerImage(imageName, "Dockerfile-BasicTest", "jdk-docker");

        try {
            // testWithoutContainer();
            testWithContainer();
        } finally {
            DockerTestUtils.removeDockerImage(imageName);
        }
    }


    static ProcessBuilder buildJavaProcess(int howLongToRun) throws Exception {
        ProcessBuilder pb =
            ProcessTools.createJavaProcessBuilder("-Dcom.sun.management.jmxremote",
                                                  "-Dcom.sun.management.jmxremote.port=" + PORT,
                                                  "-Dcom.sun.management.jmxremote.local.only=false",
                                                  "-Dcom.sun.management.jmxremote.authenticate=false",
                                                  "-Dcom.sun.management.jmxremote.ssl=false",
                                                  "EventGeneratorLoop", "" + howLongToRun);
        return pb;
    }

    static ProcessBuilder buildDockerJavaProcess(int howLongToRun) throws Exception {
        DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java", "EventGeneratorLoop")
            .addDockerOpts("--volume", Utils.TEST_CLASSES + ":/test-classes/")
            .addDockerOpts("--hostname", "jmx-jfr-test")
            .addDockerOpts("-p", "" + PORT + ":" + PORT)
            .addJavaOpts("-cp", "/test-classes/")
            .addJavaOpts("-Dcom.sun.management.jmxremote", "-Dcom.sun.management.jmxremote.port=" + PORT)
            .addJavaOpts("-Dcom.sun.management.jmxremote.local.only=false")
            .addJavaOpts("-Dcom.sun.management.jmxremote.authenticate=false")
            .addJavaOpts("-Dcom.sun.management.jmxremote.ssl=false")
            .addClassOptions("" + howLongToRun);

        List<String> cmd = DockerTestUtils.buildJavaCommand(opts);
        ProcessBuilder pb = new ProcessBuilder(cmd);

        return pb;
    }


    static void testWithoutContainer() throws Exception {
        ProcessBuilder pb = buildJavaProcess(10);
        Process p = pb.start();

        JMXConnector connector = waitForJmxConnection("localhost", PORT);
        FlightRecorderMXBean bean = getJfrBean(connector);

        long recordingId = record(bean);
        bean.closeRecording(recordingId);

        p.waitFor();
    }

    static void testWithContainer() throws Exception {
        ProcessBuilder pb = buildDockerJavaProcess(10);
        Process p = ProcessTools.startProcess("monitored-container", pb, outputConsumer);

        // wait for the target process to communicate the IP address
        while(ipAddr.get() == null) {
            Thread.sleep(1000);
        }

        File transferredRecording;
        try ( JMXConnector connector = waitForJmxConnection(ipAddr.get(), PORT) ) {
            FlightRecorderMXBean bean = getJfrBean(connector);

            long recordingId = record(bean);
            long streamId = bean.openStream(recordingId, null);
            transferredRecording = transferRecording(bean, streamId);

            bean.closeStream(streamId);
            bean.closeRecording(recordingId);
        }

        System.out.println("Recording was transferred to: " + transferredRecording.getPath());
        verifyRecording(transferredRecording);

        p.waitFor();
    }

    static void verifyRecording(File f) throws Exception {
        boolean foundSimpleEvent = false;

        try (RecordingFile recordingFile = new RecordingFile(f.toPath())) {
            while (recordingFile.hasMoreEvents()) {
                RecordedEvent event = recordingFile.readEvent();
                if(event.getEventType().getName().equals("EventGeneratorLoop$SimpleEvent")) {
                    foundSimpleEvent = true;
                    break;
                }
            }

            Asserts.assertTrue(foundSimpleEvent, "Could not find SimpleEvent in the recording");
        }
    }

    static Consumer<String> outputConsumer = s -> {
        if (ipAddr.get() != null) {
            return;
        }

        if (s.contains(EventGeneratorLoop.HOST_ADDR_TAG)) {
            String ip = s.replace(EventGeneratorLoop.HOST_ADDR_TAG, "");
            System.out.println("Observee ip: " + ip);
            ipAddr.set(ip);
        }
    };

    // try connecting in a loop, it may take some time for target process to be ready for JMX connection
    static JMXConnector waitForJmxConnection(String host, int port) throws Exception {
        JMXConnector connector = null;
        while(connector == null) {
            connector = establishJmxConnection(host, port);
            Thread.sleep(5000);
        }

        return connector;
    }

    static JMXConnector establishJmxConnection(String host, int port) throws Exception {
        String urlPath = "/jndi/rmi://" + host + ":" + port + "/jmxrmi";
        JMXServiceURL url = new JMXServiceURL("rmi", "", 0, urlPath);
        return JMXConnectorFactory.connect(url);
    }

    static FlightRecorderMXBean getJfrBean(JMXConnector connector) throws Exception {
        MBeanServerConnection connection = connector.getMBeanServerConnection();
        return ManagementFactory.newPlatformMXBeanProxy(connection,
                                                        "jdk.management.jfr:type=FlightRecorder",
                                                        FlightRecorderMXBean.class);
    }

    static long record(FlightRecorderMXBean bean) throws Exception {
        long id = bean.newRecording();
        bean.startRecording(id);
        Thread.sleep(2000);

        bean.stopRecording(id);

        String fn = "/tmp/recording-" + ProcessHandle.current().pid() + ".jfr";
        bean.copyTo(id, fn);
        System.out.println("Wrote recording to " + fn);
        return id;
    }

    static File transferRecording(FlightRecorderMXBean bean, long streamId) throws Exception {
        File f = Utils.createTempFile("recording-" + streamId + "-", ".jfr").toFile();
        try (FileOutputStream fos = new FileOutputStream(f);
             BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            while (true) {
                byte[] data = bean.readStream(streamId);
                if (data == null) {
                    bos.flush();
                    return f;
                }
                bos.write(data);
            }
        }
    }

}

