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
;
25 import java
.io
.FileNotFoundException
;
26 import java
.io
.FileReader
;
27 import java
.io
.IOException
;
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
.util
.concurrent
.CountDownLatch
;
34 import java
.util
.concurrent
.TimeUnit
;
36 import org
.lttng
.ust
.agent
.utils
.LttngUstAgentLogger
;
39 * Client for agents to connect to a local session daemon, using a TCP socket.
41 * @author David Goulet
43 public class LttngTcpSessiondClient
implements Runnable
{
45 private static final String SESSION_HOST
= "127.0.0.1";
46 private static final String ROOT_PORT_FILE
= "/var/run/lttng/agent.port";
47 private static final String USER_PORT_FILE
= "/.lttng/agent.port";
49 private static final int PROTOCOL_MAJOR_VERSION
= 2;
50 private static final int PROTOCOL_MINOR_VERSION
= 0;
52 /** Command header from the session deamon. */
53 private final CountDownLatch registrationLatch
= new CountDownLatch(1);
55 private Socket sessiondSock
;
56 private volatile boolean quit
= false;
58 private DataInputStream inFromSessiond
;
59 private DataOutputStream outToSessiond
;
61 private final ILttngTcpClientListener logAgent
;
62 private final int domainValue
;
63 private final boolean isRoot
;
69 * The listener this client will operate on, typically an LTTng
72 * The integer to send to the session daemon representing the
73 * tracing domain to handle.
75 * True if this client should connect to the root session daemon,
76 * false if it should connect to the user one.
78 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent
, int domainValue
, boolean isRoot
) {
79 this.logAgent
= logAgent
;
80 this.domainValue
= domainValue
;
85 * Wait until this client has successfully established a connection to its
86 * target session daemon.
89 * A timeout in seconds after which this method will return
91 * @return True if the the client actually established the connection, false
92 * if we returned because the timeout has elapsed or the thread was
95 public boolean waitForConnection(int seconds
) {
97 return registrationLatch
.await(seconds
, TimeUnit
.SECONDS
);
98 } catch (InterruptedException e
) {
113 * Connect to the session daemon before anything else.
115 log("Connecting to sessiond");
119 * Register to the session daemon as the Java component of the
122 log("Registering to sessiond");
123 registerToSessiond();
126 * Block on socket receive and wait for command from the
127 * session daemon. This will return if and only if there is a
128 * fatal error or the socket closes.
130 log("Waiting on sessiond commands...");
132 } catch (UnknownHostException uhe
) {
133 uhe
.printStackTrace();
134 } catch (IOException ioe
) {
137 } catch (InterruptedException e
) {
145 * Dispose this client and close any socket connection it may hold.
147 public void close() {
148 log("Closing client");
152 if (this.sessiondSock
!= null) {
153 this.sessiondSock
.close();
155 } catch (IOException e
) {
160 private void connectToSessiond() throws IOException
{
161 int rootPort
= getPortFromFile(ROOT_PORT_FILE
);
162 int userPort
= getPortFromFile(getHomePath() + USER_PORT_FILE
);
165 * Check for the edge case of both files existing but pointing to the
166 * same port. In this case, let the root client handle it.
168 if ((rootPort
!= 0) && (rootPort
== userPort
) && (!isRoot
)) {
169 log("User and root config files both point to port " + rootPort
+
170 ". Letting the root client handle it.");
171 throw new IOException();
174 int portToUse
= (isRoot ? rootPort
: userPort
);
176 if (portToUse
== 0) {
177 /* No session daemon available. Stop and retry later. */
178 throw new IOException();
181 this.sessiondSock
= new Socket(SESSION_HOST
, portToUse
);
182 this.inFromSessiond
= new DataInputStream(sessiondSock
.getInputStream());
183 this.outToSessiond
= new DataOutputStream(sessiondSock
.getOutputStream());
186 private static String
getHomePath() {
188 * The environment variable LTTNG_HOME overrides HOME if
191 String homePath
= System
.getenv("LTTNG_HOME");
193 if (homePath
== null) {
194 homePath
= System
.getProperty("user.home");
200 * Read port number from file created by the session daemon.
202 * @return port value if found else 0.
204 private static int getPortFromFile(String path
) throws IOException
{
206 BufferedReader br
= null;
207 File file
= new File(path
);
210 br
= new BufferedReader(new FileReader(file
));
211 String line
= br
.readLine();
212 port
= Integer
.parseInt(line
, 10);
213 if (port
< 0 || port
> 65535) {
214 /* Invalid value. Ignore. */
217 } catch (FileNotFoundException e
) {
218 /* No port available. */
229 private void registerToSessiond() throws IOException
{
230 byte data
[] = new byte[16];
231 ByteBuffer buf
= ByteBuffer
.wrap(data
);
232 String pid
= ManagementFactory
.getRuntimeMXBean().getName().split("@")[0];
234 buf
.putInt(domainValue
);
235 buf
.putInt(Integer
.parseInt(pid
));
236 buf
.putInt(PROTOCOL_MAJOR_VERSION
);
237 buf
.putInt(PROTOCOL_MINOR_VERSION
);
238 this.outToSessiond
.write(data
, 0, data
.length
);
239 this.outToSessiond
.flush();
243 * Handle session command from the session daemon.
245 private void handleSessiondCmd() throws IOException
{
246 /* Data read from the socket */
247 byte inputData
[] = null;
248 /* Reply data written to the socket, sent to the sessiond */
249 byte responseData
[] = null;
252 /* Get header from session daemon. */
253 SessiondCommandHeader cmdHeader
= recvHeader();
255 if (cmdHeader
.getDataSize() > 0) {
256 inputData
= recvPayload(cmdHeader
);
259 switch (cmdHeader
.getCommandType()) {
263 * Countdown the registration latch, meaning registration is
264 * done and we can proceed to continue tracing.
266 registrationLatch
.countDown();
268 * We don't send any reply to the registration done command.
269 * This just marks the end of the initial session setup.
271 log("Registration done");
276 SessiondCommand listLoggerCmd
= new SessiondListLoggersCommand();
277 LttngAgentResponse response
= listLoggerCmd
.execute(logAgent
);
278 responseData
= response
.getBytes();
279 log("Received list loggers command");
282 case CMD_EVENT_ENABLE
:
284 if (inputData
== null) {
285 /* Invalid command */
286 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
289 SessiondCommand enableEventCmd
= new SessiondEnableEventCommand(inputData
);
290 LttngAgentResponse response
= enableEventCmd
.execute(logAgent
);
291 responseData
= response
.getBytes();
292 log("Received enable event command");
295 case CMD_EVENT_DISABLE
:
297 if (inputData
== null) {
298 /* Invalid command */
299 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
302 SessiondCommand disableEventCmd
= new SessiondDisableEventCommand(inputData
);
303 LttngAgentResponse response
= disableEventCmd
.execute(logAgent
);
304 responseData
= response
.getBytes();
305 log("Received disable event command");
308 case CMD_APP_CTX_ENABLE
:
310 if (inputData
== null) {
311 /* This commands expects a payload, invalid command */
312 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
315 SessiondCommand enableAppCtxCmd
= new SessiondEnableAppContextCommand(inputData
);
316 LttngAgentResponse response
= enableAppCtxCmd
.execute(logAgent
);
317 responseData
= response
.getBytes();
318 log("Received enable app-context command");
321 case CMD_APP_CTX_DISABLE
:
323 if (inputData
== null) {
324 /* This commands expects a payload, invalid command */
325 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
328 SessiondCommand disableAppCtxCmd
= new SessiondDisableAppContextCommand(inputData
);
329 LttngAgentResponse response
= disableAppCtxCmd
.execute(logAgent
);
330 responseData
= response
.getBytes();
331 log("Received disable app-context command");
336 /* Unknown command, send empty reply */
337 responseData
= new byte[4];
338 ByteBuffer buf
= ByteBuffer
.wrap(responseData
);
339 buf
.order(ByteOrder
.BIG_ENDIAN
);
340 log("Received unknown command, ignoring");
345 /* Send response to the session daemon. */
346 log("Sending response");
347 this.outToSessiond
.write(responseData
, 0, responseData
.length
);
348 this.outToSessiond
.flush();
353 * Receive header data from the session daemon using the LTTng command
354 * static buffer of the right size.
356 private SessiondCommandHeader
recvHeader() throws IOException
{
357 byte data
[] = new byte[SessiondCommandHeader
.HEADER_SIZE
];
359 int readLen
= this.inFromSessiond
.read(data
, 0, data
.length
);
360 if (readLen
!= data
.length
) {
361 throw new IOException();
363 return new SessiondCommandHeader(data
);
367 * Receive payload from the session daemon. This MUST be done after a
368 * recvHeader() so the header value of a command are known.
370 * The caller SHOULD use isPayload() before which returns true if a payload
371 * is expected after the header.
373 private byte[] recvPayload(SessiondCommandHeader headerCmd
) throws IOException
{
374 byte payload
[] = new byte[(int) headerCmd
.getDataSize()];
376 /* Failsafe check so we don't waste our time reading 0 bytes. */
377 if (payload
.length
== 0) {
381 int read
= inFromSessiond
.read(payload
, 0, payload
.length
);
382 if (read
!= payload
.length
) {
383 throw new IOException("Unexpected number of bytes read in sessiond command payload");
389 * Wrapper for this class's logging, adds the connection's characteristics
390 * to help differentiate between multiple TCP clients.
392 private void log(String message
) {
393 LttngUstAgentLogger
.log(getClass(),
394 "(root=" + isRoot
+ ", domain=" + domainValue
+ ") " + message
);