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