Blame liblttng-ust-java-agent/java/lttng-ust-agent-common/org/lttng/ust/agent/client/LttngTcpSessiondClient.java

Packit c04fcb
/*
Packit c04fcb
 * Copyright (C) 2015-2016 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
Packit c04fcb
 * Copyright (C) 2013 - David Goulet <dgoulet@efficios.com>
Packit c04fcb
 *
Packit c04fcb
 * This library is free software; you can redistribute it and/or modify it
Packit c04fcb
 * under the terms of the GNU Lesser General Public License, version 2.1 only,
Packit c04fcb
 * as published by the Free Software Foundation.
Packit c04fcb
 *
Packit c04fcb
 * This library is distributed in the hope that it will be useful, but WITHOUT
Packit c04fcb
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
Packit c04fcb
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
Packit c04fcb
 * for more details.
Packit c04fcb
 *
Packit c04fcb
 * You should have received a copy of the GNU Lesser General Public License
Packit c04fcb
 * along with this library; if not, write to the Free Software Foundation,
Packit c04fcb
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Packit c04fcb
 */
Packit c04fcb
Packit c04fcb
package org.lttng.ust.agent.client;
Packit c04fcb
Packit c04fcb
import java.io.BufferedReader;
Packit c04fcb
import java.io.DataInputStream;
Packit c04fcb
import java.io.DataOutputStream;
Packit c04fcb
import java.io.FileInputStream;
Packit c04fcb
import java.io.FileNotFoundException;
Packit c04fcb
import java.io.IOException;
Packit c04fcb
import java.io.InputStreamReader;
Packit c04fcb
import java.lang.management.ManagementFactory;
Packit c04fcb
import java.net.Socket;
Packit c04fcb
import java.net.UnknownHostException;
Packit c04fcb
import java.nio.ByteBuffer;
Packit c04fcb
import java.nio.ByteOrder;
Packit c04fcb
import java.nio.charset.Charset;
Packit c04fcb
import java.util.concurrent.CountDownLatch;
Packit c04fcb
import java.util.concurrent.TimeUnit;
Packit c04fcb
Packit c04fcb
import org.lttng.ust.agent.utils.LttngUstAgentLogger;
Packit c04fcb
Packit c04fcb
/**
Packit c04fcb
 * Client for agents to connect to a local session daemon, using a TCP socket.
Packit c04fcb
 *
Packit c04fcb
 * @author David Goulet
Packit c04fcb
 */
Packit c04fcb
public class LttngTcpSessiondClient implements Runnable {
Packit c04fcb
Packit c04fcb
	private static final String SESSION_HOST = "127.0.0.1";
Packit c04fcb
	private static final String ROOT_PORT_FILE = "/var/run/lttng/agent.port";
Packit c04fcb
	private static final String USER_PORT_FILE = "/.lttng/agent.port";
Packit c04fcb
	private static final Charset PORT_FILE_ENCODING = Charset.forName("UTF-8");
Packit c04fcb
Packit c04fcb
	private static final int PROTOCOL_MAJOR_VERSION = 2;
Packit c04fcb
	private static final int PROTOCOL_MINOR_VERSION = 0;
Packit c04fcb
Packit c04fcb
	/** Command header from the session deamon. */
Packit c04fcb
	private final CountDownLatch registrationLatch = new CountDownLatch(1);
Packit c04fcb
Packit c04fcb
	private Socket sessiondSock;
Packit c04fcb
	private volatile boolean quit = false;
Packit c04fcb
Packit c04fcb
	private DataInputStream inFromSessiond;
Packit c04fcb
	private DataOutputStream outToSessiond;
Packit c04fcb
Packit c04fcb
	private final ILttngTcpClientListener logAgent;
Packit c04fcb
	private final int domainValue;
Packit c04fcb
	private final boolean isRoot;
Packit c04fcb
Packit c04fcb
	/**
Packit c04fcb
	 * Constructor
Packit c04fcb
	 *
Packit c04fcb
	 * @param logAgent
Packit c04fcb
	 *            The listener this client will operate on, typically an LTTng
Packit c04fcb
	 *            agent.
Packit c04fcb
	 * @param domainValue
Packit c04fcb
	 *            The integer to send to the session daemon representing the
Packit c04fcb
	 *            tracing domain to handle.
Packit c04fcb
	 * @param isRoot
Packit c04fcb
	 *            True if this client should connect to the root session daemon,
Packit c04fcb
	 *            false if it should connect to the user one.
Packit c04fcb
	 */
Packit c04fcb
	public LttngTcpSessiondClient(ILttngTcpClientListener logAgent, int domainValue, boolean isRoot) {
Packit c04fcb
		this.logAgent = logAgent;
Packit c04fcb
		this.domainValue = domainValue;
Packit c04fcb
		this.isRoot = isRoot;
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	/**
Packit c04fcb
	 * Wait until this client has successfully established a connection to its
Packit c04fcb
	 * target session daemon.
Packit c04fcb
	 *
Packit c04fcb
	 * @param seconds
Packit c04fcb
	 *            A timeout in seconds after which this method will return
Packit c04fcb
	 *            anyway.
Packit c04fcb
	 * @return True if the the client actually established the connection, false
Packit c04fcb
	 *         if we returned because the timeout has elapsed or the thread was
Packit c04fcb
	 *         interrupted.
Packit c04fcb
	 */
Packit c04fcb
	public boolean waitForConnection(int seconds) {
Packit c04fcb
		try {
Packit c04fcb
			return registrationLatch.await(seconds, TimeUnit.SECONDS);
Packit c04fcb
		} catch (InterruptedException e) {
Packit c04fcb
			return false;
Packit c04fcb
		}
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	@Override
Packit c04fcb
	public void run() {
Packit c04fcb
		for (;;) {
Packit c04fcb
			if (this.quit) {
Packit c04fcb
				break;
Packit c04fcb
			}
Packit c04fcb
Packit c04fcb
			try {
Packit c04fcb
Packit c04fcb
				/*
Packit c04fcb
				 * Connect to the session daemon before anything else.
Packit c04fcb
				 */
Packit c04fcb
				log("Connecting to sessiond");
Packit c04fcb
				connectToSessiond();
Packit c04fcb
Packit c04fcb
				/*
Packit c04fcb
				 * Register to the session daemon as the Java component of the
Packit c04fcb
				 * UST application.
Packit c04fcb
				 */
Packit c04fcb
				log("Registering to sessiond");
Packit c04fcb
				registerToSessiond();
Packit c04fcb
Packit c04fcb
				/*
Packit c04fcb
				 * Block on socket receive and wait for command from the
Packit c04fcb
				 * session daemon. This will return if and only if there is a
Packit c04fcb
				 * fatal error or the socket closes.
Packit c04fcb
				 */
Packit c04fcb
				log("Waiting on sessiond commands...");
Packit c04fcb
				handleSessiondCmd();
Packit c04fcb
			} catch (UnknownHostException uhe) {
Packit c04fcb
				uhe.printStackTrace();
Packit c04fcb
			} catch (IOException ioe) {
Packit c04fcb
				try {
Packit c04fcb
					Thread.sleep(3000);
Packit c04fcb
				} catch (InterruptedException e) {
Packit c04fcb
					e.printStackTrace();
Packit c04fcb
				}
Packit c04fcb
			}
Packit c04fcb
		}
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	/**
Packit c04fcb
	 * Dispose this client and close any socket connection it may hold.
Packit c04fcb
	 */
Packit c04fcb
	public void close() {
Packit c04fcb
		log("Closing client");
Packit c04fcb
		this.quit = true;
Packit c04fcb
Packit c04fcb
		try {
Packit c04fcb
			if (this.sessiondSock != null) {
Packit c04fcb
				this.sessiondSock.close();
Packit c04fcb
			}
Packit c04fcb
		} catch (IOException e) {
Packit c04fcb
			e.printStackTrace();
Packit c04fcb
		}
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	private void connectToSessiond() throws IOException {
Packit c04fcb
		int rootPort = getPortFromFile(ROOT_PORT_FILE);
Packit c04fcb
		int userPort = getPortFromFile(getHomePath() + USER_PORT_FILE);
Packit c04fcb
Packit c04fcb
		/*
Packit c04fcb
		 * Check for the edge case of both files existing but pointing to the
Packit c04fcb
		 * same port. In this case, let the root client handle it.
Packit c04fcb
		 */
Packit c04fcb
		if ((rootPort != 0) && (rootPort == userPort) && (!isRoot)) {
Packit c04fcb
			log("User and root config files both point to port " + rootPort +
Packit c04fcb
					". Letting the root client handle it.");
Packit c04fcb
			throw new IOException();
Packit c04fcb
		}
Packit c04fcb
Packit c04fcb
		int portToUse = (isRoot ? rootPort : userPort);
Packit c04fcb
Packit c04fcb
		if (portToUse == 0) {
Packit c04fcb
			/* No session daemon available. Stop and retry later. */
Packit c04fcb
			throw new IOException();
Packit c04fcb
		}
Packit c04fcb
Packit c04fcb
		this.sessiondSock = new Socket(SESSION_HOST, portToUse);
Packit c04fcb
		this.inFromSessiond = new DataInputStream(sessiondSock.getInputStream());
Packit c04fcb
		this.outToSessiond = new DataOutputStream(sessiondSock.getOutputStream());
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	private static String getHomePath() {
Packit c04fcb
		/*
Packit c04fcb
		 * The environment variable LTTNG_HOME overrides HOME if
Packit c04fcb
		 * defined.
Packit c04fcb
		 */
Packit c04fcb
		String homePath = System.getenv("LTTNG_HOME");
Packit c04fcb
Packit c04fcb
		if (homePath == null) {
Packit c04fcb
			homePath = System.getProperty("user.home");
Packit c04fcb
		}
Packit c04fcb
		return homePath;
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	/**
Packit c04fcb
	 * Read port number from file created by the session daemon.
Packit c04fcb
	 *
Packit c04fcb
	 * @return port value if found else 0.
Packit c04fcb
	 */
Packit c04fcb
	private static int getPortFromFile(String path) throws IOException {
Packit c04fcb
		int port;
Packit c04fcb
		BufferedReader br = null;
Packit c04fcb
Packit c04fcb
		try {
Packit c04fcb
			br = new BufferedReader(new InputStreamReader(new FileInputStream(path), PORT_FILE_ENCODING));
Packit c04fcb
			String line = br.readLine();
Packit c04fcb
			port = Integer.parseInt(line, 10);
Packit c04fcb
			if (port < 0 || port > 65535) {
Packit c04fcb
				/* Invalid value. Ignore. */
Packit c04fcb
				port = 0;
Packit c04fcb
			}
Packit c04fcb
		} catch (FileNotFoundException e) {
Packit c04fcb
			/* No port available. */
Packit c04fcb
			port = 0;
Packit c04fcb
		} finally {
Packit c04fcb
			if (br != null) {
Packit c04fcb
				br.close();
Packit c04fcb
			}
Packit c04fcb
		}
Packit c04fcb
Packit c04fcb
		return port;
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	private void registerToSessiond() throws IOException {
Packit c04fcb
		byte data[] = new byte[16];
Packit c04fcb
		ByteBuffer buf = ByteBuffer.wrap(data);
Packit c04fcb
		String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
Packit c04fcb
Packit c04fcb
		buf.putInt(domainValue);
Packit c04fcb
		buf.putInt(Integer.parseInt(pid));
Packit c04fcb
		buf.putInt(PROTOCOL_MAJOR_VERSION);
Packit c04fcb
		buf.putInt(PROTOCOL_MINOR_VERSION);
Packit c04fcb
		this.outToSessiond.write(data, 0, data.length);
Packit c04fcb
		this.outToSessiond.flush();
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	/**
Packit c04fcb
	 * Handle session command from the session daemon.
Packit c04fcb
	 */
Packit c04fcb
	private void handleSessiondCmd() throws IOException {
Packit c04fcb
		/* Data read from the socket */
Packit c04fcb
		byte inputData[] = null;
Packit c04fcb
		/* Reply data written to the socket, sent to the sessiond */
Packit c04fcb
		byte responseData[] = null;
Packit c04fcb
Packit c04fcb
		while (true) {
Packit c04fcb
			/* Get header from session daemon. */
Packit c04fcb
			SessiondCommandHeader cmdHeader = recvHeader();
Packit c04fcb
Packit c04fcb
			if (cmdHeader.getDataSize() > 0) {
Packit c04fcb
				inputData = recvPayload(cmdHeader);
Packit c04fcb
			}
Packit c04fcb
Packit c04fcb
			switch (cmdHeader.getCommandType()) {
Packit c04fcb
			case CMD_REG_DONE:
Packit c04fcb
			{
Packit c04fcb
				/*
Packit c04fcb
				 * Countdown the registration latch, meaning registration is
Packit c04fcb
				 * done and we can proceed to continue tracing.
Packit c04fcb
				 */
Packit c04fcb
				registrationLatch.countDown();
Packit c04fcb
				/*
Packit c04fcb
				 * We don't send any reply to the registration done command.
Packit c04fcb
				 * This just marks the end of the initial session setup.
Packit c04fcb
				 */
Packit c04fcb
				log("Registration done");
Packit c04fcb
				continue;
Packit c04fcb
			}
Packit c04fcb
			case CMD_LIST:
Packit c04fcb
			{
Packit c04fcb
				SessiondCommand listLoggerCmd = new SessiondListLoggersCommand();
Packit c04fcb
				LttngAgentResponse response = listLoggerCmd.execute(logAgent);
Packit c04fcb
				responseData = response.getBytes();
Packit c04fcb
				log("Received list loggers command");
Packit c04fcb
				break;
Packit c04fcb
			}
Packit c04fcb
			case CMD_EVENT_ENABLE:
Packit c04fcb
			{
Packit c04fcb
				if (inputData == null) {
Packit c04fcb
					/* Invalid command */
Packit c04fcb
					responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
Packit c04fcb
					break;
Packit c04fcb
				}
Packit c04fcb
				SessiondCommand enableEventCmd = new SessiondEnableEventCommand(inputData);
Packit c04fcb
				LttngAgentResponse response = enableEventCmd.execute(logAgent);
Packit c04fcb
				responseData = response.getBytes();
Packit c04fcb
				log("Received enable event command");
Packit c04fcb
				break;
Packit c04fcb
			}
Packit c04fcb
			case CMD_EVENT_DISABLE:
Packit c04fcb
			{
Packit c04fcb
				if (inputData == null) {
Packit c04fcb
					/* Invalid command */
Packit c04fcb
					responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
Packit c04fcb
					break;
Packit c04fcb
				}
Packit c04fcb
				SessiondCommand disableEventCmd = new SessiondDisableEventCommand(inputData);
Packit c04fcb
				LttngAgentResponse response = disableEventCmd.execute(logAgent);
Packit c04fcb
				responseData = response.getBytes();
Packit c04fcb
				log("Received disable event command");
Packit c04fcb
				break;
Packit c04fcb
			}
Packit c04fcb
			case CMD_APP_CTX_ENABLE:
Packit c04fcb
			{
Packit c04fcb
				if (inputData == null) {
Packit c04fcb
					/* This commands expects a payload, invalid command */
Packit c04fcb
					responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
Packit c04fcb
					break;
Packit c04fcb
				}
Packit c04fcb
				SessiondCommand enableAppCtxCmd = new SessiondEnableAppContextCommand(inputData);
Packit c04fcb
				LttngAgentResponse response = enableAppCtxCmd.execute(logAgent);
Packit c04fcb
				responseData = response.getBytes();
Packit c04fcb
				log("Received enable app-context command");
Packit c04fcb
				break;
Packit c04fcb
			}
Packit c04fcb
			case CMD_APP_CTX_DISABLE:
Packit c04fcb
			{
Packit c04fcb
				if (inputData == null) {
Packit c04fcb
					/* This commands expects a payload, invalid command */
Packit c04fcb
					responseData = LttngAgentResponse.FAILURE_RESPONSE.getBytes();
Packit c04fcb
					break;
Packit c04fcb
				}
Packit c04fcb
				SessiondCommand disableAppCtxCmd = new SessiondDisableAppContextCommand(inputData);
Packit c04fcb
				LttngAgentResponse response = disableAppCtxCmd.execute(logAgent);
Packit c04fcb
				responseData = response.getBytes();
Packit c04fcb
				log("Received disable app-context command");
Packit c04fcb
				break;
Packit c04fcb
			}
Packit c04fcb
			default:
Packit c04fcb
			{
Packit c04fcb
				/* Unknown command, send empty reply */
Packit c04fcb
				responseData = new byte[4];
Packit c04fcb
				ByteBuffer buf = ByteBuffer.wrap(responseData);
Packit c04fcb
				buf.order(ByteOrder.BIG_ENDIAN);
Packit c04fcb
				log("Received unknown command, ignoring");
Packit c04fcb
				break;
Packit c04fcb
			}
Packit c04fcb
			}
Packit c04fcb
Packit c04fcb
			/* Send response to the session daemon. */
Packit c04fcb
			log("Sending response");
Packit c04fcb
			this.outToSessiond.write(responseData, 0, responseData.length);
Packit c04fcb
			this.outToSessiond.flush();
Packit c04fcb
		}
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	/**
Packit c04fcb
	 * Receive header data from the session daemon using the LTTng command
Packit c04fcb
	 * static buffer of the right size.
Packit c04fcb
	 */
Packit c04fcb
	private SessiondCommandHeader recvHeader() throws IOException {
Packit c04fcb
		byte data[] = new byte[SessiondCommandHeader.HEADER_SIZE];
Packit c04fcb
Packit c04fcb
		int readLen = this.inFromSessiond.read(data, 0, data.length);
Packit c04fcb
		if (readLen != data.length) {
Packit c04fcb
			throw new IOException();
Packit c04fcb
		}
Packit c04fcb
		return new SessiondCommandHeader(data);
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	/**
Packit c04fcb
	 * Receive payload from the session daemon. This MUST be done after a
Packit c04fcb
	 * recvHeader() so the header value of a command are known.
Packit c04fcb
	 *
Packit c04fcb
	 * The caller SHOULD use isPayload() before which returns true if a payload
Packit c04fcb
	 * is expected after the header.
Packit c04fcb
	 */
Packit c04fcb
	private byte[] recvPayload(SessiondCommandHeader headerCmd) throws IOException {
Packit c04fcb
		byte payload[] = new byte[(int) headerCmd.getDataSize()];
Packit c04fcb
Packit c04fcb
		/* Failsafe check so we don't waste our time reading 0 bytes. */
Packit c04fcb
		if (payload.length == 0) {
Packit c04fcb
			return null;
Packit c04fcb
		}
Packit c04fcb
Packit c04fcb
		int read = inFromSessiond.read(payload, 0, payload.length);
Packit c04fcb
		if (read != payload.length) {
Packit c04fcb
			throw new IOException("Unexpected number of bytes read in sessiond command payload");
Packit c04fcb
		}
Packit c04fcb
		return payload;
Packit c04fcb
	}
Packit c04fcb
Packit c04fcb
	/**
Packit c04fcb
	 * Wrapper for this class's logging, adds the connection's characteristics
Packit c04fcb
	 * to help differentiate between multiple TCP clients.
Packit c04fcb
	 */
Packit c04fcb
	private void log(String message) {
Packit c04fcb
		LttngUstAgentLogger.log(getClass(),
Packit c04fcb
				"(root=" + isRoot + ", domain=" + domainValue + ") " + message);
Packit c04fcb
	}
Packit c04fcb
}