DefaultMessageManager.java 16.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
package com.dianping.cat.message.internal;

import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;

import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.lookup.ContainerHolder;
import org.unidal.lookup.annotation.Inject;

import com.dianping.cat.Cat;
import com.dianping.cat.configuration.ClientConfigManager;
import com.dianping.cat.configuration.NetworkInterfaceManager;
import com.dianping.cat.configuration.client.entity.Domain;
import com.dianping.cat.message.ForkedTransaction;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.TaggedTransaction;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.io.MessageSender;
import com.dianping.cat.message.io.TransportManager;
import com.dianping.cat.message.spi.MessageManager;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.message.spi.internal.DefaultMessageTree;

public class DefaultMessageManager extends ContainerHolder implements MessageManager, Initializable, LogEnabled {
	@Inject
	private ClientConfigManager m_configManager;

	@Inject
	private TransportManager m_transportManager;

	@Inject
	private MessageIdFactory m_factory;

	// we don't use static modifier since MessageManager is configured as singleton
	private ThreadLocal<Context> m_context = new ThreadLocal<Context>();

	private long m_throttleTimes;

	private Domain m_domain;

	private String m_hostName;

	private boolean m_firstMessage = true;

	private TransactionHelper m_validator = new TransactionHelper();

	private Map<String, TaggedTransaction> m_taggedTransactions;

	private Logger m_logger;

	@Override
	public void add(Message message) {
		Context ctx = getContext();

		if (ctx != null) {
			ctx.add(message);
		}
	}

	@Override
	public void bind(String tag, String title) {
		TaggedTransaction t = m_taggedTransactions.get(tag);

		if (t != null) {
			MessageTree tree = getThreadLocalMessageTree();
			String messageId = tree.getMessageId();

			if (messageId == null) {
				messageId = nextMessageId();
				tree.setMessageId(messageId);
			}
			if (tree != null) {
				t.start();
				t.bind(tag, messageId, title);
			}
		}
	}

	@Override
	public void enableLogging(Logger logger) {
		m_logger = logger;
	}

	@Override
	public void end(Transaction transaction) {
		Context ctx = getContext();

		if (ctx != null && transaction.isStandalone()) {
			if (ctx.end(this, transaction)) {
				m_context.remove();
			}
		}
	}

	public void flush(MessageTree tree) {
		if (tree.getMessageId() == null) {
			tree.setMessageId(nextMessageId());
		}

		MessageSender sender = m_transportManager.getSender();

		if (sender != null && isMessageEnabled()) {
			sender.send(tree);

			reset();
		} else {
			m_throttleTimes++;

			if (m_throttleTimes % 10000 == 0 || m_throttleTimes == 1) {
				m_logger.info("Cat Message is throttled! Times:" + m_throttleTimes);
			}
		}
	}

	public ClientConfigManager getConfigManager() {
		return m_configManager;
	}

	private Context getContext() {
		if (Cat.isInitialized()) {
			Context ctx = m_context.get();

			if (ctx != null) {
				return ctx;
			} else {
				if (m_domain != null) {
					ctx = new Context(m_domain.getId(), m_hostName, m_domain.getIp());
				} else {
					ctx = new Context("Unknown", m_hostName, "");
				}

				m_context.set(ctx);
				return ctx;
			}
		}

		return null;
	}

	@Override
	public String getDomain() {
		return m_domain.getId();
	}

	public String getMetricType() {
		return "";
	}

	@Override
	public Transaction getPeekTransaction() {
		Context ctx = getContext();

		if (ctx != null) {
			return ctx.peekTransaction(this);
		} else {
			return null;
		}
	}

	@Override
	public MessageTree getThreadLocalMessageTree() {
		Context ctx = m_context.get();

		if (ctx == null) {
			setup();
		}
		ctx = m_context.get();

		return ctx.m_tree;
	}

	@Override
	public boolean hasContext() {
		return m_context.get() != null;
	}

	@Override
	public void initialize() throws InitializationException {
		m_domain = m_configManager.getDomain();
		m_hostName = NetworkInterfaceManager.INSTANCE.getLocalHostName();

		if (m_domain.getIp() == null) {
			m_domain.setIp(NetworkInterfaceManager.INSTANCE.getLocalHostAddress());
		}

		// initialize domain and IP address
		try {
			m_factory.initialize(m_domain.getId());
		} catch (IOException e) {
			throw new InitializationException("Error while initializing MessageIdFactory!", e);
		}

		// initialize the tagged transaction cache
		final int size = m_configManager.getTaggedTransactionCacheSize();

		m_taggedTransactions = new LinkedHashMap<String, TaggedTransaction>(size * 4 / 3 + 1, 0.75f, true) {
			private static final long serialVersionUID = 1L;

			@Override
			protected boolean removeEldestEntry(Entry<String, TaggedTransaction> eldest) {
				return size() >= size;
			}
		};
	}

	@Override
	public boolean isCatEnabled() {
		return m_domain != null && m_domain.isEnabled() && m_configManager.isCatEnabled();
	}

	@Override
	public boolean isMessageEnabled() {
		return m_domain != null && m_domain.isEnabled() && m_context.get() != null && m_configManager.isCatEnabled();
	}

	public boolean isTraceMode() {
		Context content = getContext();

		if (content != null) {
			return content.isTraceMode();
		} else {
			return false;
		}
	}

	public void linkAsRunAway(DefaultForkedTransaction transaction) {
		Context ctx = getContext();
		if (ctx != null) {
			ctx.linkAsRunAway(transaction);
		}
	}

	public String nextMessageId() {
		return m_factory.getNextId();
	}

	@Override
	public void reset() {
		// destroy current thread local data
		Context ctx = m_context.get();

		if (ctx != null) {
			if (ctx.m_totalDurationInMicros == 0) {
				ctx.m_stack.clear();
				ctx.m_knownExceptions.clear();
				m_context.remove();
			} else {
				ctx.m_knownExceptions.clear();
			}
		}
	}

	public void setMetricType(String metricType) {
	}

	public void setTraceMode(boolean traceMode) {
		Context context = getContext();

		if (context != null) {
			context.setTraceMode(traceMode);
		}
	}

	@Override
	public void setup() {
		Context ctx;

		if (m_domain != null) {
			ctx = new Context(m_domain.getId(), m_hostName, m_domain.getIp());
		} else {
			ctx = new Context("Unknown", m_hostName, "");
		}

		m_context.set(ctx);
	}

	boolean shouldLog(Throwable e) {
		Context ctx = m_context.get();

		if (ctx != null) {
			return ctx.shouldLog(e);
		} else {
			return true;
		}
	}

	@Override
	public void start(Transaction transaction, boolean forked) {
		Context ctx = getContext();

		if (ctx != null) {
			ctx.start(transaction, forked);

			if (transaction instanceof TaggedTransaction) {
				TaggedTransaction tt = (TaggedTransaction) transaction;

				m_taggedTransactions.put(tt.getTag(), tt);
			}
		} else if (m_firstMessage) {
			m_firstMessage = false;
			m_logger.warn("CAT client is not enabled because it's not initialized yet");
		}
	}

	class Context {
		private MessageTree m_tree;

		private Stack<Transaction> m_stack;

		private int m_length;

		private boolean m_traceMode;

		private long m_totalDurationInMicros; // for truncate message

		private Set<Throwable> m_knownExceptions;

		public Context(String domain, String hostName, String ipAddress) {
			m_tree = new DefaultMessageTree();
			m_stack = new Stack<Transaction>();

			Thread thread = Thread.currentThread();
			String groupName = thread.getThreadGroup().getName();

			m_tree.setThreadGroupName(groupName);
			m_tree.setThreadId(String.valueOf(thread.getId()));
			m_tree.setThreadName(thread.getName());

			m_tree.setDomain(domain);
			m_tree.setHostName(hostName);
			m_tree.setIpAddress(ipAddress);
			m_length = 1;
			m_knownExceptions = new HashSet<Throwable>();
		}

		public void add(Message message) {
			if (m_stack.isEmpty()) {
				MessageTree tree = m_tree.copy();

				tree.setMessage(message);
				flush(tree);
			} else {
				Transaction parent = m_stack.peek();

				addTransactionChild(message, parent);
			}
		}

		private void addTransactionChild(Message message, Transaction transaction) {
			long treePeriod = trimToHour(m_tree.getMessage().getTimestamp());
			long messagePeriod = trimToHour(message.getTimestamp() - 10 * 1000L); // 10 seconds extra time allowed

			if (treePeriod < messagePeriod || m_length >= m_configManager.getMaxMessageLength()) {
				m_validator.truncateAndFlush(this, message.getTimestamp());
			}

			transaction.addChild(message);
			m_length++;
		}

		private void adjustForTruncatedTransaction(Transaction root) {
			DefaultEvent next = new DefaultEvent("TruncatedTransaction", "TotalDuration");
			long actualDurationInMicros = m_totalDurationInMicros + root.getDurationInMicros();

			next.addData(String.valueOf(actualDurationInMicros));
			next.setStatus(Message.SUCCESS);
			root.addChild(next);

			m_totalDurationInMicros = 0;
		}

		/**
		 * return true means the transaction has been flushed.
		 * 
		 * @param manager
		 * @param transaction
		 * @return true if message is flushed, false otherwise
		 */
		public boolean end(DefaultMessageManager manager, Transaction transaction) {
			if (!m_stack.isEmpty()) {
				Transaction current = m_stack.pop();

				if (transaction == current) {
					m_validator.validate(m_stack.isEmpty() ? null : m_stack.peek(), current);
				} else {
					while (transaction != current && !m_stack.empty()) {
						m_validator.validate(m_stack.peek(), current);

						current = m_stack.pop();
					}
				}

				if (m_stack.isEmpty()) {
					MessageTree tree = m_tree.copy();

					m_tree.setMessageId(null);
					m_tree.setMessage(null);

					if (m_totalDurationInMicros > 0) {
						adjustForTruncatedTransaction((Transaction) tree.getMessage());
					}

					manager.flush(tree);
					return true;
				}
			}

			return false;
		}

		public boolean isTraceMode() {
			return m_traceMode;
		}

		public void linkAsRunAway(DefaultForkedTransaction transaction) {
			m_validator.linkAsRunAway(transaction);
		}

		public Transaction peekTransaction(DefaultMessageManager defaultMessageManager) {
			if (m_stack.isEmpty()) {
				return null;
			} else {
				return m_stack.peek();
			}
		}

		public void setTraceMode(boolean traceMode) {
			m_traceMode = traceMode;
		}

		public boolean shouldLog(Throwable e) {
			if (m_knownExceptions == null) {
				m_knownExceptions = new HashSet<Throwable>();
			}

			if (m_knownExceptions.contains(e)) {
				return false;
			} else {
				m_knownExceptions.add(e);
				return true;
			}
		}

		public void start(Transaction transaction, boolean forked) {
			if (!m_stack.isEmpty()) {
				// Do NOT make strong reference from parent transaction to forked transaction.
				// Instead, we create a "soft" reference to forked transaction later, via linkAsRunAway()
				// By doing so, there is no need for synchronization between parent and child threads.
				// Both threads can complete() anytime despite the other thread.
				if (!(transaction instanceof ForkedTransaction)) {
					Transaction parent = m_stack.peek();
					addTransactionChild(transaction, parent);
				}
			} else {
				m_tree.setMessage(transaction);
			}

			if (!forked) {
				m_stack.push(transaction);
			}
		}

		private long trimToHour(long timestamp) {
			return timestamp - timestamp % (3600 * 1000L);
		}
	}

	class TransactionHelper {
		private void linkAsRunAway(DefaultForkedTransaction transaction) {
			DefaultEvent event = new DefaultEvent("RemoteCall", "RunAway");

			event.addData(transaction.getForkedMessageId(), transaction.getType() + ":" + transaction.getName());
			event.setTimestamp(transaction.getTimestamp());
			event.setStatus(Message.SUCCESS);
			event.setCompleted(true);
			transaction.setStandalone(true);

			add(event);
		}

		private void markAsNotCompleted(DefaultTransaction transaction) {
			DefaultEvent event = new DefaultEvent("cat", "BadInstrument");

			event.setStatus("TransactionNotCompleted");
			event.setCompleted(true);
			transaction.addChild(event);
			transaction.setCompleted(true);
		}

		private void markAsRunAway(Transaction parent, DefaultTaggedTransaction transaction) {
			if (!transaction.hasChildren()) {
				transaction.addData("RunAway");
			}

			transaction.setStatus(Message.SUCCESS);
			transaction.setStandalone(true);
			transaction.complete();
		}

		private void migrateMessage(Stack<Transaction> stack, Transaction source, Transaction target, int level) {
			Transaction current = level < stack.size() ? stack.get(level) : null;
			boolean shouldKeep = false;

			for (Message child : source.getChildren()) {
				if (child != current) {
					target.addChild(child);
				} else {
					DefaultTransaction cloned = new DefaultTransaction(current.getType(), current.getName(),
					      DefaultMessageManager.this);

					cloned.setTimestamp(current.getTimestamp());
					cloned.setDurationInMicros(current.getDurationInMicros());
					cloned.addData(current.getData().toString());
					cloned.setStatus(Message.SUCCESS);

					target.addChild(cloned);
					migrateMessage(stack, current, cloned, level + 1);
					shouldKeep = true;
				}
			}

			source.getChildren().clear();

			if (shouldKeep) { // add it back
				source.addChild(current);
			}
		}

		public void truncateAndFlush(Context ctx, long timestamp) {
			MessageTree tree = ctx.m_tree;
			Stack<Transaction> stack = ctx.m_stack;
			Message message = tree.getMessage();

			if (message instanceof DefaultTransaction) {
				String id = tree.getMessageId();

				if (id == null) {
					id = nextMessageId();
					tree.setMessageId(id);
				}

				String rootId = tree.getRootMessageId();
				String childId = nextMessageId();
				DefaultTransaction source = (DefaultTransaction) message;
				DefaultTransaction target = new DefaultTransaction(source.getType(), source.getName(),
						DefaultMessageManager.this);

				target.setTimestamp(source.getTimestamp());
				target.setDurationInMicros(source.getDurationInMicros());
				target.addData(source.getData().toString());
				target.setStatus(Message.SUCCESS);

				migrateMessage(stack, source, target, 1);

				for (int i = stack.size() - 1; i >= 0; i--) {
					DefaultTransaction t = (DefaultTransaction) stack.get(i);

					t.setTimestamp(timestamp);
					t.setDurationStart(System.nanoTime());
				}

				DefaultEvent next = new DefaultEvent("RemoteCall", "Next");

				next.addData(childId);
				next.setStatus(Message.SUCCESS);
				target.addChild(next);

				// tree is the parent, and m_tree is the child.
				MessageTree t = tree.copy();

				t.setMessage(target);

				ctx.m_tree.setMessageId(childId);
				ctx.m_tree.setParentMessageId(id);
				ctx.m_tree.setRootMessageId(rootId != null ? rootId : id);

				ctx.m_length = stack.size();
				ctx.m_totalDurationInMicros = ctx.m_totalDurationInMicros + target.getDurationInMicros();

				flush(t);
			}
		}

		public void validate(Transaction parent, Transaction transaction) {
			if (transaction.isStandalone()) {
				List<Message> children = transaction.getChildren();
				int len = children.size();

				for (int i = 0; i < len; i++) {
					Message message = children.get(i);

					if (message instanceof Transaction) {
						validate(transaction, (Transaction) message);
					}
				}

				if (!transaction.isCompleted() && transaction instanceof DefaultTransaction) {
					// missing transaction end, log a BadInstrument event so that
					// developer can fix the code
					markAsNotCompleted((DefaultTransaction) transaction);
				}
			} else if (!transaction.isCompleted()) {
				if (transaction instanceof DefaultForkedTransaction) {
					// link it as run away message since the forked transaction is not completed yet
					linkAsRunAway((DefaultForkedTransaction) transaction);
				} else if (transaction instanceof DefaultTaggedTransaction) {
					// link it as run away message since the forked transaction is not completed yet
					markAsRunAway(parent, (DefaultTaggedTransaction) transaction);
				}
			}
		}
	}
}