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.FileNotFoundException;
25 import java.io.FileReader;
26 import java.io.IOException;
27 import java.lang.management.ManagementFactory;
28 import java.net.Socket;
29 import java.net.UnknownHostException;
30 import java.nio.ByteBuffer;
31 import java.nio.ByteOrder;
32 import java.util.concurrent.CountDownLatch;
33 import java.util.concurrent.TimeUnit;
36 * Client for agents to connect to a local session daemon, using a TCP socket.
38 * @author David Goulet
40 public class LttngTcpSessiondClient implements Runnable {
42 private static final String SESSION_HOST = "127.0.0.1";
43 private static final String ROOT_PORT_FILE = "/var/run/lttng/agent.port";
44 private static final String USER_PORT_FILE = "/.lttng/agent.port";
46 private static final int PROTOCOL_MAJOR_VERSION = 2;
47 private static final int PROTOCOL_MINOR_VERSION = 0;
49 /** Command header from the session deamon. */
50 private final CountDownLatch registrationLatch = new CountDownLatch(1);
52 private Socket sessiondSock;
53 private volatile boolean quit = false;
55 private DataInputStream inFromSessiond;
56 private DataOutputStream outToSessiond;
58 private final ILttngTcpClientListener logAgent;
59 private final int domainValue;
60 private final boolean isRoot;
66 * The listener this client will operate on, typically an LTTng
69 * The integer to send to the session daemon representing the
70 * tracing domain to handle.
72 * True if this client should connect to the root session daemon,
73 * false if it should connect to the user one.
75 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent, int domainValue, boolean isRoot) {
76 this.logAgent = logAgent;
77 this.domainValue = domainValue;
82 * Wait until this client has successfully established a connection to its
83 * target session daemon.
86 * A timeout in seconds after which this method will return
88 * @return True if the the client actually established the connection, false
89 * if we returned because the timeout has elapsed or the thread was
92 public boolean waitForConnection(int seconds) {
94 return registrationLatch.await(seconds, TimeUnit.SECONDS);
95 } catch (InterruptedException e) {
110 * Connect to the session daemon before anything else.
115 * Register to the session daemon as the Java component of the
118 registerToSessiond();
121 * Block on socket receive and wait for command from the
122 * session daemon. This will return if and only if there is a
123 * fatal error or the socket closes.
126 } catch (UnknownHostException uhe) {
127 uhe.printStackTrace();
128 } catch (IOException ioe) {
131 } catch (InterruptedException e) {
139 * Dispose this client and close any socket connection it may hold.
141 public void close() {
145 if (this.sessiondSock != null) {
146 this.sessiondSock.close();
148 } catch (IOException e) {
153 private void connectToSessiond() throws IOException {
157 port = getPortFromFile(ROOT_PORT_FILE);
159 /* No session daemon available. Stop and retry later. */
160 throw new IOException();
163 port = getPortFromFile(getHomePath() + USER_PORT_FILE);
165 /* No session daemon available. Stop and retry later. */
166 throw new IOException();
170 this.sessiondSock = new Socket(SESSION_HOST, port);
171 this.inFromSessiond = new DataInputStream(sessiondSock.getInputStream());
172 this.outToSessiond = new DataOutputStream(sessiondSock.getOutputStream());
175 private static String getHomePath() {
176 return System.getProperty("user.home");
180 * Read port number from file created by the session daemon.
182 * @return port value if found else 0.
184 private static int getPortFromFile(String path) throws IOException {
186 BufferedReader br = null;
189 br = new BufferedReader(new FileReader(path));
190 String line = br.readLine();
191 port = Integer.parseInt(line, 10);
192 if (port < 0 || port > 65535) {
193 /* Invalid value. Ignore. */
196 } catch (FileNotFoundException e) {
197 /* No port available. */
208 private void registerToSessiond() throws IOException {
209 byte data[] = new byte[16];
210 ByteBuffer buf = ByteBuffer.wrap(data);
211 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
213 buf.putInt(domainValue);
214 buf.putInt(Integer.parseInt(pid));
215 buf.putInt(PROTOCOL_MAJOR_VERSION);
216 buf.putInt(PROTOCOL_MINOR_VERSION);
217 this.outToSessiond.write(data, 0, data.length);
218 this.outToSessiond.flush();
222 * Handle session command from the session daemon.
224 private void handleSessiondCmd() throws IOException {
225 /* Data read from the socket */
226 byte inputData[] = null;
227 /* Reply data written to the socket, sent to the sessiond */
228 byte responseData[] = null;
231 /* Get header from session daemon. */
232 SessiondCommandHeader cmdHeader = recvHeader();
234 if (cmdHeader.getDataSize() > 0) {
235 inputData = recvPayload(cmdHeader);
238 switch (cmdHeader.getCommandType()) {
242 * Countdown the registration latch, meaning registration is
243 * done and we can proceed to continue tracing.
245 registrationLatch.countDown();
247 * We don't send any reply to the registration done command.
248 * This just marks the end of the initial session setup.
254 SessiondCommand listLoggerCmd = new SessiondListLoggersCommand();
255 LttngAgentResponse response = listLoggerCmd.execute(logAgent);
256 responseData = response.getBytes();
259 case CMD_EVENT_ENABLE:
261 if (inputData == null) {
262 /* Invalid command */
263 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
266 SessiondCommand enableEventCmd = new SessiondEnableEventCommand(inputData);
267 LttngAgentResponse response = enableEventCmd.execute(logAgent);
268 responseData = response.getBytes();
271 case CMD_EVENT_DISABLE:
273 if (inputData == null) {
274 /* Invalid command */
275 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
278 SessiondCommand disableEventCmd = new SessiondDisableEventCommand(inputData);
279 LttngAgentResponse response = disableEventCmd.execute(logAgent);
280 responseData = response.getBytes();
283 case CMD_APP_CTX_ENABLE:
285 if (inputData == null) {
286 /* This commands expects a payload, invalid command */
287 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
290 SessiondCommand enableAppCtxCmd = new SessiondEnableAppContextCommand(inputData);
291 LttngAgentResponse response = enableAppCtxCmd.execute(logAgent);
292 responseData = response.getBytes();
295 case CMD_APP_CTX_DISABLE:
297 if (inputData == null) {
298 /* This commands expects a payload, invalid command */
299 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
302 SessiondCommand disableAppCtxCmd = new SessiondDisableAppContextCommand(inputData);
303 LttngAgentResponse response = disableAppCtxCmd.execute(logAgent);
304 responseData = response.getBytes();
309 /* Unknown command, send empty reply */
310 responseData = new byte[4];
311 ByteBuffer buf = ByteBuffer.wrap(responseData);
312 buf.order(ByteOrder.BIG_ENDIAN);
317 /* Send response to the session daemon. */
318 this.outToSessiond.write(responseData, 0, responseData.length);
319 this.outToSessiond.flush();
324 * Receive header data from the session daemon using the LTTng command
325 * static buffer of the right size.
327 private SessiondCommandHeader recvHeader() throws IOException {
328 byte data[] = new byte[SessiondCommandHeader.HEADER_SIZE];
330 int readLen = this.inFromSessiond.read(data, 0, data.length);
331 if (readLen != data.length) {
332 throw new IOException();
334 return new SessiondCommandHeader(data);
338 * Receive payload from the session daemon. This MUST be done after a
339 * recvHeader() so the header value of a command are known.
341 * The caller SHOULD use isPayload() before which returns true if a payload
342 * is expected after the header.
344 private byte[] recvPayload(SessiondCommandHeader headerCmd) throws IOException {
345 byte payload[] = new byte[(int) headerCmd.getDataSize()];
347 /* Failsafe check so we don't waste our time reading 0 bytes. */
348 if (payload.length == 0) {
352 this.inFromSessiond.read(payload, 0, payload.length);