Add initial support for the multiple LTTNG_UST_APP_PATHs
[lttng-ust.git] / src / lib / lttng-ust-java-agent / java / lttng-ust-agent-common / org / lttng / ust / agent / client / LttngTcpSessiondClient.java
1 /*
2 * SPDX-License-Identifier: LGPL-2.1-only
3 *
4 * Copyright (C) 2015-2016 EfficiOS Inc.
5 * Copyright (C) 2015-2016 Alexandre Montplaisir <alexmonthy@efficios.com>
6 * Copyright (C) 2013 David Goulet <dgoulet@efficios.com>
7 */
8
9 package org.lttng.ust.agent.client;
10
11 import java.io.BufferedReader;
12 import java.io.DataInputStream;
13 import java.io.DataOutputStream;
14 import java.io.FileInputStream;
15 import java.io.FileNotFoundException;
16 import java.io.IOException;
17 import java.io.InputStreamReader;
18 import java.lang.management.ManagementFactory;
19 import java.net.Socket;
20 import java.net.UnknownHostException;
21 import java.nio.ByteBuffer;
22 import java.nio.ByteOrder;
23 import java.nio.charset.Charset;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.TimeUnit;
26
27 import org.lttng.ust.agent.utils.LttngUstAgentLogger;
28
29 /**
30 * Client for agents to connect to a local session daemon, using a TCP socket.
31 *
32 * @author David Goulet
33 */
34 public class LttngTcpSessiondClient implements Runnable {
35
36 private static final String SESSION_HOST = "127.0.0.1";
37 private static final String ROOT_PORT_FILE = "/var/run/lttng/agent.port";
38 private static final String USER_PORT_FILE = "/.lttng/agent.port";
39 private static final String APP_PATH_PORT_FILE = "/agent.port";
40 private static final Charset PORT_FILE_ENCODING = Charset.forName("UTF-8");
41
42 private static final int PROTOCOL_MAJOR_VERSION = 2;
43 private static final int PROTOCOL_MINOR_VERSION = 0;
44
45 /** Command header from the session daemon. */
46 private final CountDownLatch registrationLatch = new CountDownLatch(1);
47
48 private Socket sessiondSock;
49 private volatile boolean quit = false;
50
51 private DataInputStream inFromSessiond;
52 private DataOutputStream outToSessiond;
53
54 private final ILttngTcpClientListener logAgent;
55 private final int domainValue;
56 private final boolean isRoot;
57
58 /**
59 * Constructor
60 *
61 * @param logAgent
62 * The listener this client will operate on, typically an LTTng
63 * agent.
64 * @param domainValue
65 * The integer to send to the session daemon representing the
66 * tracing domain to handle.
67 * @param isRoot
68 * True if this client should connect to the root session daemon,
69 * false if it should connect to the user one.
70 */
71 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent, int domainValue, boolean isRoot) {
72 this.logAgent = logAgent;
73 this.domainValue = domainValue;
74 this.isRoot = isRoot;
75 }
76
77 /**
78 * Wait until this client has successfully established a connection to its
79 * target session daemon.
80 *
81 * @param seconds
82 * A timeout in seconds after which this method will return
83 * anyway.
84 * @return True if the the client actually established the connection, false
85 * if we returned because the timeout has elapsed or the thread was
86 * interrupted.
87 */
88 public boolean waitForConnection(int seconds) {
89 try {
90 return registrationLatch.await(seconds, TimeUnit.SECONDS);
91 } catch (InterruptedException e) {
92 return false;
93 }
94 }
95
96 @Override
97 public void run() {
98 for (;;) {
99 if (this.quit) {
100 break;
101 }
102
103 try {
104
105 /*
106 * Connect to the session daemon before anything else.
107 */
108 log("Connecting to sessiond");
109 connectToSessiond();
110
111 /*
112 * Register to the session daemon as the Java component of the
113 * UST application.
114 */
115 log("Registering to sessiond");
116 registerToSessiond();
117
118 /*
119 * Block on socket receive and wait for command from the
120 * session daemon. This will return if and only if there is a
121 * fatal error or the socket closes.
122 */
123 log("Waiting on sessiond commands...");
124 handleSessiondCmd();
125 } catch (UnknownHostException uhe) {
126 uhe.printStackTrace();
127 /*
128 * Terminate agent thread.
129 */
130 close();
131 } catch (IOException ioe) {
132 /*
133 * I/O exception may have been triggered by a session daemon
134 * closing the socket. Close our own socket and
135 * retry connecting after a delay.
136 */
137 try {
138 if (this.sessiondSock != null) {
139 this.sessiondSock.close();
140 }
141 Thread.sleep(3000);
142 } catch (InterruptedException e) {
143 /*
144 * Retry immediately if sleep is interrupted.
145 */
146 } catch (IOException closeioe) {
147 closeioe.printStackTrace();
148 /*
149 * Terminate agent thread.
150 */
151 close();
152 }
153 }
154 }
155 }
156
157 /**
158 * Dispose this client and close any socket connection it may hold.
159 */
160 public void close() {
161 log("Closing client");
162 this.quit = true;
163
164 try {
165 if (this.sessiondSock != null) {
166 this.sessiondSock.close();
167 }
168 } catch (IOException e) {
169 e.printStackTrace();
170 }
171 }
172
173 private void connectToSessiond() throws IOException {
174 int portToUse;
175
176 /*
177 * The environment variable LTTNG_UST_APP_PATH disables
178 * connection to per-user and root session daemons.
179 */
180 String lttngUstAppPath = getUstAppPath();
181
182 if (lttngUstAppPath != null) {
183 portToUse = getPortFromFile(lttngUstAppPath + APP_PATH_PORT_FILE);
184 } else {
185 int rootPort = getPortFromFile(ROOT_PORT_FILE);
186 int userPort = getPortFromFile(getHomePath() + USER_PORT_FILE);
187
188 /*
189 * Check for the edge case of both files existing but pointing to the
190 * same port. In this case, let the root client handle it.
191 */
192 if ((rootPort != 0) && (rootPort == userPort) && (!isRoot)) {
193 log("User and root config files both point to port " + rootPort +
194 ". Letting the root client handle it.");
195 throw new IOException();
196 }
197
198 portToUse = (isRoot ? rootPort : userPort);
199 }
200
201 if (portToUse == 0) {
202 /* No session daemon available. Stop and retry later. */
203 throw new IOException();
204 }
205
206 this.sessiondSock = new Socket(SESSION_HOST, portToUse);
207 this.inFromSessiond = new DataInputStream(sessiondSock.getInputStream());
208 this.outToSessiond = new DataOutputStream(sessiondSock.getOutputStream());
209 }
210
211 private String getUstAppPath() {
212 String ustAppPath = System.getenv("LTTNG_UST_APP_PATH");
213 if (ustAppPath != null) {
214 String[] paths = ustAppPath.split(":");
215 if (paths.length > 1) {
216 log("':' separator in LTTNG_UST_APP_PATH, only the first path will be used");
217 }
218 return paths[0];
219 }
220 return ustAppPath;
221 }
222
223 private static String getHomePath() {
224 /*
225 * The environment variable LTTNG_HOME overrides HOME if
226 * set.
227 */
228 String lttngHomePath = System.getenv("LTTNG_HOME");
229 if (lttngHomePath != null) {
230 return lttngHomePath;
231 }
232 return System.getProperty("user.home");
233 }
234
235 /**
236 * Read port number from file created by the session daemon.
237 *
238 * @return port value if found else 0.
239 */
240 private static int getPortFromFile(String path) throws IOException {
241 BufferedReader br = null;
242
243 try {
244 br = new BufferedReader(new InputStreamReader(new FileInputStream(path), PORT_FILE_ENCODING));
245 String line = br.readLine();
246 if (line == null) {
247 /* File exists but is empty. */
248 return 0;
249 }
250
251 int port = Integer.parseInt(line, 10);
252 if (port < 0 || port > 65535) {
253 /* Invalid value. Ignore. */
254 port = 0;
255 }
256 return port;
257
258 } catch (NumberFormatException e) {
259 /* File contained something that was not a number. */
260 return 0;
261 } catch (FileNotFoundException e) {
262 /* No port available. */
263 return 0;
264 } finally {
265 if (br != null) {
266 br.close();
267 }
268 }
269 }
270
271 private void registerToSessiond() throws IOException {
272 byte data[] = new byte[16];
273 ByteBuffer buf = ByteBuffer.wrap(data);
274 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
275
276 buf.putInt(domainValue);
277 buf.putInt(Integer.parseInt(pid));
278 buf.putInt(PROTOCOL_MAJOR_VERSION);
279 buf.putInt(PROTOCOL_MINOR_VERSION);
280 this.outToSessiond.write(data, 0, data.length);
281 this.outToSessiond.flush();
282 }
283
284 /**
285 * Handle session command from the session daemon.
286 */
287 private void handleSessiondCmd() throws IOException {
288 /* Data read from the socket */
289 byte inputData[] = null;
290 /* Reply data written to the socket, sent to the sessiond */
291 LttngAgentResponse response;
292
293 while (true) {
294 /* Get header from session daemon. */
295 SessiondCommandHeader cmdHeader = recvHeader();
296
297 if (cmdHeader.getDataSize() > 0) {
298 inputData = recvPayload(cmdHeader);
299 }
300
301 switch (cmdHeader.getCommandType()) {
302 case CMD_REG_DONE:
303 {
304 /*
305 * Countdown the registration latch, meaning registration is
306 * done and we can proceed to continue tracing.
307 */
308 registrationLatch.countDown();
309 /*
310 * We don't send any reply to the registration done command.
311 * This just marks the end of the initial session setup.
312 */
313 log("Registration done");
314 continue;
315 }
316 case CMD_LIST:
317 {
318 SessiondCommand listLoggerCmd = new SessiondListLoggersCommand();
319 response = listLoggerCmd.execute(logAgent);
320 log("Received list loggers command");
321 break;
322 }
323 case CMD_EVENT_ENABLE:
324 {
325 if (inputData == null) {
326 /* Invalid command */
327 response = LttngAgentResponse.FAILURE_RESPONSE;
328 break;
329 }
330 SessiondCommand enableEventCmd = new SessiondEnableEventCommand(inputData);
331 response = enableEventCmd.execute(logAgent);
332 log("Received enable event command: " + enableEventCmd.toString());
333 break;
334 }
335 case CMD_EVENT_DISABLE:
336 {
337 if (inputData == null) {
338 /* Invalid command */
339 response = LttngAgentResponse.FAILURE_RESPONSE;
340 break;
341 }
342 SessiondCommand disableEventCmd = new SessiondDisableEventCommand(inputData);
343 response = disableEventCmd.execute(logAgent);
344 log("Received disable event command: " + disableEventCmd.toString());
345 break;
346 }
347 case CMD_APP_CTX_ENABLE:
348 {
349 if (inputData == null) {
350 /* This commands expects a payload, invalid command */
351 response = LttngAgentResponse.FAILURE_RESPONSE;
352 break;
353 }
354 SessiondCommand enableAppCtxCmd = new SessiondEnableAppContextCommand(inputData);
355 response = enableAppCtxCmd.execute(logAgent);
356 log("Received enable app-context command");
357 break;
358 }
359 case CMD_APP_CTX_DISABLE:
360 {
361 if (inputData == null) {
362 /* This commands expects a payload, invalid command */
363 response = LttngAgentResponse.FAILURE_RESPONSE;
364 break;
365 }
366 SessiondCommand disableAppCtxCmd = new SessiondDisableAppContextCommand(inputData);
367 response = disableAppCtxCmd.execute(logAgent);
368 log("Received disable app-context command");
369 break;
370 }
371 default:
372 {
373 /* Unknown command, send empty reply */
374 response = null;
375 log("Received unknown command, ignoring");
376 break;
377 }
378 }
379
380 /* Send response to the session daemon. */
381 byte[] responseData;
382 if (response == null) {
383 responseData = new byte[4];
384 ByteBuffer buf = ByteBuffer.wrap(responseData);
385 buf.order(ByteOrder.BIG_ENDIAN);
386 } else {
387 log("Sending response: " + response.toString());
388 responseData = response.getBytes();
389 }
390 this.outToSessiond.write(responseData, 0, responseData.length);
391 this.outToSessiond.flush();
392 }
393 }
394
395 /**
396 * Receive header data from the session daemon using the LTTng command
397 * static buffer of the right size.
398 */
399 private SessiondCommandHeader recvHeader() throws IOException {
400 byte data[] = new byte[SessiondCommandHeader.HEADER_SIZE];
401 int bytesLeft = data.length;
402 int bytesOffset = 0;
403
404 while (bytesLeft > 0) {
405 int bytesRead = this.inFromSessiond.read(data, bytesOffset, bytesLeft);
406
407 if (bytesRead < 0) {
408 throw new IOException();
409 }
410 bytesLeft -= bytesRead;
411 bytesOffset += bytesRead;
412 }
413 return new SessiondCommandHeader(data);
414 }
415
416 /**
417 * Receive payload from the session daemon. This MUST be done after a
418 * recvHeader() so the header value of a command are known.
419 *
420 * The caller SHOULD use isPayload() before which returns true if a payload
421 * is expected after the header.
422 */
423 private byte[] recvPayload(SessiondCommandHeader headerCmd) throws IOException {
424 byte payload[] = new byte[(int) headerCmd.getDataSize()];
425 int bytesLeft = payload.length;
426 int bytesOffset = 0;
427
428 /* Failsafe check so we don't waste our time reading 0 bytes. */
429 if (bytesLeft == 0) {
430 return null;
431 }
432
433 while (bytesLeft > 0) {
434 int bytesRead = inFromSessiond.read(payload, bytesOffset, bytesLeft);
435
436 if (bytesRead < 0) {
437 throw new IOException();
438 }
439 bytesLeft -= bytesRead;
440 bytesOffset += bytesRead;
441 }
442 return payload;
443 }
444
445 /**
446 * Wrapper for this class's logging, adds the connection's characteristics
447 * to help differentiate between multiple TCP clients.
448 */
449 private void log(String message) {
450 LttngUstAgentLogger.log(getClass(),
451 "(root=" + isRoot + ", domain=" + domainValue + ") " + message);
452 }
453 }
This page took 0.0393 seconds and 4 git commands to generate.