File: JMXAgentInterfaceBinding.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (306 lines) | stat: -rw-r--r-- 11,563 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*
 * Copyright (c) 2015, Red Hat Inc
 * 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.
 */

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.rmi.RMIConnectorServer;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.rmi.ssl.SslRMIClientSocketFactory;

/**
 * Tests client connections to the JDK's built-in JMX agent server on the given
 * ports/interface combinations.
 *
 * @see JMXInterfaceBindingTest
 *
 * @author Severin Gehwolf <sgehwolf@redhat.com>
 *
 * Usage:
 *
 * SSL:
 *        java -Dcom.sun.management.jmxremote.ssl.need.client.auth=true \
 *             -Dcom.sun.management.jmxremote.host=127.0.0.1 \
 *             -Dcom.sun.management.jmxremote.port=9111 \
 *             -Dcom.sun.management.jmxremote.rmi.port=9112 \
 *             -Dcom.sun.management.jmxremote.authenticate=false \
 *             -Dcom.sun.management.jmxremote.ssl=true \
 *             -Dcom.sun.management.jmxremote.registry.ssl=true
 *             -Djavax.net.ssl.keyStore=... \
 *             -Djavax.net.ssl.keyStorePassword=... \
 *             JMXAgentInterfaceBinding 127.0.0.1 9111 9112 true
 *
 * Non-SSL:
 *        java -Dcom.sun.management.jmxremote.host=127.0.0.1 \
 *             -Dcom.sun.management.jmxremote.port=9111 \
 *             -Dcom.sun.management.jmxremote.rmi.port=9112 \
 *             -Dcom.sun.management.jmxremote.authenticate=false \
 *             -Dcom.sun.management.jmxremote.ssl=false \
 *             JMXAgentInterfaceBinding 127.0.0.1 9111 9112 false
 *
 */
public class JMXAgentInterfaceBinding {

    private final MainThread mainThread;

    public JMXAgentInterfaceBinding(InetAddress bindAddress,
                                   int jmxPort,
                                   int rmiPort,
                                   boolean useSSL) {
        this.mainThread = new MainThread(bindAddress, jmxPort, rmiPort, useSSL);
    }

    public void startEndpoint() {
        mainThread.start();
        try {
            mainThread.join();
        } catch (InterruptedException e) {
            throw new RuntimeException("Test failed", e);
        }
        if (mainThread.isFailed()) {
            mainThread.rethrowException();
        }
    }

    public static void main(String[] args) {
        if (args.length != 4) {
            throw new RuntimeException(
                    "Test failed. usage: java JMXInterfaceBindingTest <BIND_ADDRESS> <JMX_PORT> <RMI_PORT> {true|false}");
        }
        int jmxPort = parsePortFromString(args[1]);
        int rmiPort = parsePortFromString(args[2]);
        boolean useSSL = Boolean.parseBoolean(args[3]);
        String strBindAddr = args[0];
        System.out.println(
                "DEBUG: Running test for triplet (hostname,jmxPort,rmiPort) = ("
                        + strBindAddr + "," + jmxPort + "," + rmiPort + "), useSSL = " + useSSL);
        InetAddress bindAddress;
        try {
            bindAddress = InetAddress.getByName(args[0]);
        } catch (UnknownHostException e) {
            throw new RuntimeException("Test failed. Unknown ip: " + args[0]);
        }
        JMXAgentInterfaceBinding test = new JMXAgentInterfaceBinding(bindAddress,
                jmxPort, rmiPort, useSSL);
        test.startEndpoint(); // Expect for main test to terminate process
    }

    private static int parsePortFromString(String port) {
        try {
            return Integer.parseInt(port);
        } catch (NumberFormatException e) {
            throw new RuntimeException(
                    "Invalid port specified. Not an integer! Value was: "
                            + port);
        }
    }

    private static class JMXConnectorThread extends Thread {

        private final String addr;
        private final int jmxPort;
        private final int rmiPort;
        private final boolean useSSL;
        private final CountDownLatch latch;
        private boolean failed;
        private boolean jmxConnectWorked;
        private boolean rmiConnectWorked;

        private JMXConnectorThread(String addr,
                                   int jmxPort,
                                   int rmiPort,
                                   boolean useSSL,
                                   CountDownLatch latch) {
            this.addr = addr;
            this.jmxPort = jmxPort;
            this.rmiPort = rmiPort;
            this.latch = latch;
            this.useSSL = useSSL;
        }

        @Override
        public void run() {
            try {
                connect();
            } catch (IOException e) {
                failed = true;
            }
        }

        private void connect() throws IOException {
            System.out.println(
                    "JMXConnectorThread: Attempting JMX connection on: "
                            + addr + " on port " + jmxPort);
            JMXServiceURL url;
            try {
                url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"
                        + addr + ":" + jmxPort + "/jmxrmi");
            } catch (MalformedURLException e) {
                throw new RuntimeException("Test failed.", e);
            }
            Map<String, Object> env = new HashMap<>();
            if (useSSL) {
                SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
                env.put("com.sun.jndi.rmi.factory.socket", csf);
                env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
            }
            // connect and immediately close
            JMXConnector c = JMXConnectorFactory.connect(url, env);
            c.close();
            System.out.println("JMXConnectorThread: connection to JMX worked");
            jmxConnectWorked = true;
            checkRmiSocket();
            latch.countDown(); // signal we are done.
        }

        private void checkRmiSocket() throws IOException {
            Socket rmiConnection;
            if (useSSL) {
                rmiConnection = SSLSocketFactory.getDefault().createSocket();
            } else {
                rmiConnection = new Socket();
            }
            SocketAddress target = new InetSocketAddress(addr, rmiPort);
            rmiConnection.connect(target);
            if (useSSL) {
                ((SSLSocket)rmiConnection).startHandshake();
            }
            System.out.println(
                    "JMXConnectorThread: connection to rmi socket worked host/port = "
                            + addr + "/" + rmiPort);
            rmiConnectWorked = true;
            // Closing the channel without sending any data will cause an
            // java.io.EOFException on the server endpoint. We don't care about this
            // though, since we only want to test if we can connect.
            rmiConnection.close();
        }

        public boolean isFailed() {
            return failed;
        }

        public boolean jmxConnectionWorked() {
            return jmxConnectWorked;
        }

        public boolean rmiConnectionWorked() {
            return rmiConnectWorked;
        }
    }

    private static class MainThread extends Thread {

        private static final int WAIT_FOR_JMX_AGENT_TIMEOUT_MS = 500;
        private final String addr;
        private final int jmxPort;
        private final int rmiPort;
        private final boolean useSSL;
        private boolean terminated = false;
        private boolean jmxAgentStarted = false;
        private Exception excptn;

        private MainThread(InetAddress bindAddress, int jmxPort, int rmiPort, boolean useSSL) {
            this.addr = wrapAddress(bindAddress.getHostAddress());
            this.jmxPort = jmxPort;
            this.rmiPort = rmiPort;
            this.useSSL = useSSL;
        }

        @Override
        public void run() {
            try {
                waitUntilReadyForConnections();
                // Do nothing, but wait for termination.
                try {
                    while (!terminated) {
                        Thread.sleep(100);
                    }
                } catch (InterruptedException e) { // ignore
                }
                System.out.println("MainThread: Thread stopped.");
            } catch (Exception e) {
                this.excptn = e;
            }
        }

        private void waitUntilReadyForConnections() {
            CountDownLatch latch = new CountDownLatch(1);
            JMXConnectorThread connectionTester = new JMXConnectorThread(
                    addr, jmxPort, rmiPort, useSSL, latch);
            connectionTester.start();
            boolean expired = false;
            try {
                expired = !latch.await(WAIT_FOR_JMX_AGENT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
                System.out.println(
                        "MainThread: Finished waiting for JMX agent to become available: expired == "
                                + expired);
                jmxAgentStarted = !expired;
            } catch (InterruptedException e) {
                throw new RuntimeException("Test failed", e);
            }
            if (!jmxAgentStarted) {
                throw new RuntimeException(
                        "Test failed. JMX server agents not becoming available.");
            }
            if (connectionTester.isFailed()
                    || !connectionTester.jmxConnectionWorked()
                    || !connectionTester.rmiConnectionWorked()) {
                throw new RuntimeException(
                        "Test failed. JMX agent does not seem ready. See log output for details.");
            }
            // The main test expects this exact message being printed
            System.out.println("MainThread: Ready for connections");
        }

        private boolean isFailed() {
            return excptn != null;
        }

        private void rethrowException() throws RuntimeException {
            throw new RuntimeException(excptn);
        }
    }

    /**
     * Will wrap IPv6 address in '[]'
     */
    static String wrapAddress(String address) {
        if (address.contains(":")) {
            return "[" + address + "]";
        }
        return address;
    }
}