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