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
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;
f1fa0535 24import java.io.FileNotFoundException;
bc7de6d9
AM
25import java.io.FileReader;
26import java.io.IOException;
43e5396b 27import java.lang.management.ManagementFactory;
bc7de6d9
AM
28import java.net.Socket;
29import java.net.UnknownHostException;
30import java.nio.ByteBuffer;
31import java.nio.ByteOrder;
d60dfbe4
AM
32import java.util.concurrent.CountDownLatch;
33import java.util.concurrent.TimeUnit;
43e5396b 34
d60dfbe4
AM
35/**
36 * Client for agents to connect to a local session daemon, using a TCP socket.
37 *
38 * @author David Goulet
39 */
40public class LttngTcpSessiondClient implements Runnable {
43e5396b 41
08284556
AM
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
191f4058
AM
46 private static final int PROTOCOL_MAJOR_VERSION = 2;
47 private static final int PROTOCOL_MINOR_VERSION = 0;
08284556 48
d60dfbe4 49 /** Command header from the session deamon. */
d60dfbe4 50 private final CountDownLatch registrationLatch = new CountDownLatch(1);
43e5396b 51
43e5396b 52 private Socket sessiondSock;
501f6777 53 private volatile boolean quit = false;
43e5396b
DG
54
55 private DataInputStream inFromSessiond;
56 private DataOutputStream outToSessiond;
57
3165c2f5
AM
58 private final ILttngTcpClientListener logAgent;
59 private final int domainValue;
d60dfbe4 60 private final boolean isRoot;
501f6777 61
d60dfbe4
AM
62 /**
63 * Constructor
64 *
65 * @param logAgent
3165c2f5
AM
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.
d60dfbe4
AM
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 */
3165c2f5 75 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent, int domainValue, boolean isRoot) {
d60dfbe4 76 this.logAgent = logAgent;
3165c2f5 77 this.domainValue = domainValue;
d60dfbe4 78 this.isRoot = isRoot;
43e5396b
DG
79 }
80
d60dfbe4
AM
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.
f1fa0535 91 */
d60dfbe4
AM
92 public boolean waitForConnection(int seconds) {
93 try {
94 return registrationLatch.await(seconds, TimeUnit.SECONDS);
95 } catch (InterruptedException e) {
96 return false;
f1fa0535
DG
97 }
98 }
99
501f6777
CB
100 @Override
101 public void run() {
43e5396b
DG
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();
43e5396b 119
43e5396b
DG
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) {
d60dfbe4 127 uhe.printStackTrace();
43e5396b 128 } catch (IOException ioe) {
501f6777
CB
129 try {
130 Thread.sleep(3000);
131 } catch (InterruptedException e) {
132 e.printStackTrace();
133 }
43e5396b
DG
134 }
135 }
136 }
137
d60dfbe4
AM
138 /**
139 * Dispose this client and close any socket connection it may hold.
140 */
141 public void close() {
43e5396b 142 this.quit = true;
43e5396b
DG
143
144 try {
145 if (this.sessiondSock != null) {
146 this.sessiondSock.close();
147 }
d60dfbe4 148 } catch (IOException e) {
43e5396b
DG
149 e.printStackTrace();
150 }
151 }
152
301a3ddb
AM
153 private void connectToSessiond() throws IOException {
154 int port;
43e5396b 155
301a3ddb
AM
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 }
43e5396b 168 }
301a3ddb
AM
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");
43e5396b
DG
177 }
178
d60dfbe4 179 /**
301a3ddb 180 * Read port number from file created by the session daemon.
43e5396b 181 *
301a3ddb 182 * @return port value if found else 0.
43e5396b 183 */
301a3ddb
AM
184 private static int getPortFromFile(String path) throws IOException {
185 int port;
186 BufferedReader br = null;
43e5396b 187
301a3ddb
AM
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 }
43e5396b
DG
203 }
204
301a3ddb
AM
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
3165c2f5 213 buf.putInt(domainValue);
301a3ddb 214 buf.putInt(Integer.parseInt(pid));
191f4058
AM
215 buf.putInt(PROTOCOL_MAJOR_VERSION);
216 buf.putInt(PROTOCOL_MINOR_VERSION);
301a3ddb
AM
217 this.outToSessiond.write(data, 0, data.length);
218 this.outToSessiond.flush();
43e5396b
DG
219 }
220
d60dfbe4 221 /**
43e5396b
DG
222 * Handle session command from the session daemon.
223 */
d60dfbe4 224 private void handleSessiondCmd() throws IOException {
301a3ddb
AM
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;
43e5396b
DG
229
230 while (true) {
231 /* Get header from session daemon. */
301a3ddb 232 SessiondCommandHeader cmdHeader = recvHeader();
43e5396b 233
301a3ddb
AM
234 if (cmdHeader.getDataSize() > 0) {
235 inputData = recvPayload(cmdHeader);
43e5396b
DG
236 }
237
301a3ddb 238 switch (cmdHeader.getCommandType()) {
d60dfbe4
AM
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 {
1d193914 254 SessiondCommand listLoggerCmd = new SessiondListLoggersCommand();
93253569 255 LttngAgentResponse response = listLoggerCmd.execute(logAgent);
301a3ddb 256 responseData = response.getBytes();
d60dfbe4
AM
257 break;
258 }
8ab5c06b 259 case CMD_EVENT_ENABLE:
d60dfbe4 260 {
301a3ddb
AM
261 if (inputData == null) {
262 /* Invalid command */
93253569 263 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
43e5396b
DG
264 break;
265 }
8ab5c06b
AM
266 SessiondCommand enableEventCmd = new SessiondEnableEventCommand(inputData);
267 LttngAgentResponse response = enableEventCmd.execute(logAgent);
301a3ddb 268 responseData = response.getBytes();
d60dfbe4
AM
269 break;
270 }
8ab5c06b 271 case CMD_EVENT_DISABLE:
d60dfbe4 272 {
301a3ddb
AM
273 if (inputData == null) {
274 /* Invalid command */
93253569 275 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
43e5396b
DG
276 break;
277 }
8ab5c06b
AM
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);
301a3ddb 304 responseData = response.getBytes();
d60dfbe4
AM
305 break;
306 }
307 default:
308 {
301a3ddb
AM
309 /* Unknown command, send empty reply */
310 responseData = new byte[4];
311 ByteBuffer buf = ByteBuffer.wrap(responseData);
d60dfbe4
AM
312 buf.order(ByteOrder.BIG_ENDIAN);
313 break;
314 }
43e5396b
DG
315 }
316
301a3ddb
AM
317 /* Send response to the session daemon. */
318 this.outToSessiond.write(responseData, 0, responseData.length);
43e5396b
DG
319 this.outToSessiond.flush();
320 }
321 }
322
f1fa0535 323 /**
301a3ddb
AM
324 * Receive header data from the session daemon using the LTTng command
325 * static buffer of the right size.
f1fa0535 326 */
301a3ddb
AM
327 private SessiondCommandHeader recvHeader() throws IOException {
328 byte data[] = new byte[SessiondCommandHeader.HEADER_SIZE];
f1fa0535 329
301a3ddb
AM
330 int readLen = this.inFromSessiond.read(data, 0, data.length);
331 if (readLen != data.length) {
332 throw new IOException();
f1fa0535 333 }
301a3ddb 334 return new SessiondCommandHeader(data);
f1fa0535
DG
335 }
336
301a3ddb
AM
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()];
f1fa0535 346
301a3ddb
AM
347 /* Failsafe check so we don't waste our time reading 0 bytes. */
348 if (payload.length == 0) {
349 return null;
f1fa0535
DG
350 }
351
301a3ddb
AM
352 this.inFromSessiond.read(payload, 0, payload.length);
353 return payload;
43e5396b
DG
354 }
355
43e5396b 356}
This page took 0.041678 seconds and 4 git commands to generate.