Refactor liblttng-ust-jul in liblttng-ust-agent
[lttng-ust.git] / liblttng-ust-java-agent / java / org / lttng / ust / agent / LTTngTCPSessiondClient.java
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;
19
20 import java.util.concurrent.Semaphore;
21 import java.nio.ByteBuffer;
22 import java.nio.ByteOrder;
23 import java.lang.Integer;
24 import java.io.IOException;
25 import java.io.BufferedOutputStream;
26 import java.io.BufferedReader;
27 import java.io.ByteArrayOutputStream;
28 import java.io.DataOutputStream;
29 import java.io.DataInputStream;
30 import java.io.FileReader;
31 import java.io.FileNotFoundException;
32 import java.net.*;
33 import java.lang.management.ManagementFactory;
34
35 class LTTngTCPSessiondClient implements Runnable {
36
37 /* Command header from the session deamon. */
38 private LTTngSessiondCmd2_6.sessiond_hdr headerCmd =
39 new LTTngSessiondCmd2_6.sessiond_hdr();
40
41 private Socket sessiondSock;
42 private volatile boolean quit = false;
43
44 private DataInputStream inFromSessiond;
45 private DataOutputStream outToSessiond;
46
47 private LogFramework log;
48
49 private Semaphore registerSem;
50
51 private static final String sessiondHost = "127.0.0.1";
52 private static final String rootPortFile = "/var/run/lttng/agent.port";
53 private static final String userPortFile = "/.lttng/agent.port";
54
55 private static Integer protocolMajorVersion = 1;
56 private static Integer protocolMinorVersion = 0;
57
58 private LTTngAgent.Domain agentDomain;
59
60 /* Indicate if we've already release the semaphore. */
61 private boolean sem_posted = false;
62
63 public LTTngTCPSessiondClient(LTTngAgent.Domain domain, LogFramework log, Semaphore sem) {
64 this.agentDomain = domain;
65 this.log = log;
66 this.registerSem = sem;
67 }
68
69 /*
70 * Try to release the registerSem if it's not already done.
71 */
72 private void tryReleaseSem()
73 {
74 /* Release semaphore so we unblock the agent. */
75 if (!this.sem_posted) {
76 this.registerSem.release();
77 this.sem_posted = true;
78 }
79 }
80
81 @Override
82 public void run() {
83 for (;;) {
84 if (this.quit) {
85 break;
86 }
87
88 /* Cleanup Agent state before trying to connect or reconnect. */
89 this.log.reset();
90
91 try {
92
93 /*
94 * Connect to the session daemon before anything else.
95 */
96 connectToSessiond();
97
98 /*
99 * Register to the session daemon as the Java component of the
100 * UST application.
101 */
102 registerToSessiond();
103
104 /*
105 * Block on socket receive and wait for command from the
106 * session daemon. This will return if and only if there is a
107 * fatal error or the socket closes.
108 */
109 handleSessiondCmd();
110 } catch (UnknownHostException uhe) {
111 tryReleaseSem();
112 System.out.println(uhe);
113 } catch (IOException ioe) {
114 tryReleaseSem();
115 try {
116 Thread.sleep(3000);
117 } catch (InterruptedException e) {
118 e.printStackTrace();
119 }
120 } catch (Exception e) {
121 tryReleaseSem();
122 e.printStackTrace();
123 }
124 }
125 }
126
127 public void destroy() {
128 this.quit = true;
129
130 try {
131 if (this.sessiondSock != null) {
132 this.sessiondSock.close();
133 }
134 } catch (Exception e) {
135 e.printStackTrace();
136 }
137 }
138
139 /*
140 * Receive header data from the session daemon using the LTTng command
141 * static buffer of the right size.
142 */
143 private void recvHeader() throws Exception {
144 int read_len;
145 byte data[] = new byte[this.headerCmd.SIZE];
146
147 read_len = this.inFromSessiond.read(data, 0, data.length);
148 if (read_len != data.length) {
149 throw new IOException();
150 }
151 this.headerCmd.populate(data);
152 }
153
154 /*
155 * Receive payload from the session daemon. This MUST be done after a
156 * recvHeader() so the header value of a command are known.
157 *
158 * The caller SHOULD use isPayload() before which returns true if a payload
159 * is expected after the header.
160 */
161 private byte[] recvPayload() throws Exception {
162 byte payload[] = new byte[(int) this.headerCmd.data_size];
163
164 /* Failsafe check so we don't waste our time reading 0 bytes. */
165 if (payload.length == 0) {
166 return null;
167 }
168
169 this.inFromSessiond.read(payload, 0, payload.length);
170 return payload;
171 }
172
173 /*
174 * Handle session command from the session daemon.
175 */
176 private void handleSessiondCmd() throws Exception {
177 int ret_code;
178 byte data[] = null;
179
180 while (true) {
181 /* Get header from session daemon. */
182 recvHeader();
183
184 if (headerCmd.data_size > 0) {
185 data = recvPayload();
186 }
187
188 switch (headerCmd.cmd) {
189 case CMD_REG_DONE:
190 {
191 /*
192 * Release semaphore so meaning registration is done and we
193 * can proceed to continue tracing.
194 */
195 tryReleaseSem();
196 /*
197 * We don't send any reply to the registration done command.
198 * This just marks the end of the initial session setup.
199 */
200 continue;
201 }
202 case CMD_LIST:
203 {
204 LTTngSessiondCmd2_6.sessiond_list_logger listLoggerCmd =
205 new LTTngSessiondCmd2_6.sessiond_list_logger();
206 listLoggerCmd.execute(this.log);
207 data = listLoggerCmd.getBytes();
208 break;
209 }
210 case CMD_ENABLE:
211 {
212 LTTngSessiondCmd2_6.sessiond_enable_handler enableCmd =
213 new LTTngSessiondCmd2_6.sessiond_enable_handler();
214 if (data == null) {
215 enableCmd.code = LTTngSessiondCmd2_6.lttng_agent_ret_code.CODE_INVALID_CMD;
216 break;
217 }
218 enableCmd.populate(data);
219 enableCmd.execute(this.log);
220 data = enableCmd.getBytes();
221 break;
222 }
223 case CMD_DISABLE:
224 {
225 LTTngSessiondCmd2_6.sessiond_disable_handler disableCmd =
226 new LTTngSessiondCmd2_6.sessiond_disable_handler();
227 if (data == null) {
228 disableCmd.code = LTTngSessiondCmd2_6.lttng_agent_ret_code.CODE_INVALID_CMD;
229 break;
230 }
231 disableCmd.populate(data);
232 disableCmd.execute(this.log);
233 data = disableCmd.getBytes();
234 break;
235 }
236 default:
237 {
238 data = new byte[4];
239 ByteBuffer buf = ByteBuffer.wrap(data);
240 buf.order(ByteOrder.BIG_ENDIAN);
241 LTTngSessiondCmd2_6.lttng_agent_ret_code code =
242 LTTngSessiondCmd2_6.lttng_agent_ret_code.CODE_INVALID_CMD;
243 break;
244 }
245 }
246
247 /* Send payload to session daemon. */
248 this.outToSessiond.write(data, 0, data.length);
249 this.outToSessiond.flush();
250 }
251 }
252
253 private String getHomePath() {
254 return System.getProperty("user.home");
255 }
256
257 /**
258 * Read port number from file created by the session daemon.
259 *
260 * @return port value if found else 0.
261 */
262 private int getPortFromFile(String path) throws IOException {
263 int port;
264 BufferedReader br;
265
266 try {
267 br = new BufferedReader(new FileReader(path));
268 String line = br.readLine();
269 port = Integer.parseInt(line, 10);
270 if (port < 0 || port > 65535) {
271 /* Invalid value. Ignore. */
272 port = 0;
273 }
274 br.close();
275 } catch (FileNotFoundException e) {
276 /* No port available. */
277 port = 0;
278 }
279
280 return port;
281 }
282
283 private void connectToSessiond() throws Exception {
284 int port;
285
286 if (this.log.isRoot()) {
287 port = getPortFromFile(rootPortFile);
288 if (port == 0) {
289 /* No session daemon available. Stop and retry later. */
290 throw new IOException();
291 }
292 } else {
293 port = getPortFromFile(getHomePath() + userPortFile);
294 if (port == 0) {
295 /* No session daemon available. Stop and retry later. */
296 throw new IOException();
297 }
298 }
299
300 this.sessiondSock = new Socket(this.sessiondHost, port);
301 this.inFromSessiond = new DataInputStream(
302 sessiondSock.getInputStream());
303 this.outToSessiond = new DataOutputStream(
304 sessiondSock.getOutputStream());
305 }
306
307 private void registerToSessiond() throws Exception {
308 byte data[] = new byte[16];
309 ByteBuffer buf = ByteBuffer.wrap(data);
310 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
311
312 buf.putInt(this.agentDomain.value());
313 buf.putInt(Integer.parseInt(pid));
314 buf.putInt(this.protocolMajorVersion);
315 buf.putInt(this.protocolMinorVersion);
316 this.outToSessiond.write(data, 0, data.length);
317 this.outToSessiond.flush();
318 }
319 }
This page took 0.049726 seconds and 4 git commands to generate.