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 Charset PORT_FILE_ENCODING
= Charset
.forName("UTF-8");
41 private static final int PROTOCOL_MAJOR_VERSION
= 2;
42 private static final int PROTOCOL_MINOR_VERSION
= 0;
44 /** Command header from the session daemon. */
45 private final CountDownLatch registrationLatch
= new CountDownLatch(1);
47 private Socket sessiondSock
;
48 private volatile boolean quit
= false;
50 private DataInputStream inFromSessiond
;
51 private DataOutputStream outToSessiond
;
53 private final ILttngTcpClientListener logAgent
;
54 private final int domainValue
;
55 private final boolean isRoot
;
61 * The listener this client will operate on, typically an LTTng
64 * The integer to send to the session daemon representing the
65 * tracing domain to handle.
67 * True if this client should connect to the root session daemon,
68 * false if it should connect to the user one.
70 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent
, int domainValue
, boolean isRoot
) {
71 this.logAgent
= logAgent
;
72 this.domainValue
= domainValue
;
77 * Wait until this client has successfully established a connection to its
78 * target session daemon.
81 * A timeout in seconds after which this method will return
83 * @return True if the the client actually established the connection, false
84 * if we returned because the timeout has elapsed or the thread was
87 public boolean waitForConnection(int seconds
) {
89 return registrationLatch
.await(seconds
, TimeUnit
.SECONDS
);
90 } catch (InterruptedException e
) {
105 * Connect to the session daemon before anything else.
107 log("Connecting to sessiond");
111 * Register to the session daemon as the Java component of the
114 log("Registering to sessiond");
115 registerToSessiond();
118 * Block on socket receive and wait for command from the
119 * session daemon. This will return if and only if there is a
120 * fatal error or the socket closes.
122 log("Waiting on sessiond commands...");
124 } catch (UnknownHostException uhe
) {
125 uhe
.printStackTrace();
127 * Terminate agent thread.
130 } catch (IOException ioe
) {
132 * I/O exception may have been triggered by a session daemon
133 * closing the socket. Close our own socket and
134 * retry connecting after a delay.
137 if (this.sessiondSock
!= null) {
138 this.sessiondSock
.close();
141 } catch (InterruptedException e
) {
143 * Retry immediately if sleep is interrupted.
145 } catch (IOException closeioe
) {
146 closeioe
.printStackTrace();
148 * Terminate agent thread.
157 * Dispose this client and close any socket connection it may hold.
159 public void close() {
160 log("Closing client");
164 if (this.sessiondSock
!= null) {
165 this.sessiondSock
.close();
167 } catch (IOException e
) {
172 private void connectToSessiond() throws IOException
{
176 * The environment variable LTTNG_UST_APP_PATH disables
177 * connection to per-user and root session daemons.
179 String lttngUstAppPath
= getUstAppPath();
181 if (lttngUstAppPath
!= null) {
182 portToUse
= getPortFromFile(lttngUstAppPath
+ USER_PORT_FILE
);
184 int rootPort
= getPortFromFile(ROOT_PORT_FILE
);
185 int userPort
= getPortFromFile(getHomePath() + USER_PORT_FILE
);
188 * Check for the edge case of both files existing but pointing to the
189 * same port. In this case, let the root client handle it.
191 if ((rootPort
!= 0) && (rootPort
== userPort
) && (!isRoot
)) {
192 log("User and root config files both point to port " + rootPort
+
193 ". Letting the root client handle it.");
194 throw new IOException();
197 portToUse
= (isRoot ? rootPort
: userPort
);
200 if (portToUse
== 0) {
201 /* No session daemon available. Stop and retry later. */
202 throw new IOException();
205 this.sessiondSock
= new Socket(SESSION_HOST
, portToUse
);
206 this.inFromSessiond
= new DataInputStream(sessiondSock
.getInputStream());
207 this.outToSessiond
= new DataOutputStream(sessiondSock
.getOutputStream());
210 private static String
getUstAppPath() {
211 return System
.getenv("LTTNG_UST_APP_PATH");
214 private static String
getHomePath() {
216 * The environment variable LTTNG_HOME overrides HOME if
219 String lttngHomePath
= System
.getenv("LTTNG_HOME");
220 if (lttngHomePath
!= null) {
221 return lttngHomePath
;
223 return System
.getProperty("user.home");
227 * Read port number from file created by the session daemon.
229 * @return port value if found else 0.
231 private static int getPortFromFile(String path
) throws IOException
{
232 BufferedReader br
= null;
235 br
= new BufferedReader(new InputStreamReader(new FileInputStream(path
), PORT_FILE_ENCODING
));
236 String line
= br
.readLine();
238 /* File exists but is empty. */
242 int port
= Integer
.parseInt(line
, 10);
243 if (port
< 0 || port
> 65535) {
244 /* Invalid value. Ignore. */
249 } catch (NumberFormatException e
) {
250 /* File contained something that was not a number. */
252 } catch (FileNotFoundException e
) {
253 /* No port available. */
262 private void registerToSessiond() throws IOException
{
263 byte data
[] = new byte[16];
264 ByteBuffer buf
= ByteBuffer
.wrap(data
);
265 String pid
= ManagementFactory
.getRuntimeMXBean().getName().split("@")[0];
267 buf
.putInt(domainValue
);
268 buf
.putInt(Integer
.parseInt(pid
));
269 buf
.putInt(PROTOCOL_MAJOR_VERSION
);
270 buf
.putInt(PROTOCOL_MINOR_VERSION
);
271 this.outToSessiond
.write(data
, 0, data
.length
);
272 this.outToSessiond
.flush();
276 * Handle session command from the session daemon.
278 private void handleSessiondCmd() throws IOException
{
279 /* Data read from the socket */
280 byte inputData
[] = null;
281 /* Reply data written to the socket, sent to the sessiond */
282 LttngAgentResponse response
;
285 /* Get header from session daemon. */
286 SessiondCommandHeader cmdHeader
= recvHeader();
288 if (cmdHeader
.getDataSize() > 0) {
289 inputData
= recvPayload(cmdHeader
);
292 switch (cmdHeader
.getCommandType()) {
296 * Countdown the registration latch, meaning registration is
297 * done and we can proceed to continue tracing.
299 registrationLatch
.countDown();
301 * We don't send any reply to the registration done command.
302 * This just marks the end of the initial session setup.
304 log("Registration done");
309 SessiondCommand listLoggerCmd
= new SessiondListLoggersCommand();
310 response
= listLoggerCmd
.execute(logAgent
);
311 log("Received list loggers command");
314 case CMD_EVENT_ENABLE
:
316 if (inputData
== null) {
317 /* Invalid command */
318 response
= LttngAgentResponse
.FAILURE_RESPONSE
;
321 SessiondCommand enableEventCmd
= new SessiondEnableEventCommand(inputData
);
322 response
= enableEventCmd
.execute(logAgent
);
323 log("Received enable event command: " + enableEventCmd
.toString());
326 case CMD_EVENT_DISABLE
:
328 if (inputData
== null) {
329 /* Invalid command */
330 response
= LttngAgentResponse
.FAILURE_RESPONSE
;
333 SessiondCommand disableEventCmd
= new SessiondDisableEventCommand(inputData
);
334 response
= disableEventCmd
.execute(logAgent
);
335 log("Received disable event command: " + disableEventCmd
.toString());
338 case CMD_APP_CTX_ENABLE
:
340 if (inputData
== null) {
341 /* This commands expects a payload, invalid command */
342 response
= LttngAgentResponse
.FAILURE_RESPONSE
;
345 SessiondCommand enableAppCtxCmd
= new SessiondEnableAppContextCommand(inputData
);
346 response
= enableAppCtxCmd
.execute(logAgent
);
347 log("Received enable app-context command");
350 case CMD_APP_CTX_DISABLE
:
352 if (inputData
== null) {
353 /* This commands expects a payload, invalid command */
354 response
= LttngAgentResponse
.FAILURE_RESPONSE
;
357 SessiondCommand disableAppCtxCmd
= new SessiondDisableAppContextCommand(inputData
);
358 response
= disableAppCtxCmd
.execute(logAgent
);
359 log("Received disable app-context command");
364 /* Unknown command, send empty reply */
366 log("Received unknown command, ignoring");
371 /* Send response to the session daemon. */
373 if (response
== null) {
374 responseData
= new byte[4];
375 ByteBuffer buf
= ByteBuffer
.wrap(responseData
);
376 buf
.order(ByteOrder
.BIG_ENDIAN
);
378 log("Sending response: " + response
.toString());
379 responseData
= response
.getBytes();
381 this.outToSessiond
.write(responseData
, 0, responseData
.length
);
382 this.outToSessiond
.flush();
387 * Receive header data from the session daemon using the LTTng command
388 * static buffer of the right size.
390 private SessiondCommandHeader
recvHeader() throws IOException
{
391 byte data
[] = new byte[SessiondCommandHeader
.HEADER_SIZE
];
392 int bytesLeft
= data
.length
;
395 while (bytesLeft
> 0) {
396 int bytesRead
= this.inFromSessiond
.read(data
, bytesOffset
, bytesLeft
);
399 throw new IOException();
401 bytesLeft
-= bytesRead
;
402 bytesOffset
+= bytesRead
;
404 return new SessiondCommandHeader(data
);
408 * Receive payload from the session daemon. This MUST be done after a
409 * recvHeader() so the header value of a command are known.
411 * The caller SHOULD use isPayload() before which returns true if a payload
412 * is expected after the header.
414 private byte[] recvPayload(SessiondCommandHeader headerCmd
) throws IOException
{
415 byte payload
[] = new byte[(int) headerCmd
.getDataSize()];
416 int bytesLeft
= payload
.length
;
419 /* Failsafe check so we don't waste our time reading 0 bytes. */
420 if (bytesLeft
== 0) {
424 while (bytesLeft
> 0) {
425 int bytesRead
= inFromSessiond
.read(payload
, bytesOffset
, bytesLeft
);
428 throw new IOException();
430 bytesLeft
-= bytesRead
;
431 bytesOffset
+= bytesRead
;
437 * Wrapper for this class's logging, adds the connection's characteristics
438 * to help differentiate between multiple TCP clients.
440 private void log(String message
) {
441 LttngUstAgentLogger
.log(getClass(),
442 "(root=" + isRoot
+ ", domain=" + domainValue
+ ") " + message
);