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