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();
136 } catch (IOException ioe
) {
139 } catch (InterruptedException e
) {
147 * Dispose this client and close any socket connection it may hold.
149 public void close() {
150 log("Closing client");
154 if (this.sessiondSock
!= null) {
155 this.sessiondSock
.close();
157 } catch (IOException e
) {
162 private void connectToSessiond() throws IOException
{
163 int rootPort
= getPortFromFile(ROOT_PORT_FILE
);
164 int userPort
= getPortFromFile(getHomePath() + USER_PORT_FILE
);
167 * Check for the edge case of both files existing but pointing to the
168 * same port. In this case, let the root client handle it.
170 if ((rootPort
!= 0) && (rootPort
== userPort
) && (!isRoot
)) {
171 log("User and root config files both point to port " + rootPort
+
172 ". Letting the root client handle it.");
173 throw new IOException();
176 int portToUse
= (isRoot ? rootPort
: userPort
);
178 if (portToUse
== 0) {
179 /* No session daemon available. Stop and retry later. */
180 throw new IOException();
183 this.sessiondSock
= new Socket(SESSION_HOST
, portToUse
);
184 this.inFromSessiond
= new DataInputStream(sessiondSock
.getInputStream());
185 this.outToSessiond
= new DataOutputStream(sessiondSock
.getOutputStream());
188 private static String
getHomePath() {
190 * The environment variable LTTNG_HOME overrides HOME if
193 String homePath
= System
.getenv("LTTNG_HOME");
195 if (homePath
== null) {
196 homePath
= System
.getProperty("user.home");
202 * Read port number from file created by the session daemon.
204 * @return port value if found else 0.
206 private static int getPortFromFile(String path
) throws IOException
{
207 BufferedReader br
= null;
210 br
= new BufferedReader(new InputStreamReader(new FileInputStream(path
), PORT_FILE_ENCODING
));
211 String line
= br
.readLine();
213 /* File exists but is empty. */
217 int port
= Integer
.parseInt(line
, 10);
218 if (port
< 0 || port
> 65535) {
219 /* Invalid value. Ignore. */
224 } catch (NumberFormatException e
) {
225 /* File contained something that was not a number. */
227 } catch (FileNotFoundException e
) {
228 /* No port available. */
237 private void registerToSessiond() throws IOException
{
238 byte data
[] = new byte[16];
239 ByteBuffer buf
= ByteBuffer
.wrap(data
);
240 String pid
= ManagementFactory
.getRuntimeMXBean().getName().split("@")[0];
242 buf
.putInt(domainValue
);
243 buf
.putInt(Integer
.parseInt(pid
));
244 buf
.putInt(PROTOCOL_MAJOR_VERSION
);
245 buf
.putInt(PROTOCOL_MINOR_VERSION
);
246 this.outToSessiond
.write(data
, 0, data
.length
);
247 this.outToSessiond
.flush();
251 * Handle session command from the session daemon.
253 private void handleSessiondCmd() throws IOException
{
254 /* Data read from the socket */
255 byte inputData
[] = null;
256 /* Reply data written to the socket, sent to the sessiond */
257 byte responseData
[] = null;
260 /* Get header from session daemon. */
261 SessiondCommandHeader cmdHeader
= recvHeader();
263 if (cmdHeader
.getDataSize() > 0) {
264 inputData
= recvPayload(cmdHeader
);
267 switch (cmdHeader
.getCommandType()) {
271 * Countdown the registration latch, meaning registration is
272 * done and we can proceed to continue tracing.
274 registrationLatch
.countDown();
276 * We don't send any reply to the registration done command.
277 * This just marks the end of the initial session setup.
279 log("Registration done");
284 SessiondCommand listLoggerCmd
= new SessiondListLoggersCommand();
285 LttngAgentResponse response
= listLoggerCmd
.execute(logAgent
);
286 responseData
= response
.getBytes();
287 log("Received list loggers command");
290 case CMD_EVENT_ENABLE
:
292 if (inputData
== null) {
293 /* Invalid command */
294 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
297 SessiondCommand enableEventCmd
= new SessiondEnableEventCommand(inputData
);
298 LttngAgentResponse response
= enableEventCmd
.execute(logAgent
);
299 responseData
= response
.getBytes();
300 log("Received enable event command");
303 case CMD_EVENT_DISABLE
:
305 if (inputData
== null) {
306 /* Invalid command */
307 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
310 SessiondCommand disableEventCmd
= new SessiondDisableEventCommand(inputData
);
311 LttngAgentResponse response
= disableEventCmd
.execute(logAgent
);
312 responseData
= response
.getBytes();
313 log("Received disable event command");
316 case CMD_APP_CTX_ENABLE
:
318 if (inputData
== null) {
319 /* This commands expects a payload, invalid command */
320 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
323 SessiondCommand enableAppCtxCmd
= new SessiondEnableAppContextCommand(inputData
);
324 LttngAgentResponse response
= enableAppCtxCmd
.execute(logAgent
);
325 responseData
= response
.getBytes();
326 log("Received enable app-context command");
329 case CMD_APP_CTX_DISABLE
:
331 if (inputData
== null) {
332 /* This commands expects a payload, invalid command */
333 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
336 SessiondCommand disableAppCtxCmd
= new SessiondDisableAppContextCommand(inputData
);
337 LttngAgentResponse response
= disableAppCtxCmd
.execute(logAgent
);
338 responseData
= response
.getBytes();
339 log("Received disable app-context command");
344 /* Unknown command, send empty reply */
345 responseData
= new byte[4];
346 ByteBuffer buf
= ByteBuffer
.wrap(responseData
);
347 buf
.order(ByteOrder
.BIG_ENDIAN
);
348 log("Received unknown command, ignoring");
353 /* Send response to the session daemon. */
354 log("Sending response");
355 this.outToSessiond
.write(responseData
, 0, responseData
.length
);
356 this.outToSessiond
.flush();
361 * Receive header data from the session daemon using the LTTng command
362 * static buffer of the right size.
364 private SessiondCommandHeader
recvHeader() throws IOException
{
365 byte data
[] = new byte[SessiondCommandHeader
.HEADER_SIZE
];
367 int readLen
= this.inFromSessiond
.read(data
, 0, data
.length
);
368 if (readLen
!= data
.length
) {
369 throw new IOException();
371 return new SessiondCommandHeader(data
);
375 * Receive payload from the session daemon. This MUST be done after a
376 * recvHeader() so the header value of a command are known.
378 * The caller SHOULD use isPayload() before which returns true if a payload
379 * is expected after the header.
381 private byte[] recvPayload(SessiondCommandHeader headerCmd
) throws IOException
{
382 byte payload
[] = new byte[(int) headerCmd
.getDataSize()];
384 /* Failsafe check so we don't waste our time reading 0 bytes. */
385 if (payload
.length
== 0) {
389 int read
= inFromSessiond
.read(payload
, 0, payload
.length
);
390 if (read
!= payload
.length
) {
391 throw new IOException("Unexpected number of bytes read in sessiond command payload");
397 * Wrapper for this class's logging, adds the connection's characteristics
398 * to help differentiate between multiple TCP clients.
400 private void log(String message
) {
401 LttngUstAgentLogger
.log(getClass(),
402 "(root=" + isRoot
+ ", domain=" + domainValue
+ ") " + message
);