d8788d320c416a9b9538bed603f7a9b45a8ca4cf
[lttng-ust.git] /
1 /*
2 * Copyright (C) 2013 - David Goulet <dgoulet@efficios.com>
3 *
4 * This library is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU Lesser General Public License, version 2.1 only,
6 * as published by the Free Software Foundation.
7 *
8 * This library is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
11 * for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this library; if not, write to the Free Software Foundation,
15 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16 */
17
18 package org.lttng.ust.agent.client;
19
20 import java.io.BufferedReader;
21 import java.io.DataInputStream;
22 import java.io.DataOutputStream;
23 import java.io.FileNotFoundException;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.lang.management.ManagementFactory;
27 import java.net.Socket;
28 import java.net.UnknownHostException;
29 import java.nio.ByteBuffer;
30 import java.nio.ByteOrder;
31 import java.util.concurrent.CountDownLatch;
32 import java.util.concurrent.TimeUnit;
33
34 /**
35 * Client for agents to connect to a local session daemon, using a TCP socket.
36 *
37 * @author David Goulet
38 */
39 public class LttngTcpSessiondClient implements Runnable {
40
41 private static final String SESSION_HOST = "127.0.0.1";
42 private static final String ROOT_PORT_FILE = "/var/run/lttng/agent.port";
43 private static final String USER_PORT_FILE = "/.lttng/agent.port";
44
45 private static int protocolMajorVersion = 1;
46 private static int protocolMinorVersion = 0;
47
48 /** Command header from the session deamon. */
49 private final CountDownLatch registrationLatch = new CountDownLatch(1);
50
51 private Socket sessiondSock;
52 private volatile boolean quit = false;
53
54 private DataInputStream inFromSessiond;
55 private DataOutputStream outToSessiond;
56
57 private final ILttngTcpClientListener logAgent;
58 private final int domainValue;
59 private final boolean isRoot;
60
61 /**
62 * Constructor
63 *
64 * @param logAgent
65 * The listener this client will operate on, typically an LTTng
66 * agent.
67 * @param domainValue
68 * The integer to send to the session daemon representing the
69 * tracing domain to handle.
70 * @param isRoot
71 * True if this client should connect to the root session daemon,
72 * false if it should connect to the user one.
73 */
74 public LttngTcpSessiondClient(ILttngTcpClientListener logAgent, int domainValue, boolean isRoot) {
75 this.logAgent = logAgent;
76 this.domainValue = domainValue;
77 this.isRoot = isRoot;
78 }
79
80 /**
81 * Wait until this client has successfully established a connection to its
82 * target session daemon.
83 *
84 * @param seconds
85 * A timeout in seconds after which this method will return
86 * anyway.
87 * @return True if the the client actually established the connection, false
88 * if we returned because the timeout has elapsed or the thread was
89 * interrupted.
90 */
91 public boolean waitForConnection(int seconds) {
92 try {
93 return registrationLatch.await(seconds, TimeUnit.SECONDS);
94 } catch (InterruptedException e) {
95 return false;
96 }
97 }
98
99 @Override
100 public void run() {
101 for (;;) {
102 if (this.quit) {
103 break;
104 }
105
106 try {
107
108 /*
109 * Connect to the session daemon before anything else.
110 */
111 connectToSessiond();
112
113 /*
114 * Register to the session daemon as the Java component of the
115 * UST application.
116 */
117 registerToSessiond();
118
119 /*
120 * Block on socket receive and wait for command from the
121 * session daemon. This will return if and only if there is a
122 * fatal error or the socket closes.
123 */
124 handleSessiondCmd();
125 } catch (UnknownHostException uhe) {
126 uhe.printStackTrace();
127 } catch (IOException ioe) {
128 try {
129 Thread.sleep(3000);
130 } catch (InterruptedException e) {
131 e.printStackTrace();
132 }
133 }
134 }
135 }
136
137 /**
138 * Dispose this client and close any socket connection it may hold.
139 */
140 public void close() {
141 this.quit = true;
142
143 try {
144 if (this.sessiondSock != null) {
145 this.sessiondSock.close();
146 }
147 } catch (IOException e) {
148 e.printStackTrace();
149 }
150 }
151
152 private void connectToSessiond() throws IOException {
153 int port;
154
155 if (this.isRoot) {
156 port = getPortFromFile(ROOT_PORT_FILE);
157 if (port == 0) {
158 /* No session daemon available. Stop and retry later. */
159 throw new IOException();
160 }
161 } else {
162 port = getPortFromFile(getHomePath() + USER_PORT_FILE);
163 if (port == 0) {
164 /* No session daemon available. Stop and retry later. */
165 throw new IOException();
166 }
167 }
168
169 this.sessiondSock = new Socket(SESSION_HOST, port);
170 this.inFromSessiond = new DataInputStream(sessiondSock.getInputStream());
171 this.outToSessiond = new DataOutputStream(sessiondSock.getOutputStream());
172 }
173
174 private static String getHomePath() {
175 return System.getProperty("user.home");
176 }
177
178 /**
179 * Read port number from file created by the session daemon.
180 *
181 * @return port value if found else 0.
182 */
183 private static int getPortFromFile(String path) throws IOException {
184 int port;
185 BufferedReader br = null;
186
187 try {
188 br = new BufferedReader(new FileReader(path));
189 String line = br.readLine();
190 port = Integer.parseInt(line, 10);
191 if (port < 0 || port > 65535) {
192 /* Invalid value. Ignore. */
193 port = 0;
194 }
195 } catch (FileNotFoundException e) {
196 /* No port available. */
197 port = 0;
198 } finally {
199 if (br != null) {
200 br.close();
201 }
202 }
203
204 return port;
205 }
206
207 private void registerToSessiond() throws IOException {
208 byte data[] = new byte[16];
209 ByteBuffer buf = ByteBuffer.wrap(data);
210 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
211
212 buf.putInt(domainValue);
213 buf.putInt(Integer.parseInt(pid));
214 buf.putInt(protocolMajorVersion);
215 buf.putInt(protocolMinorVersion);
216 this.outToSessiond.write(data, 0, data.length);
217 this.outToSessiond.flush();
218 }
219
220 /**
221 * Handle session command from the session daemon.
222 */
223 private void handleSessiondCmd() throws IOException {
224 /* Data read from the socket */
225 byte inputData[] = null;
226 /* Reply data written to the socket, sent to the sessiond */
227 byte responseData[] = null;
228
229 while (true) {
230 /* Get header from session daemon. */
231 SessiondCommandHeader cmdHeader = recvHeader();
232
233 if (cmdHeader.getDataSize() > 0) {
234 inputData = recvPayload(cmdHeader);
235 }
236
237 switch (cmdHeader.getCommandType()) {
238 case CMD_REG_DONE:
239 {
240 /*
241 * Countdown the registration latch, meaning registration is
242 * done and we can proceed to continue tracing.
243 */
244 registrationLatch.countDown();
245 /*
246 * We don't send any reply to the registration done command.
247 * This just marks the end of the initial session setup.
248 */
249 continue;
250 }
251 case CMD_LIST:
252 {
253 ISessiondCommand listLoggerCmd = new SessiondListLoggersCommand();
254 LttngAgentResponse response = listLoggerCmd.execute(logAgent);
255 responseData = response.getBytes();
256 break;
257 }
258 case CMD_ENABLE:
259 {
260 if (inputData == null) {
261 /* Invalid command */
262 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
263 break;
264 }
265 ISessiondCommand enableCmd = new SessiondEnableEventCommand(inputData);
266 LttngAgentResponse response = enableCmd.execute(logAgent);
267 responseData = response.getBytes();
268 break;
269 }
270 case CMD_DISABLE:
271 {
272 if (inputData == null) {
273 /* Invalid command */
274 responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
275 break;
276 }
277 ISessiondCommand disableCmd = new SessiondDisableEventCommand(inputData);
278 LttngAgentResponse response = disableCmd.execute(logAgent);
279 responseData = response.getBytes();
280 break;
281 }
282 default:
283 {
284 /* Unknown command, send empty reply */
285 responseData = new byte[4];
286 ByteBuffer buf = ByteBuffer.wrap(responseData);
287 buf.order(ByteOrder.BIG_ENDIAN);
288 break;
289 }
290 }
291
292 /* Send response to the session daemon. */
293 this.outToSessiond.write(responseData, 0, responseData.length);
294 this.outToSessiond.flush();
295 }
296 }
297
298 /**
299 * Receive header data from the session daemon using the LTTng command
300 * static buffer of the right size.
301 */
302 private SessiondCommandHeader recvHeader() throws IOException {
303 byte data[] = new byte[SessiondCommandHeader.HEADER_SIZE];
304
305 int readLen = this.inFromSessiond.read(data, 0, data.length);
306 if (readLen != data.length) {
307 throw new IOException();
308 }
309 return new SessiondCommandHeader(data);
310 }
311
312 /**
313 * Receive payload from the session daemon. This MUST be done after a
314 * recvHeader() so the header value of a command are known.
315 *
316 * The caller SHOULD use isPayload() before which returns true if a payload
317 * is expected after the header.
318 */
319 private byte[] recvPayload(SessiondCommandHeader headerCmd) throws IOException {
320 byte payload[] = new byte[(int) headerCmd.getDataSize()];
321
322 /* Failsafe check so we don't waste our time reading 0 bytes. */
323 if (payload.length == 0) {
324 return null;
325 }
326
327 this.inFromSessiond.read(payload, 0, payload.length);
328 return payload;
329 }
330
331 }
This page took 0.03384 seconds and 3 git commands to generate.