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