2 * SPDX-License-Identifier: LGPL-2.1-only
4 * Copyright (C) 2015-2016 EfficiOS Inc.
5 * Copyright (C) 2015-2016 Alexandre Montplaisir <alexmonthy@efficios.com>
6 * Copyright (C) 2013 David Goulet <dgoulet@efficios.com>
9 package org.lttng.ust.agent.client;
11 import java.io.BufferedReader;
12 import java.io.DataInputStream;
13 import java.io.DataOutputStream;
14 import java.io.FileInputStream;
15 import java.io.FileNotFoundException;
16 import java.io.IOException;
17 import java.io.InputStreamReader;
18 import java.lang.management.ManagementFactory;
19 import java.net.Socket;
20 import java.net.UnknownHostException;
21 import java.nio.ByteBuffer;
22 import java.nio.ByteOrder;
23 import java.nio.charset.Charset;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.TimeUnit;
27 import org.lttng.ust.agent.utils.LttngUstAgentLogger;
30 * Client for agents to connect to a local session daemon, using a TCP socket.
32 * @author David Goulet
34 public class LttngTcpSessiondClient implements Runnable {
36 private static final String SESSION_HOST = "127.0.0.1";
37 private static final String ROOT_PORT_FILE = "/var/run/lttng/agent.port";
38 private static final String USER_PORT_FILE = "/.lttng/agent.port";
39 private static final String APP_PATH_PORT_FILE = "/agent.port";
40 private static final Charset PORT_FILE_ENCODING = Charset.forName("UTF-8");
42 private static final int PROTOCOL_MAJOR_VERSION = 2;
43 private static final int PROTOCOL_MINOR_VERSION = 0;
45 /** Command header from the session daemon. */
46 private final CountDownLatch registrationLatch = new CountDownLatch(1);
48 private Socket sessiondSock;
49 private volatile boolean quit = false;
51 private DataInputStream inFromSessiond;
52 private DataOutputStream outToSessiond;
54 private final ILttngTcpClientListener logAgent;
55 private final int domainValue;
56 private final boolean isRoot;
62 * The listener this client will operate on, typically an LTTng
65 * The integer to send to the session daemon representing the
66 * tracing domain to handle.
68 * True if this client should connect to the root session daemon,
69 * false if it should connect to the user one.
71 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent, int domainValue, boolean isRoot) {
72 this.logAgent = logAgent;
73 this.domainValue = domainValue;
78 * Wait until this client has successfully established a connection to its
79 * target session daemon.
82 * A timeout in seconds after which this method will return
84 * @return True if the the client actually established the connection, false
85 * if we returned because the timeout has elapsed or the thread was
88 public boolean waitForConnection(int seconds) {
90 return registrationLatch.await(seconds, TimeUnit.SECONDS);
91 } catch (InterruptedException e) {
106 * Connect to the session daemon before anything else.
108 log("Connecting to sessiond");
112 * Register to the session daemon as the Java component of the
115 log("Registering to sessiond");
116 registerToSessiond();
119 * Block on socket receive and wait for command from the
120 * session daemon. This will return if and only if there is a
121 * fatal error or the socket closes.
123 log("Waiting on sessiond commands...");
125 } catch (UnknownHostException uhe) {
126 uhe.printStackTrace();
128 * Terminate agent thread.
131 } catch (IOException ioe) {
133 * I/O exception may have been triggered by a session daemon
134 * closing the socket. Close our own socket and
135 * retry connecting after a delay.
138 if (this.sessiondSock != null) {
139 this.sessiondSock.close();
142 } catch (InterruptedException e) {
144 * Retry immediately if sleep is interrupted.
146 } catch (IOException closeioe) {
147 closeioe.printStackTrace();
149 * Terminate agent thread.
158 * Dispose this client and close any socket connection it may hold.
160 public void close() {
161 log("Closing client");
165 if (this.sessiondSock != null) {
166 this.sessiondSock.close();
168 } catch (IOException e) {
173 private void connectToSessiond() throws IOException {
177 * The environment variable LTTNG_UST_APP_PATH disables
178 * connection to per-user and root session daemons.
180 String lttngUstAppPath = getUstAppPath();
182 if (lttngUstAppPath != null) {
183 portToUse = getPortFromFile(lttngUstAppPath + APP_PATH_PORT_FILE);
185 int rootPort = getPortFromFile(ROOT_PORT_FILE);
186 int userPort = getPortFromFile(getHomePath() + USER_PORT_FILE);
189 * Check for the edge case of both files existing but pointing to the
190 * same port. In this case, let the root client handle it.
192 if ((rootPort != 0) && (rootPort == userPort) && (!isRoot)) {
193 log("User and root config files both point to port " + rootPort +
194 ". Letting the root client handle it.");
195 throw new IOException();
198 portToUse = (isRoot ? rootPort : userPort);
201 if (portToUse == 0) {
202 /* No session daemon available. Stop and retry later. */
203 throw new IOException();
206 this.sessiondSock = new Socket(SESSION_HOST, portToUse);
207 this.inFromSessiond = new DataInputStream(sessiondSock.getInputStream());
208 this.outToSessiond = new DataOutputStream(sessiondSock.getOutputStream());
211 private static String getUstAppPath() {
212 return System.getenv("LTTNG_UST_APP_PATH");
215 private static String getHomePath() {
217 * The environment variable LTTNG_HOME overrides HOME if
220 String lttngHomePath = System.getenv("LTTNG_HOME");
221 if (lttngHomePath != null) {
222 return lttngHomePath;
224 return System.getProperty("user.home");
228 * Read port number from file created by the session daemon.
230 * @return port value if found else 0.
232 private static int getPortFromFile(String path) throws IOException {
233 BufferedReader br = null;
236 br = new BufferedReader(new InputStreamReader(new FileInputStream(path), PORT_FILE_ENCODING));
237 String line = br.readLine();
239 /* File exists but is empty. */
243 int port = Integer.parseInt(line, 10);
244 if (port < 0 || port > 65535) {
245 /* Invalid value. Ignore. */
250 } catch (NumberFormatException e) {
251 /* File contained something that was not a number. */
253 } catch (FileNotFoundException e) {
254 /* No port available. */
263 private void registerToSessiond() throws IOException {
264 byte data[] = new byte[16];
265 ByteBuffer buf = ByteBuffer.wrap(data);
266 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
268 buf.putInt(domainValue);
269 buf.putInt(Integer.parseInt(pid));
270 buf.putInt(PROTOCOL_MAJOR_VERSION);
271 buf.putInt(PROTOCOL_MINOR_VERSION);
272 this.outToSessiond.write(data, 0, data.length);
273 this.outToSessiond.flush();
277 * Handle session command from the session daemon.
279 private void handleSessiondCmd() throws IOException {
280 /* Data read from the socket */
281 byte inputData[] = null;
282 /* Reply data written to the socket, sent to the sessiond */
283 LttngAgentResponse response;
286 /* Get header from session daemon. */
287 SessiondCommandHeader cmdHeader = recvHeader();
289 if (cmdHeader.getDataSize() > 0) {
290 inputData = recvPayload(cmdHeader);
293 switch (cmdHeader.getCommandType()) {
297 * Countdown the registration latch, meaning registration is
298 * done and we can proceed to continue tracing.
300 registrationLatch.countDown();
302 * We don't send any reply to the registration done command.
303 * This just marks the end of the initial session setup.
305 log("Registration done");
310 SessiondCommand listLoggerCmd = new SessiondListLoggersCommand();
311 response = listLoggerCmd.execute(logAgent);
312 log("Received list loggers command");
315 case CMD_EVENT_ENABLE:
317 if (inputData == null) {
318 /* Invalid command */
319 response = LttngAgentResponse.FAILURE_RESPONSE;
322 SessiondCommand enableEventCmd = new SessiondEnableEventCommand(inputData);
323 response = enableEventCmd.execute(logAgent);
324 log("Received enable event command: " + enableEventCmd.toString());
327 case CMD_EVENT_DISABLE:
329 if (inputData == null) {
330 /* Invalid command */
331 response = LttngAgentResponse.FAILURE_RESPONSE;
334 SessiondCommand disableEventCmd = new SessiondDisableEventCommand(inputData);
335 response = disableEventCmd.execute(logAgent);
336 log("Received disable event command: " + disableEventCmd.toString());
339 case CMD_APP_CTX_ENABLE:
341 if (inputData == null) {
342 /* This commands expects a payload, invalid command */
343 response = LttngAgentResponse.FAILURE_RESPONSE;
346 SessiondCommand enableAppCtxCmd = new SessiondEnableAppContextCommand(inputData);
347 response = enableAppCtxCmd.execute(logAgent);
348 log("Received enable app-context command");
351 case CMD_APP_CTX_DISABLE:
353 if (inputData == null) {
354 /* This commands expects a payload, invalid command */
355 response = LttngAgentResponse.FAILURE_RESPONSE;
358 SessiondCommand disableAppCtxCmd = new SessiondDisableAppContextCommand(inputData);
359 response = disableAppCtxCmd.execute(logAgent);
360 log("Received disable app-context command");
365 /* Unknown command, send empty reply */
367 log("Received unknown command, ignoring");
372 /* Send response to the session daemon. */
374 if (response == null) {
375 responseData = new byte[4];
376 ByteBuffer buf = ByteBuffer.wrap(responseData);
377 buf.order(ByteOrder.BIG_ENDIAN);
379 log("Sending response: " + response.toString());
380 responseData = response.getBytes();
382 this.outToSessiond.write(responseData, 0, responseData.length);
383 this.outToSessiond.flush();
388 * Receive header data from the session daemon using the LTTng command
389 * static buffer of the right size.
391 private SessiondCommandHeader recvHeader() throws IOException {
392 byte data[] = new byte[SessiondCommandHeader.HEADER_SIZE];
393 int bytesLeft = data.length;
396 while (bytesLeft > 0) {
397 int bytesRead = this.inFromSessiond.read(data, bytesOffset, bytesLeft);
400 throw new IOException();
402 bytesLeft -= bytesRead;
403 bytesOffset += bytesRead;
405 return new SessiondCommandHeader(data);
409 * Receive payload from the session daemon. This MUST be done after a
410 * recvHeader() so the header value of a command are known.
412 * The caller SHOULD use isPayload() before which returns true if a payload
413 * is expected after the header.
415 private byte[] recvPayload(SessiondCommandHeader headerCmd) throws IOException {
416 byte payload[] = new byte[(int) headerCmd.getDataSize()];
417 int bytesLeft = payload.length;
420 /* Failsafe check so we don't waste our time reading 0 bytes. */
421 if (bytesLeft == 0) {
425 while (bytesLeft > 0) {
426 int bytesRead = inFromSessiond.read(payload, bytesOffset, bytesLeft);
429 throw new IOException();
431 bytesLeft -= bytesRead;
432 bytesOffset += bytesRead;
438 * Wrapper for this class's logging, adds the connection's characteristics
439 * to help differentiate between multiple TCP clients.
441 private void log(String message) {
442 LttngUstAgentLogger.log(getClass(),
443 "(root=" + isRoot + ", domain=" + domainValue + ") " + message);