Rename Java Agent event names to "event"
[lttng-ust.git] / liblttng-ust-java-agent / java / lttng-ust-agent-common / org / lttng / ust / agent / client / LttngTcpSessiondClient.java
CommitLineData
43e5396b
DG
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
d60dfbe4 18package org.lttng.ust.agent.client;
43e5396b 19
f1fa0535 20import java.io.BufferedReader;
43e5396b 21import java.io.DataInputStream;
bc7de6d9 22import java.io.DataOutputStream;
f1fa0535 23import java.io.FileNotFoundException;
bc7de6d9
AM
24import java.io.FileReader;
25import java.io.IOException;
43e5396b 26import java.lang.management.ManagementFactory;
bc7de6d9
AM
27import java.net.Socket;
28import java.net.UnknownHostException;
29import java.nio.ByteBuffer;
30import java.nio.ByteOrder;
d60dfbe4
AM
31import java.util.concurrent.CountDownLatch;
32import java.util.concurrent.TimeUnit;
43e5396b 33
d60dfbe4
AM
34import org.lttng.ust.agent.AbstractLttngAgent;
35
36/**
37 * Client for agents to connect to a local session daemon, using a TCP socket.
38 *
39 * @author David Goulet
40 */
41public class LttngTcpSessiondClient implements Runnable {
43e5396b 42
08284556
AM
43 private static final String SESSION_HOST = "127.0.0.1";
44 private static final String ROOT_PORT_FILE = "/var/run/lttng/agent.port";
45 private static final String USER_PORT_FILE = "/.lttng/agent.port";
46
d60dfbe4
AM
47 private static int protocolMajorVersion = 1;
48 private static int protocolMinorVersion = 0;
08284556 49
d60dfbe4
AM
50 /** Command header from the session deamon. */
51 private final SessiondHeaderCommand headerCmd = new SessiondHeaderCommand();
52 private final CountDownLatch registrationLatch = new CountDownLatch(1);
43e5396b 53
43e5396b 54 private Socket sessiondSock;
501f6777 55 private volatile boolean quit = false;
43e5396b
DG
56
57 private DataInputStream inFromSessiond;
58 private DataOutputStream outToSessiond;
59
d60dfbe4
AM
60 private final AbstractLttngAgent<?> logAgent;
61 private final boolean isRoot;
501f6777 62
f1fa0535 63
d60dfbe4
AM
64 /**
65 * Constructor
66 *
67 * @param logAgent
68 * The logging agent this client will operate on.
69 * @param isRoot
70 * True if this client should connect to the root session daemon,
71 * false if it should connect to the user one.
72 */
73 public LttngTcpSessiondClient(AbstractLttngAgent<?> logAgent, boolean isRoot) {
74 this.logAgent = logAgent;
75 this.isRoot = isRoot;
43e5396b
DG
76 }
77
d60dfbe4
AM
78 /**
79 * Wait until this client has successfully established a connection to its
80 * target session daemon.
81 *
82 * @param seconds
83 * A timeout in seconds after which this method will return
84 * anyway.
85 * @return True if the the client actually established the connection, false
86 * if we returned because the timeout has elapsed or the thread was
87 * interrupted.
f1fa0535 88 */
d60dfbe4
AM
89 public boolean waitForConnection(int seconds) {
90 try {
91 return registrationLatch.await(seconds, TimeUnit.SECONDS);
92 } catch (InterruptedException e) {
93 return false;
f1fa0535
DG
94 }
95 }
96
501f6777
CB
97 @Override
98 public void run() {
43e5396b
DG
99 for (;;) {
100 if (this.quit) {
101 break;
102 }
103
104 try {
105
106 /*
107 * Connect to the session daemon before anything else.
108 */
109 connectToSessiond();
110
111 /*
112 * Register to the session daemon as the Java component of the
113 * UST application.
114 */
115 registerToSessiond();
43e5396b 116
43e5396b
DG
117 /*
118 * Block on socket receive and wait for command from the
119 * session daemon. This will return if and only if there is a
120 * fatal error or the socket closes.
121 */
122 handleSessiondCmd();
123 } catch (UnknownHostException uhe) {
d60dfbe4 124 uhe.printStackTrace();
43e5396b 125 } catch (IOException ioe) {
501f6777
CB
126 try {
127 Thread.sleep(3000);
128 } catch (InterruptedException e) {
129 e.printStackTrace();
130 }
43e5396b
DG
131 }
132 }
133 }
134
d60dfbe4
AM
135 /**
136 * Dispose this client and close any socket connection it may hold.
137 */
138 public void close() {
43e5396b 139 this.quit = true;
43e5396b
DG
140
141 try {
142 if (this.sessiondSock != null) {
143 this.sessiondSock.close();
144 }
d60dfbe4 145 } catch (IOException e) {
43e5396b
DG
146 e.printStackTrace();
147 }
148 }
149
d60dfbe4 150 /**
43e5396b
DG
151 * Receive header data from the session daemon using the LTTng command
152 * static buffer of the right size.
153 */
d60dfbe4
AM
154 private void recvHeader() throws IOException {
155 byte data[] = new byte[SessiondHeaderCommand.HEADER_SIZE];
43e5396b 156
08284556
AM
157 int readLen = this.inFromSessiond.read(data, 0, data.length);
158 if (readLen != data.length) {
43e5396b
DG
159 throw new IOException();
160 }
161 this.headerCmd.populate(data);
162 }
163
d60dfbe4 164 /**
43e5396b
DG
165 * Receive payload from the session daemon. This MUST be done after a
166 * recvHeader() so the header value of a command are known.
167 *
168 * The caller SHOULD use isPayload() before which returns true if a payload
169 * is expected after the header.
170 */
d60dfbe4
AM
171 private byte[] recvPayload() throws IOException {
172 byte payload[] = new byte[(int) this.headerCmd.getDataSize()];
43e5396b
DG
173
174 /* Failsafe check so we don't waste our time reading 0 bytes. */
175 if (payload.length == 0) {
176 return null;
177 }
178
179 this.inFromSessiond.read(payload, 0, payload.length);
180 return payload;
181 }
182
d60dfbe4 183 /**
43e5396b
DG
184 * Handle session command from the session daemon.
185 */
d60dfbe4 186 private void handleSessiondCmd() throws IOException {
43e5396b
DG
187 byte data[] = null;
188
189 while (true) {
190 /* Get header from session daemon. */
191 recvHeader();
192
d60dfbe4 193 if (headerCmd.getDataSize() > 0) {
43e5396b
DG
194 data = recvPayload();
195 }
196
d60dfbe4
AM
197 switch (headerCmd.getCommandType()) {
198 case CMD_REG_DONE:
199 {
200 /*
201 * Countdown the registration latch, meaning registration is
202 * done and we can proceed to continue tracing.
203 */
204 registrationLatch.countDown();
205 /*
206 * We don't send any reply to the registration done command.
207 * This just marks the end of the initial session setup.
208 */
209 continue;
210 }
211 case CMD_LIST:
212 {
213 SessiondListLoggersResponse listLoggerCmd = new SessiondListLoggersResponse();
214 listLoggerCmd.execute(logAgent);
215 data = listLoggerCmd.getBytes();
216 break;
217 }
218 case CMD_ENABLE:
219 {
220 SessiondEnableHandler enableCmd = new SessiondEnableHandler();
221 if (data == null) {
222 enableCmd.code = ISessiondResponse.LttngAgentRetCode.CODE_INVALID_CMD;
43e5396b
DG
223 break;
224 }
d60dfbe4
AM
225 enableCmd.populate(data);
226 enableCmd.execute(logAgent);
227 data = enableCmd.getBytes();
228 break;
229 }
230 case CMD_DISABLE:
231 {
232 SessiondDisableHandler disableCmd = new SessiondDisableHandler();
233 if (data == null) {
234 disableCmd.setRetCode(ISessiondResponse.LttngAgentRetCode.CODE_INVALID_CMD);
43e5396b
DG
235 break;
236 }
d60dfbe4
AM
237 disableCmd.populate(data);
238 disableCmd.execute(logAgent);
239 data = disableCmd.getBytes();
240 break;
241 }
242 default:
243 {
244 data = new byte[4];
245 ByteBuffer buf = ByteBuffer.wrap(data);
246 buf.order(ByteOrder.BIG_ENDIAN);
247 break;
248 }
43e5396b
DG
249 }
250
d60dfbe4
AM
251 if (data == null) {
252 /*
253 * Simply used to silence a potential null access warning below.
254 *
255 * The flow analysis gets confused here and thinks "data" may be
256 * null at this point. It should not happen according to program
257 * logic, if it does we've done something wrong.
258 */
259 throw new IllegalStateException();
260 }
43e5396b
DG
261 /* Send payload to session daemon. */
262 this.outToSessiond.write(data, 0, data.length);
263 this.outToSessiond.flush();
264 }
265 }
266
bc7de6d9 267 private static String getHomePath() {
f1fa0535
DG
268 return System.getProperty("user.home");
269 }
270
271 /**
272 * Read port number from file created by the session daemon.
273 *
274 * @return port value if found else 0.
275 */
bc7de6d9 276 private static int getPortFromFile(String path) throws IOException {
f1fa0535 277 int port;
d60dfbe4 278 BufferedReader br = null;
f1fa0535
DG
279
280 try {
281 br = new BufferedReader(new FileReader(path));
282 String line = br.readLine();
283 port = Integer.parseInt(line, 10);
284 if (port < 0 || port > 65535) {
285 /* Invalid value. Ignore. */
286 port = 0;
287 }
f1fa0535
DG
288 } catch (FileNotFoundException e) {
289 /* No port available. */
290 port = 0;
d60dfbe4
AM
291 } finally {
292 if (br != null) {
293 br.close();
294 }
f1fa0535
DG
295 }
296
297 return port;
298 }
299
d60dfbe4 300 private void connectToSessiond() throws IOException {
f1fa0535
DG
301 int port;
302
d60dfbe4 303 if (this.isRoot) {
08284556 304 port = getPortFromFile(ROOT_PORT_FILE);
f1fa0535
DG
305 if (port == 0) {
306 /* No session daemon available. Stop and retry later. */
307 throw new IOException();
308 }
309 } else {
08284556 310 port = getPortFromFile(getHomePath() + USER_PORT_FILE);
f1fa0535
DG
311 if (port == 0) {
312 /* No session daemon available. Stop and retry later. */
313 throw new IOException();
314 }
315 }
316
08284556
AM
317 this.sessiondSock = new Socket(SESSION_HOST, port);
318 this.inFromSessiond = new DataInputStream(sessiondSock.getInputStream());
319 this.outToSessiond = new DataOutputStream(sessiondSock.getOutputStream());
43e5396b
DG
320 }
321
d60dfbe4 322 private void registerToSessiond() throws IOException {
501f6777 323 byte data[] = new byte[16];
43e5396b
DG
324 ByteBuffer buf = ByteBuffer.wrap(data);
325 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
326
d60dfbe4 327 buf.putInt(logAgent.getDomain().value());
43e5396b 328 buf.putInt(Integer.parseInt(pid));
bc7de6d9
AM
329 buf.putInt(protocolMajorVersion);
330 buf.putInt(protocolMinorVersion);
43e5396b
DG
331 this.outToSessiond.write(data, 0, data.length);
332 this.outToSessiond.flush();
333 }
334}
This page took 0.039132 seconds and 4 git commands to generate.