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
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;
9f84d546 24import java.io.FileInputStream;
f1fa0535 25import java.io.FileNotFoundException;
bc7de6d9 26import java.io.IOException;
9f84d546 27import java.io.InputStreamReader;
43e5396b 28import java.lang.management.ManagementFactory;
bc7de6d9
AM
29import java.net.Socket;
30import java.net.UnknownHostException;
31import java.nio.ByteBuffer;
32import java.nio.ByteOrder;
9f84d546 33import java.nio.charset.Charset;
d60dfbe4
AM
34import java.util.concurrent.CountDownLatch;
35import java.util.concurrent.TimeUnit;
43e5396b 36
cbe2ebd6
AM
37import org.lttng.ust.agent.utils.LttngUstAgentLogger;
38
d60dfbe4
AM
39/**
40 * Client for agents to connect to a local session daemon, using a TCP socket.
41 *
42 * @author David Goulet
43 */
44public class LttngTcpSessiondClient implements Runnable {
43e5396b 45
08284556
AM
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";
9f84d546 49 private static final Charset PORT_FILE_ENCODING = Charset.forName("UTF-8");
08284556 50
191f4058
AM
51 private static final int PROTOCOL_MAJOR_VERSION = 2;
52 private static final int PROTOCOL_MINOR_VERSION = 0;
08284556 53
d60dfbe4 54 /** Command header from the session deamon. */
d60dfbe4 55 private final CountDownLatch registrationLatch = new CountDownLatch(1);
43e5396b 56
43e5396b 57 private Socket sessiondSock;
501f6777 58 private volatile boolean quit = false;
43e5396b
DG
59
60 private DataInputStream inFromSessiond;
61 private DataOutputStream outToSessiond;
62
3165c2f5
AM
63 private final ILttngTcpClientListener logAgent;
64 private final int domainValue;
d60dfbe4 65 private final boolean isRoot;
501f6777 66
d60dfbe4
AM
67 /**
68 * Constructor
69 *
70 * @param logAgent
3165c2f5
AM
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.
d60dfbe4
AM
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 */
3165c2f5 80 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent, int domainValue, boolean isRoot) {
d60dfbe4 81 this.logAgent = logAgent;
3165c2f5 82 this.domainValue = domainValue;
d60dfbe4 83 this.isRoot = isRoot;
43e5396b
DG
84 }
85
d60dfbe4
AM
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.
f1fa0535 96 */
d60dfbe4
AM
97 public boolean waitForConnection(int seconds) {
98 try {
99 return registrationLatch.await(seconds, TimeUnit.SECONDS);
100 } catch (InterruptedException e) {
101 return false;
f1fa0535
DG
102 }
103 }
104
501f6777
CB
105 @Override
106 public void run() {
43e5396b
DG
107 for (;;) {
108 if (this.quit) {
109 break;
110 }
111
112 try {
113
114 /*
115 * Connect to the session daemon before anything else.
116 */
6e1fdc3a 117 log("Connecting to sessiond");
43e5396b
DG
118 connectToSessiond();
119
120 /*
121 * Register to the session daemon as the Java component of the
122 * UST application.
123 */
6e1fdc3a 124 log("Registering to sessiond");
43e5396b 125 registerToSessiond();
43e5396b 126
43e5396b
DG
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 */
6e1fdc3a 132 log("Waiting on sessiond commands...");
43e5396b
DG
133 handleSessiondCmd();
134 } catch (UnknownHostException uhe) {
d60dfbe4 135 uhe.printStackTrace();
35cbacdb
MD
136 /*
137 * Terminate agent thread.
138 */
139 close();
43e5396b 140 } catch (IOException ioe) {
35cbacdb
MD
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 */
501f6777 146 try {
35cbacdb
MD
147 if (this.sessiondSock != null) {
148 this.sessiondSock.close();
149 }
501f6777
CB
150 Thread.sleep(3000);
151 } catch (InterruptedException e) {
35cbacdb
MD
152 /*
153 * Retry immediately if sleep is interrupted.
154 */
155 } catch (IOException closeioe) {
156 closeioe.printStackTrace();
157 /*
158 * Terminate agent thread.
159 */
160 close();
501f6777 161 }
43e5396b
DG
162 }
163 }
164 }
165
d60dfbe4
AM
166 /**
167 * Dispose this client and close any socket connection it may hold.
168 */
169 public void close() {
6e1fdc3a 170 log("Closing client");
43e5396b 171 this.quit = true;
43e5396b
DG
172
173 try {
174 if (this.sessiondSock != null) {
175 this.sessiondSock.close();
176 }
d60dfbe4 177 } catch (IOException e) {
43e5396b
DG
178 e.printStackTrace();
179 }
180 }
181
301a3ddb 182 private void connectToSessiond() throws IOException {
e0c010a9
AM
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 }
43e5396b 195
e0c010a9
AM
196 int portToUse = (isRoot ? rootPort : userPort);
197
198 if (portToUse == 0) {
199 /* No session daemon available. Stop and retry later. */
200 throw new IOException();
43e5396b 201 }
301a3ddb 202
e0c010a9 203 this.sessiondSock = new Socket(SESSION_HOST, portToUse);
301a3ddb
AM
204 this.inFromSessiond = new DataInputStream(sessiondSock.getInputStream());
205 this.outToSessiond = new DataOutputStream(sessiondSock.getOutputStream());
206 }
207
208 private static String getHomePath() {
59e3be47
MD
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;
43e5396b
DG
219 }
220
d60dfbe4 221 /**
301a3ddb 222 * Read port number from file created by the session daemon.
43e5396b 223 *
301a3ddb 224 * @return port value if found else 0.
43e5396b 225 */
301a3ddb 226 private static int getPortFromFile(String path) throws IOException {
301a3ddb 227 BufferedReader br = null;
43e5396b 228
301a3ddb 229 try {
9f84d546 230 br = new BufferedReader(new InputStreamReader(new FileInputStream(path), PORT_FILE_ENCODING));
301a3ddb 231 String line = br.readLine();
8d8c99c9
AM
232 if (line == null) {
233 /* File exists but is empty. */
234 return 0;
235 }
236
237 int port = Integer.parseInt(line, 10);
301a3ddb
AM
238 if (port < 0 || port > 65535) {
239 /* Invalid value. Ignore. */
240 port = 0;
241 }
8d8c99c9
AM
242 return port;
243
244 } catch (NumberFormatException e) {
245 /* File contained something that was not a number. */
246 return 0;
301a3ddb
AM
247 } catch (FileNotFoundException e) {
248 /* No port available. */
8d8c99c9 249 return 0;
301a3ddb
AM
250 } finally {
251 if (br != null) {
252 br.close();
253 }
43e5396b 254 }
301a3ddb
AM
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
3165c2f5 262 buf.putInt(domainValue);
301a3ddb 263 buf.putInt(Integer.parseInt(pid));
191f4058
AM
264 buf.putInt(PROTOCOL_MAJOR_VERSION);
265 buf.putInt(PROTOCOL_MINOR_VERSION);
301a3ddb
AM
266 this.outToSessiond.write(data, 0, data.length);
267 this.outToSessiond.flush();
43e5396b
DG
268 }
269
d60dfbe4 270 /**
43e5396b
DG
271 * Handle session command from the session daemon.
272 */
d60dfbe4 273 private void handleSessiondCmd() throws IOException {
301a3ddb
AM
274 /* Data read from the socket */
275 byte inputData[] = null;
276 /* Reply data written to the socket, sent to the sessiond */
f35c6aa0 277 LttngAgentResponse response;
43e5396b
DG
278
279 while (true) {
280 /* Get header from session daemon. */
301a3ddb 281 SessiondCommandHeader cmdHeader = recvHeader();
43e5396b 282
301a3ddb
AM
283 if (cmdHeader.getDataSize() > 0) {
284 inputData = recvPayload(cmdHeader);
43e5396b
DG
285 }
286
301a3ddb 287 switch (cmdHeader.getCommandType()) {
d60dfbe4
AM
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 */
6e1fdc3a 299 log("Registration done");
d60dfbe4
AM
300 continue;
301 }
302 case CMD_LIST:
303 {
1d193914 304 SessiondCommand listLoggerCmd = new SessiondListLoggersCommand();
f35c6aa0 305 response = listLoggerCmd.execute(logAgent);
6e1fdc3a 306 log("Received list loggers command");
d60dfbe4
AM
307 break;
308 }
8ab5c06b 309 case CMD_EVENT_ENABLE:
d60dfbe4 310 {
301a3ddb
AM
311 if (inputData == null) {
312 /* Invalid command */
f35c6aa0 313 response = LttngAgentResponse.FAILURE_RESPONSE;
43e5396b
DG
314 break;
315 }
8ab5c06b 316 SessiondCommand enableEventCmd = new SessiondEnableEventCommand(inputData);
f35c6aa0
AM
317 response = enableEventCmd.execute(logAgent);
318 log("Received enable event command: " + enableEventCmd.toString());
d60dfbe4
AM
319 break;
320 }
8ab5c06b 321 case CMD_EVENT_DISABLE:
d60dfbe4 322 {
301a3ddb
AM
323 if (inputData == null) {
324 /* Invalid command */
f35c6aa0 325 response = LttngAgentResponse.FAILURE_RESPONSE;
43e5396b
DG
326 break;
327 }
8ab5c06b 328 SessiondCommand disableEventCmd = new SessiondDisableEventCommand(inputData);
f35c6aa0
AM
329 response = disableEventCmd.execute(logAgent);
330 log("Received disable event command: " + disableEventCmd.toString());
8ab5c06b
AM
331 break;
332 }
333 case CMD_APP_CTX_ENABLE:
334 {
335 if (inputData == null) {
336 /* This commands expects a payload, invalid command */
f35c6aa0 337 response = LttngAgentResponse.FAILURE_RESPONSE;
8ab5c06b
AM
338 break;
339 }
340 SessiondCommand enableAppCtxCmd = new SessiondEnableAppContextCommand(inputData);
f35c6aa0 341 response = enableAppCtxCmd.execute(logAgent);
6e1fdc3a 342 log("Received enable app-context command");
8ab5c06b
AM
343 break;
344 }
345 case CMD_APP_CTX_DISABLE:
346 {
347 if (inputData == null) {
348 /* This commands expects a payload, invalid command */
f35c6aa0 349 response = LttngAgentResponse.FAILURE_RESPONSE;
8ab5c06b
AM
350 break;
351 }
352 SessiondCommand disableAppCtxCmd = new SessiondDisableAppContextCommand(inputData);
f35c6aa0 353 response = disableAppCtxCmd.execute(logAgent);
6e1fdc3a 354 log("Received disable app-context command");
d60dfbe4
AM
355 break;
356 }
357 default:
358 {
301a3ddb 359 /* Unknown command, send empty reply */
f35c6aa0 360 response = null;
6e1fdc3a 361 log("Received unknown command, ignoring");
d60dfbe4
AM
362 break;
363 }
43e5396b
DG
364 }
365
301a3ddb 366 /* Send response to the session daemon. */
f35c6aa0
AM
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 }
301a3ddb 376 this.outToSessiond.write(responseData, 0, responseData.length);
43e5396b
DG
377 this.outToSessiond.flush();
378 }
379 }
380
f1fa0535 381 /**
301a3ddb
AM
382 * Receive header data from the session daemon using the LTTng command
383 * static buffer of the right size.
f1fa0535 384 */
301a3ddb
AM
385 private SessiondCommandHeader recvHeader() throws IOException {
386 byte data[] = new byte[SessiondCommandHeader.HEADER_SIZE];
32974710
MD
387 int bytesLeft = data.length;
388 int bytesOffset = 0;
f1fa0535 389
dcd9a9d7 390 while (bytesLeft > 0) {
32974710
MD
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;
f1fa0535 398 }
301a3ddb 399 return new SessiondCommandHeader(data);
f1fa0535
DG
400 }
401
301a3ddb
AM
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()];
32974710
MD
411 int bytesLeft = payload.length;
412 int bytesOffset = 0;
f1fa0535 413
301a3ddb 414 /* Failsafe check so we don't waste our time reading 0 bytes. */
32974710 415 if (bytesLeft == 0) {
301a3ddb 416 return null;
f1fa0535
DG
417 }
418
dcd9a9d7 419 while (bytesLeft > 0) {
32974710
MD
420 int bytesRead = inFromSessiond.read(payload, bytesOffset, bytesLeft);
421
422 if (bytesRead < 0) {
423 throw new IOException();
424 }
425 bytesLeft -= bytesRead;
426 bytesOffset += bytesRead;
1e111005 427 }
301a3ddb 428 return payload;
43e5396b
DG
429 }
430
6e1fdc3a
AM
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 }
43e5396b 439}
This page took 0.048622 seconds and 4 git commands to generate.