Fix: Include child loggers in the output of "lttng list"
[lttng-ust.git] / liblttng-ust-java-agent / java / lttng-ust-agent-common / org / lttng / ust / agent / client / LttngTcpSessiondClient.java
CommitLineData
43e5396b 1/*
8ab5c06b 2 * Copyright (C) 2015-2016 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
43e5396b
DG
3 * Copyright (C) 2013 - David Goulet <dgoulet@efficios.com>
4 *
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.
8 *
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
12 * for more details.
13 *
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
17 */
18
d60dfbe4 19package org.lttng.ust.agent.client;
43e5396b 20
f1fa0535 21import java.io.BufferedReader;
43e5396b 22import java.io.DataInputStream;
bc7de6d9 23import java.io.DataOutputStream;
22191ffd 24import java.io.File;
f1fa0535 25import java.io.FileNotFoundException;
bc7de6d9
AM
26import java.io.FileReader;
27import java.io.IOException;
43e5396b 28import java.lang.management.ManagementFactory;
bc7de6d9
AM
29import java.net.Socket;
30import java.net.UnknownHostException;
31import java.nio.ByteBuffer;
32import java.nio.ByteOrder;
d60dfbe4
AM
33import java.util.concurrent.CountDownLatch;
34import java.util.concurrent.TimeUnit;
43e5396b 35
cbe2ebd6
AM
36import org.lttng.ust.agent.utils.LttngUstAgentLogger;
37
d60dfbe4
AM
38/**
39 * Client for agents to connect to a local session daemon, using a TCP socket.
40 *
41 * @author David Goulet
42 */
43public class LttngTcpSessiondClient implements Runnable {
43e5396b 44
08284556
AM
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";
48
191f4058
AM
49 private static final int PROTOCOL_MAJOR_VERSION = 2;
50 private static final int PROTOCOL_MINOR_VERSION = 0;
08284556 51
d60dfbe4 52 /** Command header from the session deamon. */
d60dfbe4 53 private final CountDownLatch registrationLatch = new CountDownLatch(1);
43e5396b 54
43e5396b 55 private Socket sessiondSock;
501f6777 56 private volatile boolean quit = false;
43e5396b
DG
57
58 private DataInputStream inFromSessiond;
59 private DataOutputStream outToSessiond;
60
3165c2f5
AM
61 private final ILttngTcpClientListener logAgent;
62 private final int domainValue;
d60dfbe4 63 private final boolean isRoot;
501f6777 64
d60dfbe4
AM
65 /**
66 * Constructor
67 *
68 * @param logAgent
3165c2f5
AM
69 * The listener this client will operate on, typically an LTTng
70 * agent.
71 * @param domainValue
72 * The integer to send to the session daemon representing the
73 * tracing domain to handle.
d60dfbe4
AM
74 * @param isRoot
75 * True if this client should connect to the root session daemon,
76 * false if it should connect to the user one.
77 */
3165c2f5 78 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent, int domainValue, boolean isRoot) {
d60dfbe4 79 this.logAgent = logAgent;
3165c2f5 80 this.domainValue = domainValue;
d60dfbe4 81 this.isRoot = isRoot;
43e5396b
DG
82 }
83
d60dfbe4
AM
84 /**
85 * Wait until this client has successfully established a connection to its
86 * target session daemon.
87 *
88 * @param seconds
89 * A timeout in seconds after which this method will return
90 * anyway.
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
93 * interrupted.
f1fa0535 94 */
d60dfbe4
AM
95 public boolean waitForConnection(int seconds) {
96 try {
97 return registrationLatch.await(seconds, TimeUnit.SECONDS);
98 } catch (InterruptedException e) {
99 return false;
f1fa0535
DG
100 }
101 }
102
501f6777
CB
103 @Override
104 public void run() {
43e5396b
DG
105 for (;;) {
106 if (this.quit) {
107 break;
108 }
109
110 try {
111
112 /*
113 * Connect to the session daemon before anything else.
114 */
6e1fdc3a 115 log("Connecting to sessiond");
43e5396b
DG
116 connectToSessiond();
117
118 /*
119 * Register to the session daemon as the Java component of the
120 * UST application.
121 */
6e1fdc3a 122 log("Registering to sessiond");
43e5396b 123 registerToSessiond();
43e5396b 124
43e5396b
DG
125 /*
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.
129 */
6e1fdc3a 130 log("Waiting on sessiond commands...");
43e5396b
DG
131 handleSessiondCmd();
132 } catch (UnknownHostException uhe) {
d60dfbe4 133 uhe.printStackTrace();
43e5396b 134 } catch (IOException ioe) {
501f6777
CB
135 try {
136 Thread.sleep(3000);
137 } catch (InterruptedException e) {
138 e.printStackTrace();
139 }
43e5396b
DG
140 }
141 }
142 }
143
d60dfbe4
AM
144 /**
145 * Dispose this client and close any socket connection it may hold.
146 */
147 public void close() {
6e1fdc3a 148 log("Closing client");
43e5396b 149 this.quit = true;
43e5396b
DG
150
151 try {
152 if (this.sessiondSock != null) {
153 this.sessiondSock.close();
154 }
d60dfbe4 155 } catch (IOException e) {
43e5396b
DG
156 e.printStackTrace();
157 }
158 }
159
301a3ddb 160 private void connectToSessiond() throws IOException {
e0c010a9
AM
161 int rootPort = getPortFromFile(ROOT_PORT_FILE);
162 int userPort = getPortFromFile(getHomePath() + USER_PORT_FILE);
163
164 /*
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.
167 */
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();
172 }
43e5396b 173
e0c010a9
AM
174 int portToUse = (isRoot ? rootPort : userPort);
175
176 if (portToUse == 0) {
177 /* No session daemon available. Stop and retry later. */
178 throw new IOException();
43e5396b 179 }
301a3ddb 180
e0c010a9 181 this.sessiondSock = new Socket(SESSION_HOST, portToUse);
301a3ddb
AM
182 this.inFromSessiond = new DataInputStream(sessiondSock.getInputStream());
183 this.outToSessiond = new DataOutputStream(sessiondSock.getOutputStream());
184 }
185
186 private static String getHomePath() {
59e3be47
MD
187 /*
188 * The environment variable LTTNG_HOME overrides HOME if
189 * defined.
190 */
191 String homePath = System.getenv("LTTNG_HOME");
192
193 if (homePath == null) {
194 homePath = System.getProperty("user.home");
195 }
196 return homePath;
43e5396b
DG
197 }
198
d60dfbe4 199 /**
301a3ddb 200 * Read port number from file created by the session daemon.
43e5396b 201 *
301a3ddb 202 * @return port value if found else 0.
43e5396b 203 */
301a3ddb
AM
204 private static int getPortFromFile(String path) throws IOException {
205 int port;
206 BufferedReader br = null;
22191ffd 207 File file = new File(path);
43e5396b 208
301a3ddb 209 try {
22191ffd 210 br = new BufferedReader(new FileReader(file));
301a3ddb
AM
211 String line = br.readLine();
212 port = Integer.parseInt(line, 10);
213 if (port < 0 || port > 65535) {
214 /* Invalid value. Ignore. */
215 port = 0;
216 }
217 } catch (FileNotFoundException e) {
218 /* No port available. */
219 port = 0;
220 } finally {
221 if (br != null) {
222 br.close();
223 }
43e5396b
DG
224 }
225
301a3ddb
AM
226 return port;
227 }
228
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];
233
3165c2f5 234 buf.putInt(domainValue);
301a3ddb 235 buf.putInt(Integer.parseInt(pid));
191f4058
AM
236 buf.putInt(PROTOCOL_MAJOR_VERSION);
237 buf.putInt(PROTOCOL_MINOR_VERSION);
301a3ddb
AM
238 this.outToSessiond.write(data, 0, data.length);
239 this.outToSessiond.flush();
43e5396b
DG
240 }
241
d60dfbe4 242 /**
43e5396b
DG
243 * Handle session command from the session daemon.
244 */
d60dfbe4 245 private void handleSessiondCmd() throws IOException {
301a3ddb
AM
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;
43e5396b
DG
250
251 while (true) {
252 /* Get header from session daemon. */
301a3ddb 253 SessiondCommandHeader cmdHeader = recvHeader();
43e5396b 254
301a3ddb
AM
255 if (cmdHeader.getDataSize() > 0) {
256 inputData = recvPayload(cmdHeader);
43e5396b
DG
257 }
258
301a3ddb 259 switch (cmdHeader.getCommandType()) {
d60dfbe4
AM
260 case CMD_REG_DONE:
261 {
262 /*
263 * Countdown the registration latch, meaning registration is
264 * done and we can proceed to continue tracing.
265 */
266 registrationLatch.countDown();
267 /*
268 * We don't send any reply to the registration done command.
269 * This just marks the end of the initial session setup.
270 */
6e1fdc3a 271 log("Registration done");
d60dfbe4
AM
272 continue;
273 }
274 case CMD_LIST:
275 {
1d193914 276 SessiondCommand listLoggerCmd = new SessiondListLoggersCommand();
93253569 277 LttngAgentResponse response = listLoggerCmd.execute(logAgent);
301a3ddb 278 responseData = response.getBytes();
6e1fdc3a 279 log("Received list loggers command");
d60dfbe4
AM
280 break;
281 }
8ab5c06b 282 case CMD_EVENT_ENABLE:
d60dfbe4 283 {
301a3ddb
AM
284 if (inputData == null) {
285 /* Invalid command */
93253569 286 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
43e5396b
DG
287 break;
288 }
8ab5c06b
AM
289 SessiondCommand enableEventCmd = new SessiondEnableEventCommand(inputData);
290 LttngAgentResponse response = enableEventCmd.execute(logAgent);
301a3ddb 291 responseData = response.getBytes();
6e1fdc3a 292 log("Received enable event command");
d60dfbe4
AM
293 break;
294 }
8ab5c06b 295 case CMD_EVENT_DISABLE:
d60dfbe4 296 {
301a3ddb
AM
297 if (inputData == null) {
298 /* Invalid command */
93253569 299 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
43e5396b
DG
300 break;
301 }
8ab5c06b
AM
302 SessiondCommand disableEventCmd = new SessiondDisableEventCommand(inputData);
303 LttngAgentResponse response = disableEventCmd.execute(logAgent);
304 responseData = response.getBytes();
6e1fdc3a 305 log("Received disable event command");
8ab5c06b
AM
306 break;
307 }
308 case CMD_APP_CTX_ENABLE:
309 {
310 if (inputData == null) {
311 /* This commands expects a payload, invalid command */
312 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
313 break;
314 }
315 SessiondCommand enableAppCtxCmd = new SessiondEnableAppContextCommand(inputData);
316 LttngAgentResponse response = enableAppCtxCmd.execute(logAgent);
317 responseData = response.getBytes();
6e1fdc3a 318 log("Received enable app-context command");
8ab5c06b
AM
319 break;
320 }
321 case CMD_APP_CTX_DISABLE:
322 {
323 if (inputData == null) {
324 /* This commands expects a payload, invalid command */
325 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
326 break;
327 }
328 SessiondCommand disableAppCtxCmd = new SessiondDisableAppContextCommand(inputData);
329 LttngAgentResponse response = disableAppCtxCmd.execute(logAgent);
301a3ddb 330 responseData = response.getBytes();
6e1fdc3a 331 log("Received disable app-context command");
d60dfbe4
AM
332 break;
333 }
334 default:
335 {
301a3ddb
AM
336 /* Unknown command, send empty reply */
337 responseData = new byte[4];
338 ByteBuffer buf = ByteBuffer.wrap(responseData);
d60dfbe4 339 buf.order(ByteOrder.BIG_ENDIAN);
6e1fdc3a 340 log("Received unknown command, ignoring");
d60dfbe4
AM
341 break;
342 }
43e5396b
DG
343 }
344
301a3ddb 345 /* Send response to the session daemon. */
6e1fdc3a 346 log("Sending response");
301a3ddb 347 this.outToSessiond.write(responseData, 0, responseData.length);
43e5396b
DG
348 this.outToSessiond.flush();
349 }
350 }
351
f1fa0535 352 /**
301a3ddb
AM
353 * Receive header data from the session daemon using the LTTng command
354 * static buffer of the right size.
f1fa0535 355 */
301a3ddb
AM
356 private SessiondCommandHeader recvHeader() throws IOException {
357 byte data[] = new byte[SessiondCommandHeader.HEADER_SIZE];
f1fa0535 358
301a3ddb
AM
359 int readLen = this.inFromSessiond.read(data, 0, data.length);
360 if (readLen != data.length) {
361 throw new IOException();
f1fa0535 362 }
301a3ddb 363 return new SessiondCommandHeader(data);
f1fa0535
DG
364 }
365
301a3ddb
AM
366 /**
367 * Receive payload from the session daemon. This MUST be done after a
368 * recvHeader() so the header value of a command are known.
369 *
370 * The caller SHOULD use isPayload() before which returns true if a payload
371 * is expected after the header.
372 */
373 private byte[] recvPayload(SessiondCommandHeader headerCmd) throws IOException {
374 byte payload[] = new byte[(int) headerCmd.getDataSize()];
f1fa0535 375
301a3ddb
AM
376 /* Failsafe check so we don't waste our time reading 0 bytes. */
377 if (payload.length == 0) {
378 return null;
f1fa0535
DG
379 }
380
1e111005
AM
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");
384 }
301a3ddb 385 return payload;
43e5396b
DG
386 }
387
6e1fdc3a
AM
388 /**
389 * Wrapper for this class's logging, adds the connection's characteristics
390 * to help differentiate between multiple TCP clients.
391 */
392 private void log(String message) {
393 LttngUstAgentLogger.log(getClass(),
394 "(root=" + isRoot + ", domain=" + domainValue + ") " + message);
395 }
43e5396b 396}
This page took 0.045457 seconds and 4 git commands to generate.