From 6d735e7471b8208a2ff83635094d34b22223b2d6 Mon Sep 17 00:00:00 2001 From: Frankie Wu Date: Fri, 24 Jun 2022 19:51:54 +0800 Subject: [PATCH] add test cases --- .../src/main/java/com/dianping/cat/Cat.java | 106 +++++----- .../component/DefaultComponentContext.java | 3 - .../component/DefaultComponentLifecycle.java | 45 ++--- .../message/context/TraceContextHelper.java | 12 +- .../test/java/com/dianping/cat/AllTests.java | 6 +- .../com/dianping/cat/CatBootstrapTest.java | 54 ++++- .../com/dianping/cat/CatEnvironmentTest.java | 96 --------- .../java/com/dianping/cat/CatInitTest.java | 125 ------------ .../com/dianping/cat/CatPerformanceTest.java | 188 ------------------ .../test/java/com/dianping/cat/CatTest.java | 52 ----- .../com/dianping/cat/ComponentTestCase.java | 3 +- .../com/dianping/cat/PerformanceTest.java | 184 +++++++++++++++++ .../cat/support/servlet/CatFilterTest.java | 5 +- .../test/resources/META-INF/app.properties | 2 +- 14 files changed, 322 insertions(+), 559 deletions(-) delete mode 100644 cat-client/src/test/java/com/dianping/cat/CatEnvironmentTest.java delete mode 100644 cat-client/src/test/java/com/dianping/cat/CatInitTest.java delete mode 100644 cat-client/src/test/java/com/dianping/cat/CatPerformanceTest.java delete mode 100644 cat-client/src/test/java/com/dianping/cat/CatTest.java create mode 100644 cat-client/src/test/java/com/dianping/cat/PerformanceTest.java diff --git a/cat-client/src/main/java/com/dianping/cat/Cat.java b/cat-client/src/main/java/com/dianping/cat/Cat.java index fe77468046..9fb7128fcd 100644 --- a/cat-client/src/main/java/com/dianping/cat/Cat.java +++ b/cat-client/src/main/java/com/dianping/cat/Cat.java @@ -22,6 +22,7 @@ import com.dianping.cat.message.Event; import com.dianping.cat.message.Heartbeat; +import com.dianping.cat.message.MessageTree; import com.dianping.cat.message.Metric; import com.dianping.cat.message.Trace; import com.dianping.cat.message.Transaction; @@ -205,9 +206,9 @@ public static void logMetricForSum(String name, double sum, int quantity) { * @param domain * domain is default, if use default config, the performance of server storage is bad。 */ - // public static void logRemoteCallClient(Context ctx) { - // logRemoteCallClient(ctx, "default"); - // } + public static void logRemoteCallClient(Context ctx) { + logRemoteCallClient(ctx, null); + } /** * logRemoteCallClient is used in rpc client @@ -217,32 +218,27 @@ public static void logMetricForSum(String name, double sum, int quantity) { * @param domain * domain is project name of rpc server name */ - // public static void logRemoteCallClient(Context ctx, String domain) { - // try { - // MessageTree tree = getManager().getThreadLocalMessageTree(); - // String messageId = tree.getMessageId(); - // - // if (messageId == null) { - // messageId = Cat.createMessageId(); - // tree.setMessageId(messageId); - // } - // - // String childId = CAT.m_factory.getNextId(domain); - // Cat.logEvent(CatClientConstants.TYPE_REMOTE_CALL, "", Event.SUCCESS, childId); - // - // String root = tree.getRootMessageId(); - // - // if (root == null) { - // root = messageId; - // } - // - // ctx.addProperty(Context.ROOT, root); - // ctx.addProperty(Context.PARENT, messageId); - // ctx.addProperty(Context.CHILD, childId); - // } catch (Exception e) { - // errorHandler(e); - // } - // } + public static void logRemoteCallClient(Context ctx, String domain) { + try { + MessageTree tree = TraceContextHelper.threadLocal().getMessageTree(); + String messageId = tree.getMessageId(); + String childId = TraceContextHelper.createMessageId(domain); + + Cat.logEvent(CatClientConstants.TYPE_REMOTE_CALL, "", Event.SUCCESS, childId); + + String root = tree.getRootMessageId(); + + if (root == null) { + root = messageId; + } + + ctx.addProperty(Context.ROOT, root); + ctx.addProperty(Context.PARENT, messageId); + ctx.addProperty(Context.CHILD, childId); + } catch (Exception e) { + errorHandler(e); + } + } /** * used in rpc server,use clild id as server message tree id. @@ -250,26 +246,26 @@ public static void logMetricForSum(String name, double sum, int quantity) { * @param ctx * ctx is rpc context ,such as duboo context , please use rpc context implement Context */ - // public static void logRemoteCallServer(Context ctx) { - // try { - // MessageTree tree = getManager().getThreadLocalMessageTree(); - // String childId = ctx.getProperty(Context.CHILD); - // String rootId = ctx.getProperty(Context.ROOT); - // String parentId = ctx.getProperty(Context.PARENT); - // - // if (parentId != null) { - // tree.setParentMessageId(parentId); - // } - // if (rootId != null) { - // tree.setRootMessageId(rootId); - // } - // if (childId != null) { - // tree.setMessageId(childId); - // } - // } catch (Exception e) { - // errorHandler(e); - // } - // } + public static void logRemoteCallServer(Context ctx) { + try { + MessageTree tree = TraceContextHelper.threadLocal().getMessageTree(); + String childId = ctx.getProperty(Context.CHILD); + String rootId = ctx.getProperty(Context.ROOT); + String parentId = ctx.getProperty(Context.PARENT); + + if (parentId != null) { + tree.setParentMessageId(parentId); + } + if (rootId != null) { + tree.setRootMessageId(rootId); + } + if (childId != null) { + tree.setMessageId(childId); + } + } catch (Exception e) { + errorHandler(e); + } + } public static void logTrace(String type, String name) { try { @@ -328,4 +324,16 @@ public static Transaction newTransaction(String type, String name) { return NullMessage.TRANSACTION; } } + + public static interface Context { + public final String ROOT = "_catRootMessageId"; + + public final String PARENT = "_catParentMessageId"; + + public final String CHILD = "_catChildMessageId"; + + public void addProperty(String key, String value); + + public String getProperty(String key); + } } diff --git a/cat-client/src/main/java/com/dianping/cat/component/DefaultComponentContext.java b/cat-client/src/main/java/com/dianping/cat/component/DefaultComponentContext.java index be0debe7bd..f36a69d04f 100644 --- a/cat-client/src/main/java/com/dianping/cat/component/DefaultComponentContext.java +++ b/cat-client/src/main/java/com/dianping/cat/component/DefaultComponentContext.java @@ -28,7 +28,6 @@ public DefaultComponentContext() { registerFactory(new SystemComponentFactory()); m_lifecycle = new DefaultComponentLifecycle(this); - m_lifecycle.initialize(this); } @Override @@ -41,8 +40,6 @@ public void dispose() { m_lifecycle.onStop(factory); } - m_lifecycle.dispose(); - m_singletons.clear(); m_factories.clear(); } diff --git a/cat-client/src/main/java/com/dianping/cat/component/DefaultComponentLifecycle.java b/cat-client/src/main/java/com/dianping/cat/component/DefaultComponentLifecycle.java index 32b01919fa..ab1ce1a3fd 100644 --- a/cat-client/src/main/java/com/dianping/cat/component/DefaultComponentLifecycle.java +++ b/cat-client/src/main/java/com/dianping/cat/component/DefaultComponentLifecycle.java @@ -1,60 +1,43 @@ package com.dianping.cat.component; -import java.util.concurrent.atomic.AtomicBoolean; - import com.dianping.cat.component.lifecycle.Disposable; import com.dianping.cat.component.lifecycle.Initializable; import com.dianping.cat.component.lifecycle.LogEnabled; import com.dianping.cat.component.lifecycle.Logger; -public class DefaultComponentLifecycle implements ComponentLifecycle, Initializable, Disposable { +public class DefaultComponentLifecycle implements ComponentLifecycle { private ComponentContext m_ctx; private Logger m_logger; - private AtomicBoolean m_initialized = new AtomicBoolean(); - public DefaultComponentLifecycle(ComponentContext ctx) { m_ctx = ctx; } - @Override - public void dispose() { - if (m_initialized.get()) { - m_logger = null; - m_initialized.set(false); + private Logger getLogger() { + // lazy load to avoid cyclically dependency resolution + if (m_logger == null) { + m_logger = m_ctx.lookup(Logger.class); } - } - @Override - public void initialize(ComponentContext ctx) { - m_initialized.set(true); - m_logger = m_ctx.lookup(Logger.class); + return m_logger; } @Override public void onStart(Object component) { - if (m_initialized.get()) { - if (component instanceof LogEnabled) { - ((LogEnabled) component).enableLogging(m_logger); - } - - if (component instanceof Initializable) { - ((Initializable) component).initialize(m_ctx); - } - } else { - throw new IllegalStateException("Component lifecycle has been shutdown!"); + if (component instanceof LogEnabled) { + ((LogEnabled) component).enableLogging(getLogger()); + } + + if (component instanceof Initializable) { + ((Initializable) component).initialize(m_ctx); } } @Override public void onStop(Object component) { - if (m_initialized.get()) { - if (component instanceof Disposable) { - ((Disposable) component).dispose(); - } - } else { - throw new IllegalStateException("Component lifecycle has been shutdown!"); + if (component instanceof Disposable) { + ((Disposable) component).dispose(); } } } diff --git a/cat-client/src/main/java/com/dianping/cat/message/context/TraceContextHelper.java b/cat-client/src/main/java/com/dianping/cat/message/context/TraceContextHelper.java index d0d371f48c..3569ea52e4 100644 --- a/cat-client/src/main/java/com/dianping/cat/message/context/TraceContextHelper.java +++ b/cat-client/src/main/java/com/dianping/cat/message/context/TraceContextHelper.java @@ -22,10 +22,20 @@ public class TraceContextHelper { public static String createMessageId() { initialize(); - + return s_factory.getNextId(); } + public static String createMessageId(String domain) { + initialize(); + + if (domain == null) { + return s_factory.getNextId(); + } else { + return s_factory.getNextId(domain); + } + } + public static TraceContext extractFrom(HttpServletRequest req) { Object ctx = req.getAttribute(CAT_MESSAGE_CONTEXT); diff --git a/cat-client/src/test/java/com/dianping/cat/AllTests.java b/cat-client/src/test/java/com/dianping/cat/AllTests.java index 22572e06e5..13284512ac 100644 --- a/cat-client/src/test/java/com/dianping/cat/AllTests.java +++ b/cat-client/src/test/java/com/dianping/cat/AllTests.java @@ -42,8 +42,6 @@ @RunWith(Suite.class) @SuiteClasses({ - CatTest.class, - CatBootstrapTest.class, /* .component */ @@ -60,11 +58,9 @@ /* .configuration */ ConfigureManagerTest.class, - CatEnvironmentTest.class, - /* .message */ MessageTest.class, - + MetricTest.class, EventTest.class, diff --git a/cat-client/src/test/java/com/dianping/cat/CatBootstrapTest.java b/cat-client/src/test/java/com/dianping/cat/CatBootstrapTest.java index 7a89bc6e27..9fb3e2279a 100644 --- a/cat-client/src/test/java/com/dianping/cat/CatBootstrapTest.java +++ b/cat-client/src/test/java/com/dianping/cat/CatBootstrapTest.java @@ -1,16 +1,60 @@ package com.dianping.cat; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -public class CatBootstrapTest { +import com.dianping.cat.configuration.ConfigureManager; + +public class CatBootstrapTest extends ComponentTestCase { + @After + public void after() { + } + + @Before + public void before() { + } + + @Test + public void testInitializeByDomain() { + Cat.getBootstrap().initializeByDomain("MyDomain"); + + ConfigureManager manager = context().lookup(ConfigureManager.class); + + Assert.assertEquals("MyDomain", manager.getDomain()); + } + @Test - public void testLazyInitialize() { - Cat.newTransaction("Type", "Name"); + public void testInitializeByDomainAndServers() { + Cat.getBootstrap().initializeByDomain("MyDomain", "server1", "server2"); + + ConfigureManager manager = context().lookup(ConfigureManager.class); + Assert.assertEquals("MyDomain", manager.getDomain()); + Assert.assertEquals(2, manager.getServers().size()); + Assert.assertEquals("server1", manager.getServers().get(0).getIp()); + Assert.assertEquals("server2", manager.getServers().get(1).getIp()); } @Test - public void testInitializeByServer() { - Cat.getBootstrap().initialize("localhost"); + public void testInitializeByServers() { + Cat.getBootstrap().initialize("server1", "server2"); + + ConfigureManager manager = context().lookup(ConfigureManager.class); + + Assert.assertEquals(2, manager.getServers().size()); + Assert.assertEquals("server1", manager.getServers().get(0).getIp()); + Assert.assertEquals("server2", manager.getServers().get(1).getIp()); + } + + @Test + public void testLazyInitialization() { + Assert.assertEquals(false, Cat.getBootstrap().isInitialized()); + + // CAT API call will trigger lazy initialization + Cat.newTransaction("Type", "Name").success().complete(); + + Assert.assertEquals(true, Cat.getBootstrap().isInitialized()); } } diff --git a/cat-client/src/test/java/com/dianping/cat/CatEnvironmentTest.java b/cat-client/src/test/java/com/dianping/cat/CatEnvironmentTest.java deleted file mode 100644 index 8df5ec3e18..0000000000 --- a/cat-client/src/test/java/com/dianping/cat/CatEnvironmentTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.dianping.cat; - -import java.io.File; - -import org.junit.Assert; -import org.junit.Test; - -import com.dianping.cat.message.Transaction; - -public class CatEnvironmentTest { - - @Test - public void setMuli() throws InterruptedException { - // Cat.enableMultiInstances(); - - for (int i = 0; i < 100; i++) { - Transaction t = Cat.newTransaction("type1", "name"); - t.complete(); - } - - Thread.sleep(1000); - } - - @Test - public void testWithoutInitialize() throws InterruptedException { - Transaction t = Cat.newTransaction("TestType", "TestName"); - - t.addData("data here"); - t.setStatus("TestStatus"); - t.complete(); - - Thread.sleep(100); - Assert.assertEquals(true, Cat.getBootstrap().isInitialized()); - Cat.destroy(); - } - - @Test - public void testWithInitialize() throws InterruptedException { - Cat.getBootstrap().initialize(new File(Cat.getCatHome(), "client.xml")); - Transaction t = Cat.newTransaction("TestType", "TestName"); - - t.addData("data here"); - t.setStatus("TestStatus"); - t.complete(); - - Thread.sleep(100); - - Assert.assertEquals(true, Cat.getBootstrap().isInitialized()); - Cat.destroy(); - } - - @Test - public void testWithNoExistGlobalConfigInitialize() throws InterruptedException { - Cat.getBootstrap().initialize(new File(Cat.getCatHome(), "clientNoExist.xml")); - Transaction t = Cat.newTransaction("TestType", "TestName"); - - t.addData("data here"); - t.setStatus("TestStatus"); - t.complete(); - - Thread.sleep(100); - - Assert.assertEquals(true, Cat.getBootstrap().isInitialized()); - Cat.destroy(); - } - - @Test - public void testJobTest() throws Exception { - Cat.getBootstrap().initialize("192.168.7.70", "192.168.7.71"); - Transaction t = Cat.newTransaction("TestType", "TestName"); - - t.addData("data here"); - t.setStatus("TestStatus"); - t.complete(); - - Thread.sleep(1000); - } -} diff --git a/cat-client/src/test/java/com/dianping/cat/CatInitTest.java b/cat-client/src/test/java/com/dianping/cat/CatInitTest.java deleted file mode 100644 index 595d53068d..0000000000 --- a/cat-client/src/test/java/com/dianping/cat/CatInitTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.dianping.cat; - -import java.util.concurrent.CountDownLatch; - -import org.junit.Test; - -import com.dianping.cat.message.Transaction; -import com.dianping.cat.support.Threads; -import com.dianping.cat.support.Threads.Task; - -public class CatInitTest { - - @Test - public void testInitCat() throws InterruptedException { - CountDownLatch latch = new CountDownLatch(100); - for (int i = 0; i < 50; i++) { - Threads.forGroup("cat").start(new InitTask(latch)); - latch.countDown(); - } - for (int i = 0; i < 50; i++) { - - Threads.forGroup("cat").start(new InitWithJobTask(latch)); - latch.countDown(); - } - - Thread.sleep(50 * 1000); - } - - public static class InitTask implements Task { - - private CountDownLatch m_latch; - - public InitTask(CountDownLatch latch) { - m_latch = latch; - } - - @Override - public void run() { - try { - m_latch.await(); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - - Transaction t = Cat.newTransaction("test", "test"); - - try { - Thread.sleep(10 * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - t.complete(); - } - - @Override - public String getName() { - return null; - } - - @Override - public void shutdown() { - - } - } - - public static class InitWithJobTask implements Task { - - private CountDownLatch m_latch; - - public InitWithJobTask(CountDownLatch latch) { - m_latch = latch; - } - - @Override - public void run() { - try { - m_latch.await(); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - - Cat.getBootstrap().initializeByDomain("cat", "127.0.0.1", "127.0.0.2"); - - Transaction t = Cat.newTransaction("test", "test"); - - try { - Thread.sleep(10 * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - t.complete(); - } - - @Override - public String getName() { - return null; - } - - @Override - public void shutdown() { - - } - } - -} diff --git a/cat-client/src/test/java/com/dianping/cat/CatPerformanceTest.java b/cat-client/src/test/java/com/dianping/cat/CatPerformanceTest.java deleted file mode 100644 index 99e76aba41..0000000000 --- a/cat-client/src/test/java/com/dianping/cat/CatPerformanceTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.dianping.cat; - -import java.io.IOException; -import java.text.DecimalFormat; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicLong; - -import com.dianping.cat.message.Transaction; -import com.dianping.cat.support.Threads; -import com.dianping.cat.support.Threads.Task; - -public class CatPerformanceTest { - - public static volatile AtomicLong m_totalTime = new AtomicLong(0); - - public static volatile AtomicLong m_bussniessTime = new AtomicLong(0); - - // 每个线程执行的cat api次数 - public static int m_perTheadExecuteTime = 10000; - - public static void autoTest() throws InterruptedException { - testGroup(1); - testGroup(2); - testGroup(5); - testGroup(50); - } - - public static void testGroup(int duration) throws InterruptedException { - test(10, duration); - test(20, duration); - test(50, duration); - test(100, duration); - test(200, duration); - test(500, duration); - } - - public static void main(String args[]) throws IOException, InterruptedException { - setUp(); - - if (args.length == 0) { - autoTest(); - } else { - int totalThreadCount = Integer.parseInt(args[0]); - int sleepTime = Integer.parseInt(args[1]); - - test(totalThreadCount, sleepTime); - } - } - - private static void test(int totalThreadCount, int sleepTime) throws InterruptedException { - System.out.println("开启压测线程个数:" + totalThreadCount + " 业务代码消耗时间:" + sleepTime + "(ms)"); - CountDownLatch latch = new CountDownLatch(totalThreadCount); - - m_totalTime = new AtomicLong(0); - m_bussniessTime = new AtomicLong(0); - - for (int index = 0; index < totalThreadCount; index++) { - Threads.forGroup("cat").start(new TestThread(index, sleepTime, latch)); - } - - latch.await(); - - System.out.println("=====打印最后结果====="); - printResult(); - System.out.println("===================="); - } - - private static void doBussniess(int avg) throws InterruptedException { - Thread.sleep(avg); - } - - public static void processWithCatApi(int index, int avg) throws InterruptedException { - for (int i = 1; i < m_perTheadExecuteTime; i++) { - long start = System.currentTimeMillis(); // 记录开始时间 - Transaction t0 = Cat.newTransaction("test", "test0"); - Transaction t1 = Cat.newTransaction("test", "test1"); - Transaction t2 = Cat.newTransaction("test", "test2"); - Transaction t3 = Cat.newTransaction("test", "test3"); - Transaction t4 = Cat.newTransaction("test", "test4"); - Transaction t5 = Cat.newTransaction("test", "test5"); - Transaction t6 = Cat.newTransaction("test", "test6"); - Transaction t7 = Cat.newTransaction("test", "test7"); - Transaction t8 = Cat.newTransaction("test", "test8"); - Transaction t9 = Cat.newTransaction("test", "test9"); - - long bussinessStart = System.currentTimeMillis(); // 记录业务开始时间 - doBussniess(avg); - long duration = System.currentTimeMillis() - bussinessStart; // 记录业务结束时间 - - t0.setStatus(Transaction.SUCCESS); - t1.setStatus(Transaction.SUCCESS); - t2.setStatus(Transaction.SUCCESS); - t3.setStatus(Transaction.SUCCESS); - t4.setStatus(Transaction.SUCCESS); - t5.setStatus(Transaction.SUCCESS); - t6.setStatus(Transaction.SUCCESS); - t7.setStatus(Transaction.SUCCESS); - t8.setStatus(Transaction.SUCCESS); - t9.setStatus(Transaction.SUCCESS); - t9.complete(); - t8.complete(); - t7.complete(); - t6.complete(); - t5.complete(); - t4.complete(); - t3.complete(); - t2.complete(); - t1.complete(); - t0.complete(); - - m_totalTime.addAndGet((System.currentTimeMillis() - start)); - m_bussniessTime.addAndGet(duration); - - if (i % 1000 == 0) { // 每次100次打印一次cat的平均消耗 - // printResult(); - } - } - } - - private static void printResult() { - double catCost = 1 - m_bussniessTime.get() * 1.0 / m_totalTime.get(); - - System.out.println( - "总时间消耗:" + m_totalTime.get() + "(ms) 业务代码消耗:" + m_bussniessTime + "(ms) CAT消耗比例:" + new DecimalFormat("0.00%") - .format(catCost)); - } - - public static void setUp() { - Transaction t = Cat.newTransaction("PerformanceTest", "PerformanceTest"); - - t.setStatus(Transaction.SUCCESS); - t.complete(); - } - - public static class TestThread implements Task { - - private int m_index; - - private int m_sleepTime; - - private CountDownLatch m_latch; - - public TestThread(int index, int sleepTime, CountDownLatch latch) { - m_index = index; - m_sleepTime = sleepTime; - m_latch = latch; - } - - @Override - public String getName() { - return null; - } - - @Override - public void run() { - try { - // 业务代码的sleep时间 - processWithCatApi(m_index, m_sleepTime); - } catch (InterruptedException e) { - e.printStackTrace(); - } - m_latch.countDown(); - } - - @Override - public void shutdown() { - - } - } -} diff --git a/cat-client/src/test/java/com/dianping/cat/CatTest.java b/cat-client/src/test/java/com/dianping/cat/CatTest.java deleted file mode 100644 index 59957ce1be..0000000000 --- a/cat-client/src/test/java/com/dianping/cat/CatTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.dianping.cat; - -import org.junit.Assert; -import org.junit.Test; - -import com.dianping.cat.message.Message; -import com.dianping.cat.message.Trace; - -public class CatTest { - - @Test - public void test() { - Throwable cause = new Throwable(); - - Cat.getBootstrap().initialize("localhost"); - - Cat.newTransaction("logTransaction", "logTransaction"); - Cat.newEvent("logEvent", "logEvent"); - Cat.newHeartbeat("logHeartbeat", "logHeartbeat"); - Cat.logError(cause); - Cat.logError("message", cause); - Cat.logTrace("logTrace", ""); - Cat.logTrace("logTrace", "", Trace.SUCCESS, "data"); - Cat.logMetricForCount("logMetricForCount"); - Cat.logMetricForCount("logMetricForCount", 4); - Cat.logMetricForDuration("logMetricForDuration", 100); - Cat.logMetricForSum("logMetricForSum", 100); - Cat.logMetricForSum("logMetricForSum", 100, 100); - Cat.logEvent("RemoteLink", "Call", Message.SUCCESS, "Cat-0a010680-384736-2061"); - Cat.logEvent("EventType", "EventName"); - - Assert.assertEquals(true, Cat.getBootstrap().isInitialized()); - } -} diff --git a/cat-client/src/test/java/com/dianping/cat/ComponentTestCase.java b/cat-client/src/test/java/com/dianping/cat/ComponentTestCase.java index e2bd2603b9..0450a284b5 100644 --- a/cat-client/src/test/java/com/dianping/cat/ComponentTestCase.java +++ b/cat-client/src/test/java/com/dianping/cat/ComponentTestCase.java @@ -17,7 +17,8 @@ protected T lookup(Class componentType) { @Before public void setUp() throws Exception { - Cat.getBootstrap(); + Cat.destroy(); + Cat.getBootstrap().testMode(); TraceContextHelper.reset(); } diff --git a/cat-client/src/test/java/com/dianping/cat/PerformanceTest.java b/cat-client/src/test/java/com/dianping/cat/PerformanceTest.java new file mode 100644 index 0000000000..02f6939177 --- /dev/null +++ b/cat-client/src/test/java/com/dianping/cat/PerformanceTest.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.dianping.cat; + +import java.io.IOException; +import java.text.DecimalFormat; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.Before; +import org.junit.Test; + +import com.dianping.cat.message.Transaction; +import com.dianping.cat.support.Threads; +import com.dianping.cat.support.Threads.Task; + +public class PerformanceTest { + private AtomicLong m_allTime = new AtomicLong(); + + private AtomicLong m_bizTime = new AtomicLong(); + + private AtomicLong m_totalMessages = new AtomicLong(); + + public static void main(String args[]) throws IOException, InterruptedException { + PerformanceTest test = new PerformanceTest(); + + if (args.length == 0) { + test.testPerformance(); + } else { + int totalThreadCount = Integer.parseInt(args[0]); + int sleepTime = Integer.parseInt(args[1]); + + test.testThreads(totalThreadCount, sleepTime); + } + } + + @Test + public void testPerformance() throws InterruptedException { + long start = System.currentTimeMillis(); + int[] durations = { 1, 2, 3, 5 }; + int[] threadCounts = { 10, 50, 100, 200, 500, 1000 }; + + for (int duration : durations) { + for (int threadCount : threadCounts) { + testThreads(threadCount, duration); + } + } + + long cost = System.currentTimeMillis() - start; + System.out.println(String.format("Total messages(%s) sent in %s ms", m_totalMessages.get(), cost)); + } + + private void testThreads(int threadCount, int duration) throws InterruptedException { + m_allTime.set(0); + m_bizTime.set(0); + + System.out.println("Start threads(" + threadCount + ") with duration(" + duration + " ms) ..."); + + ExecutorService pool = Threads.forPool().getFixedThreadPool("cat", threadCount); + CountDownLatch latch = new CountDownLatch(threadCount); + + for (int i = 0; i < threadCount; i++) { + pool.submit(new TestThread(threadCount, duration, latch)); + } + + latch.await(); + pool.shutdown(); + + double percentage = 1 - m_bizTime.get() * 1.0 / m_allTime.get(); + + System.out.println("All time used: " + m_allTime.get() + " ms, biz time used:" + m_bizTime + + " ms, CAT time used: " + (m_allTime.get() - m_bizTime.get()) + " ms, percentage: " + + new DecimalFormat("0.00%").format(percentage)); + System.out.println(); + } + + @Before + public void warmup() { + Cat.getBootstrap().testMode(); + Cat.newTransaction("PerformanceTest", "Start").success().complete(); + } + + private class TestThread implements Task { + private int m_id; + + private int m_duration; + + private AtomicBoolean m_enabled = new AtomicBoolean(true); + + private CountDownLatch m_latch; + + public TestThread(int id, int duration, CountDownLatch latch) { + m_id = id; + m_duration = duration; + m_latch = latch; + } + + private void doBiz() throws InterruptedException { + Threads.sleep(m_enabled, m_duration); + } + + private void doBizWithCat() throws InterruptedException { + long allStart = System.nanoTime(); + String name = "Test-" + m_id; + + Transaction t0 = Cat.newTransaction(name, "Test0"); + Transaction t1 = Cat.newTransaction(name, "Test1"); + Transaction t2 = Cat.newTransaction(name, "Test2"); + Transaction t3 = Cat.newTransaction(name, "Test3"); + Transaction t4 = Cat.newTransaction(name, "Test4"); + Transaction t5 = Cat.newTransaction(name, "Test5"); + Transaction t6 = Cat.newTransaction(name, "Test6"); + Transaction t7 = Cat.newTransaction(name, "Test7"); + Transaction t8 = Cat.newTransaction(name, "Test8"); + Transaction t9 = Cat.newTransaction(name, "Test9"); + + long bizStart = System.nanoTime(); + + doBiz(); + + long bizTime = System.nanoTime() - bizStart; + + t9.success().complete(); + t8.success().complete(); + t7.success().complete(); + t6.success().complete(); + t5.success().complete(); + t4.success().complete(); + t3.success().complete(); + t2.success().complete(); + t1.success().complete(); + t0.success().complete(); + + long allTime = System.nanoTime() - allStart; + + m_allTime.addAndGet(allTime / 1000000L); + m_bizTime.addAndGet(bizTime / 1000000L); + } + + @Override + public String getName() { + return getClass().getSimpleName(); + } + + @Override + public void run() { + try { + for (int i = 0; i < 1000; i++) { + if (m_enabled.get()) { + doBizWithCat(); + m_totalMessages.addAndGet(1); + } + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + m_latch.countDown(); + } + } + + @Override + public void shutdown() { + m_enabled.set(false); + } + } +} diff --git a/cat-client/src/test/java/com/dianping/cat/support/servlet/CatFilterTest.java b/cat-client/src/test/java/com/dianping/cat/support/servlet/CatFilterTest.java index 77eb181d1a..68698619b3 100644 --- a/cat-client/src/test/java/com/dianping/cat/support/servlet/CatFilterTest.java +++ b/cat-client/src/test/java/com/dianping/cat/support/servlet/CatFilterTest.java @@ -38,6 +38,7 @@ import org.junit.Test; import com.dianping.cat.Cat; +import com.dianping.cat.CatClientConstants; import com.dianping.cat.message.Message; import com.dianping.cat.message.MessageAssert; import com.dianping.cat.message.MessageAssert.HeaderAssert; @@ -106,7 +107,7 @@ public void testMode1() throws Exception { String id = TraceContextHelper.threadLocal().getMessageTree().getMessageId(); String childId = TraceContextHelper.createMessageId(); - Cat.logEvent("RemoteCall", "/mock/mode1", Message.SUCCESS, childId); + Cat.logEvent(CatClientConstants.TYPE_REMOTE_CALL, "/mock/mode1", Message.SUCCESS, childId); Assert.assertEquals("/mock/mode1", httpCall("/mock/mode1?k1=v1&k2=v2", // "x-cat-id", childId, // @@ -137,7 +138,7 @@ public void testMode1() throws Exception { TransactionAssert ta = MessageAssert.transactionBy("FilterTest").name("testMode1").success().complete(); - ta.childEvent(0).type("RemoteCall").name("/mock/mode1").withData(); + ta.childEvent(0).type(CatClientConstants.TYPE_REMOTE_CALL).name("/mock/mode1").withData(); } } diff --git a/cat-client/src/test/resources/META-INF/app.properties b/cat-client/src/test/resources/META-INF/app.properties index d7799838ca..bffddce668 100644 --- a/cat-client/src/test/resources/META-INF/app.properties +++ b/cat-client/src/test/resources/META-INF/app.properties @@ -1 +1 @@ -app.name=javacat \ No newline at end of file +app.name=cat \ No newline at end of file