2 * Copyright (C) 2013 - David Goulet <dgoulet@efficios.com>
4 * This library is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU Lesser General Public License, version 2.1 only,
6 * as published by the Free Software Foundation.
8 * This library is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this library; if not, write to the Free Software Foundation,
15 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 package org
.lttng
.ust
.agent
.client
;
20 import java
.io
.BufferedReader
;
21 import java
.io
.DataInputStream
;
22 import java
.io
.DataOutputStream
;
23 import java
.io
.FileNotFoundException
;
24 import java
.io
.FileReader
;
25 import java
.io
.IOException
;
26 import java
.lang
.management
.ManagementFactory
;
27 import java
.net
.Socket
;
28 import java
.net
.UnknownHostException
;
29 import java
.nio
.ByteBuffer
;
30 import java
.nio
.ByteOrder
;
31 import java
.util
.concurrent
.CountDownLatch
;
32 import java
.util
.concurrent
.TimeUnit
;
35 * Client for agents to connect to a local session daemon, using a TCP socket.
37 * @author David Goulet
39 public class LttngTcpSessiondClient
implements Runnable
{
41 private static final String SESSION_HOST
= "127.0.0.1";
42 private static final String ROOT_PORT_FILE
= "/var/run/lttng/agent.port";
43 private static final String USER_PORT_FILE
= "/.lttng/agent.port";
45 private static final int PROTOCOL_MAJOR_VERSION
= 2;
46 private static final int PROTOCOL_MINOR_VERSION
= 0;
48 /** Command header from the session deamon. */
49 private final CountDownLatch registrationLatch
= new CountDownLatch(1);
51 private Socket sessiondSock
;
52 private volatile boolean quit
= false;
54 private DataInputStream inFromSessiond
;
55 private DataOutputStream outToSessiond
;
57 private final ILttngTcpClientListener logAgent
;
58 private final int domainValue
;
59 private final boolean isRoot
;
65 * The listener this client will operate on, typically an LTTng
68 * The integer to send to the session daemon representing the
69 * tracing domain to handle.
71 * True if this client should connect to the root session daemon,
72 * false if it should connect to the user one.
74 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent
, int domainValue
, boolean isRoot
) {
75 this.logAgent
= logAgent
;
76 this.domainValue
= domainValue
;
81 * Wait until this client has successfully established a connection to its
82 * target session daemon.
85 * A timeout in seconds after which this method will return
87 * @return True if the the client actually established the connection, false
88 * if we returned because the timeout has elapsed or the thread was
91 public boolean waitForConnection(int seconds
) {
93 return registrationLatch
.await(seconds
, TimeUnit
.SECONDS
);
94 } catch (InterruptedException e
) {
109 * Connect to the session daemon before anything else.
114 * Register to the session daemon as the Java component of the
117 registerToSessiond();
120 * Block on socket receive and wait for command from the
121 * session daemon. This will return if and only if there is a
122 * fatal error or the socket closes.
125 } catch (UnknownHostException uhe
) {
126 uhe
.printStackTrace();
127 } catch (IOException ioe
) {
130 } catch (InterruptedException e
) {
138 * Dispose this client and close any socket connection it may hold.
140 public void close() {
144 if (this.sessiondSock
!= null) {
145 this.sessiondSock
.close();
147 } catch (IOException e
) {
152 private void connectToSessiond() throws IOException
{
156 port
= getPortFromFile(ROOT_PORT_FILE
);
158 /* No session daemon available. Stop and retry later. */
159 throw new IOException();
162 port
= getPortFromFile(getHomePath() + USER_PORT_FILE
);
164 /* No session daemon available. Stop and retry later. */
165 throw new IOException();
169 this.sessiondSock
= new Socket(SESSION_HOST
, port
);
170 this.inFromSessiond
= new DataInputStream(sessiondSock
.getInputStream());
171 this.outToSessiond
= new DataOutputStream(sessiondSock
.getOutputStream());
174 private static String
getHomePath() {
175 return System
.getProperty("user.home");
179 * Read port number from file created by the session daemon.
181 * @return port value if found else 0.
183 private static int getPortFromFile(String path
) throws IOException
{
185 BufferedReader br
= null;
188 br
= new BufferedReader(new FileReader(path
));
189 String line
= br
.readLine();
190 port
= Integer
.parseInt(line
, 10);
191 if (port
< 0 || port
> 65535) {
192 /* Invalid value. Ignore. */
195 } catch (FileNotFoundException e
) {
196 /* No port available. */
207 private void registerToSessiond() throws IOException
{
208 byte data
[] = new byte[16];
209 ByteBuffer buf
= ByteBuffer
.wrap(data
);
210 String pid
= ManagementFactory
.getRuntimeMXBean().getName().split("@")[0];
212 buf
.putInt(domainValue
);
213 buf
.putInt(Integer
.parseInt(pid
));
214 buf
.putInt(PROTOCOL_MAJOR_VERSION
);
215 buf
.putInt(PROTOCOL_MINOR_VERSION
);
216 this.outToSessiond
.write(data
, 0, data
.length
);
217 this.outToSessiond
.flush();
221 * Handle session command from the session daemon.
223 private void handleSessiondCmd() throws IOException
{
224 /* Data read from the socket */
225 byte inputData
[] = null;
226 /* Reply data written to the socket, sent to the sessiond */
227 byte responseData
[] = null;
230 /* Get header from session daemon. */
231 SessiondCommandHeader cmdHeader
= recvHeader();
233 if (cmdHeader
.getDataSize() > 0) {
234 inputData
= recvPayload(cmdHeader
);
237 switch (cmdHeader
.getCommandType()) {
241 * Countdown the registration latch, meaning registration is
242 * done and we can proceed to continue tracing.
244 registrationLatch
.countDown();
246 * We don't send any reply to the registration done command.
247 * This just marks the end of the initial session setup.
253 ISessiondCommand listLoggerCmd
= new SessiondListLoggersCommand();
254 LttngAgentResponse response
= listLoggerCmd
.execute(logAgent
);
255 responseData
= response
.getBytes();
260 if (inputData
== null) {
261 /* Invalid command */
262 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
265 ISessiondCommand enableCmd
= new SessiondEnableEventCommand(inputData
);
266 LttngAgentResponse response
= enableCmd
.execute(logAgent
);
267 responseData
= response
.getBytes();
272 if (inputData
== null) {
273 /* Invalid command */
274 responseData
= LttngAgentResponse
.FAILURE_RESPONSE
.getBytes();
277 ISessiondCommand disableCmd
= new SessiondDisableEventCommand(inputData
);
278 LttngAgentResponse response
= disableCmd
.execute(logAgent
);
279 responseData
= response
.getBytes();
284 /* Unknown command, send empty reply */
285 responseData
= new byte[4];
286 ByteBuffer buf
= ByteBuffer
.wrap(responseData
);
287 buf
.order(ByteOrder
.BIG_ENDIAN
);
292 /* Send response to the session daemon. */
293 this.outToSessiond
.write(responseData
, 0, responseData
.length
);
294 this.outToSessiond
.flush();
299 * Receive header data from the session daemon using the LTTng command
300 * static buffer of the right size.
302 private SessiondCommandHeader
recvHeader() throws IOException
{
303 byte data
[] = new byte[SessiondCommandHeader
.HEADER_SIZE
];
305 int readLen
= this.inFromSessiond
.read(data
, 0, data
.length
);
306 if (readLen
!= data
.length
) {
307 throw new IOException();
309 return new SessiondCommandHeader(data
);
313 * Receive payload from the session daemon. This MUST be done after a
314 * recvHeader() so the header value of a command are known.
316 * The caller SHOULD use isPayload() before which returns true if a payload
317 * is expected after the header.
319 private byte[] recvPayload(SessiondCommandHeader headerCmd
) throws IOException
{
320 byte payload
[] = new byte[(int) headerCmd
.getDataSize()];
322 /* Failsafe check so we don't waste our time reading 0 bytes. */
323 if (payload
.length
== 0) {
327 this.inFromSessiond
.read(payload
, 0, payload
.length
);