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