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