2 * Copyright (C) 2015-2016 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
3 * Copyright (C) 2013 - David Goulet <dgoulet@efficios.com>
5 * This library is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License, version 2.1 only,
7 * as published by the Free Software Foundation.
9 * This library is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
14 * You should have received a copy of the GNU Lesser General Public License
15 * along with this library; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 package org
.lttng
.ust
.agent
.client
;
21 import java
.io
.BufferedReader
;
22 import java
.io
.DataInputStream
;
23 import java
.io
.DataOutputStream
;
24 import java
.io
.FileInputStream
;
25 import java
.io
.FileNotFoundException
;
26 import java
.io
.IOException
;
27 import java
.io
.InputStreamReader
;
28 import java
.lang
.management
.ManagementFactory
;
29 import java
.net
.Socket
;
30 import java
.net
.UnknownHostException
;
31 import java
.nio
.ByteBuffer
;
32 import java
.nio
.ByteOrder
;
33 import java
.nio
.charset
.Charset
;
34 import java
.util
.concurrent
.CountDownLatch
;
35 import java
.util
.concurrent
.TimeUnit
;
37 import org
.lttng
.ust
.agent
.utils
.LttngUstAgentLogger
;
40 * Client for agents to connect to a local session daemon, using a TCP socket.
42 * @author David Goulet
44 public class LttngTcpSessiondClient
implements Runnable
{
46 private static final String SESSION_HOST
= "127.0.0.1";
47 private static final String ROOT_PORT_FILE
= "/var/run/lttng/agent.port";
48 private static final String USER_PORT_FILE
= "/.lttng/agent.port";
49 private static final Charset PORT_FILE_ENCODING
= Charset
.forName("UTF-8");
51 private static final int PROTOCOL_MAJOR_VERSION
= 2;
52 private static final int PROTOCOL_MINOR_VERSION
= 0;
54 /** Command header from the session deamon. */
55 private final CountDownLatch registrationLatch
= new CountDownLatch(1);
57 private Socket sessiondSock
;
58 private volatile boolean quit
= false;
60 private DataInputStream inFromSessiond
;
61 private DataOutputStream outToSessiond
;
63 private final ILttngTcpClientListener logAgent
;
64 private final int domainValue
;
65 private final boolean isRoot
;
71 * The listener this client will operate on, typically an LTTng
74 * The integer to send to the session daemon representing the
75 * tracing domain to handle.
77 * True if this client should connect to the root session daemon,
78 * false if it should connect to the user one.
80 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent
, int domainValue
, boolean isRoot
) {
81 this.logAgent
= logAgent
;
82 this.domainValue
= domainValue
;
87 * Wait until this client has successfully established a connection to its
88 * target session daemon.
91 * A timeout in seconds after which this method will return
93 * @return True if the the client actually established the connection, false
94 * if we returned because the timeout has elapsed or the thread was
97 public boolean waitForConnection(int seconds
) {
99 return registrationLatch
.await(seconds
, TimeUnit
.SECONDS
);
100 } catch (InterruptedException e
) {
115 * Connect to the session daemon before anything else.
117 log("Connecting to sessiond");
121 * Register to the session daemon as the Java component of the
124 log("Registering to sessiond");
125 registerToSessiond();
128 * Block on socket receive and wait for command from the
129 * session daemon. This will return if and only if there is a
130 * fatal error or the socket closes.
132 log("Waiting on sessiond commands...");
134 } catch (UnknownHostException uhe
) {
135 uhe
.printStackTrace();
137 * Terminate agent thread.
140 } catch (IOException ioe
) {
142 * I/O exception may have been triggered by a session daemon
143 * closing the socket. Close our own socket and
144 * retry connecting after a delay.
147 if (this.sessiondSock
!= null) {
148 this.sessiondSock
.close();
151 } catch (InterruptedException e
) {
153 * Retry immediately if sleep is interrupted.
155 } catch (IOException closeioe
) {
156 closeioe
.printStackTrace();
158 * Terminate agent thread.
167 * Dispose this client and close any socket connection it may hold.
169 public void close() {
170 log("Closing client");
174 if (this.sessiondSock
!= null) {
175 this.sessiondSock
.close();
177 } catch (IOException e
) {
182 private void connectToSessiond() throws IOException
{
183 int rootPort
= getPortFromFile(ROOT_PORT_FILE
);
184 int userPort
= getPortFromFile(getHomePath() + USER_PORT_FILE
);
187 * Check for the edge case of both files existing but pointing to the
188 * same port. In this case, let the root client handle it.
190 if ((rootPort
!= 0) && (rootPort
== userPort
) && (!isRoot
)) {
191 log("User and root config files both point to port " + rootPort
+
192 ". Letting the root client handle it.");
193 throw new IOException();
196 int portToUse
= (isRoot ? rootPort
: userPort
);
198 if (portToUse
== 0) {
199 /* No session daemon available. Stop and retry later. */
200 throw new IOException();
203 this.sessiondSock
= new Socket(SESSION_HOST
, portToUse
);
204 this.inFromSessiond
= new DataInputStream(sessiondSock
.getInputStream());
205 this.outToSessiond
= new DataOutputStream(sessiondSock
.getOutputStream());
208 private static String
getHomePath() {
210 * The environment variable LTTNG_HOME overrides HOME if
213 String homePath
= System
.getenv("LTTNG_HOME");
215 if (homePath
== null) {
216 homePath
= System
.getProperty("user.home");
222 * Read port number from file created by the session daemon.
224 * @return port value if found else 0.
226 private static int getPortFromFile(String path
) throws IOException
{
227 BufferedReader br
= null;
230 br
= new BufferedReader(new InputStreamReader(new FileInputStream(path
), PORT_FILE_ENCODING
));
231 String line
= br
.readLine();
233 /* File exists but is empty. */
237 int port
= Integer
.parseInt(line
, 10);
238 if (port
< 0 || port
> 65535) {
239 /* Invalid value. Ignore. */
244 } catch (NumberFormatException e
) {
245 /* File contained something that was not a number. */
247 } catch (FileNotFoundException e
) {
248 /* No port available. */
257 private void registerToSessiond() throws IOException
{
258 byte data
[] = new byte[16];
259 ByteBuffer buf
= ByteBuffer
.wrap(data
);
260 String pid
= ManagementFactory
.getRuntimeMXBean().getName().split("@")[0];
262 buf
.putInt(domainValue
);
263 buf
.putInt(Integer
.parseInt(pid
));
264 buf
.putInt(PROTOCOL_MAJOR_VERSION
);
265 buf
.putInt(PROTOCOL_MINOR_VERSION
);
266 this.outToSessiond
.write(data
, 0, data
.length
);
267 this.outToSessiond
.flush();
271 * Handle session command from the session daemon.
273 private void handleSessiondCmd() throws IOException
{
274 /* Data read from the socket */
275 byte inputData
[] = null;
276 /* Reply data written to the socket, sent to the sessiond */
277 LttngAgentResponse response
;
280 /* Get header from session daemon. */
281 SessiondCommandHeader cmdHeader
= recvHeader();
283 if (cmdHeader
.getDataSize() > 0) {
284 inputData
= recvPayload(cmdHeader
);
287 switch (cmdHeader
.getCommandType()) {
291 * Countdown the registration latch, meaning registration is
292 * done and we can proceed to continue tracing.
294 registrationLatch
.countDown();
296 * We don't send any reply to the registration done command.
297 * This just marks the end of the initial session setup.
299 log("Registration done");
304 SessiondCommand listLoggerCmd
= new SessiondListLoggersCommand();
305 response
= listLoggerCmd
.execute(logAgent
);
306 log("Received list loggers command");
309 case CMD_EVENT_ENABLE
:
311 if (inputData
== null) {
312 /* Invalid command */
313 response
= LttngAgentResponse
.FAILURE_RESPONSE
;
316 SessiondCommand enableEventCmd
= new SessiondEnableEventCommand(inputData
);
317 response
= enableEventCmd
.execute(logAgent
);
318 log("Received enable event command: " + enableEventCmd
.toString());
321 case CMD_EVENT_DISABLE
:
323 if (inputData
== null) {
324 /* Invalid command */
325 response
= LttngAgentResponse
.FAILURE_RESPONSE
;
328 SessiondCommand disableEventCmd
= new SessiondDisableEventCommand(inputData
);
329 response
= disableEventCmd
.execute(logAgent
);
330 log("Received disable event command: " + disableEventCmd
.toString());
333 case CMD_APP_CTX_ENABLE
:
335 if (inputData
== null) {
336 /* This commands expects a payload, invalid command */
337 response
= LttngAgentResponse
.FAILURE_RESPONSE
;
340 SessiondCommand enableAppCtxCmd
= new SessiondEnableAppContextCommand(inputData
);
341 response
= enableAppCtxCmd
.execute(logAgent
);
342 log("Received enable app-context command");
345 case CMD_APP_CTX_DISABLE
:
347 if (inputData
== null) {
348 /* This commands expects a payload, invalid command */
349 response
= LttngAgentResponse
.FAILURE_RESPONSE
;
352 SessiondCommand disableAppCtxCmd
= new SessiondDisableAppContextCommand(inputData
);
353 response
= disableAppCtxCmd
.execute(logAgent
);
354 log("Received disable app-context command");
359 /* Unknown command, send empty reply */
361 log("Received unknown command, ignoring");
366 /* Send response to the session daemon. */
368 if (response
== null) {
369 responseData
= new byte[4];
370 ByteBuffer buf
= ByteBuffer
.wrap(responseData
);
371 buf
.order(ByteOrder
.BIG_ENDIAN
);
373 log("Sending response: " + response
.toString());
374 responseData
= response
.getBytes();
376 this.outToSessiond
.write(responseData
, 0, responseData
.length
);
377 this.outToSessiond
.flush();
382 * Receive header data from the session daemon using the LTTng command
383 * static buffer of the right size.
385 private SessiondCommandHeader
recvHeader() throws IOException
{
386 byte data
[] = new byte[SessiondCommandHeader
.HEADER_SIZE
];
387 int bytesLeft
= data
.length
;
390 while (bytesLeft
>= 0) {
391 int bytesRead
= this.inFromSessiond
.read(data
, bytesOffset
, bytesLeft
);
394 throw new IOException();
396 bytesLeft
-= bytesRead
;
397 bytesOffset
+= bytesRead
;
399 return new SessiondCommandHeader(data
);
403 * Receive payload from the session daemon. This MUST be done after a
404 * recvHeader() so the header value of a command are known.
406 * The caller SHOULD use isPayload() before which returns true if a payload
407 * is expected after the header.
409 private byte[] recvPayload(SessiondCommandHeader headerCmd
) throws IOException
{
410 byte payload
[] = new byte[(int) headerCmd
.getDataSize()];
411 int bytesLeft
= payload
.length
;
414 /* Failsafe check so we don't waste our time reading 0 bytes. */
415 if (bytesLeft
== 0) {
419 while (bytesLeft
>= 0) {
420 int bytesRead
= inFromSessiond
.read(payload
, bytesOffset
, bytesLeft
);
423 throw new IOException();
425 bytesLeft
-= bytesRead
;
426 bytesOffset
+= bytesRead
;
432 * Wrapper for this class's logging, adds the connection's characteristics
433 * to help differentiate between multiple TCP clients.
435 private void log(String message
) {
436 LttngUstAgentLogger
.log(getClass(),
437 "(root=" + isRoot
+ ", domain=" + domainValue
+ ") " + message
);