index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-cpp/tests/AndroidSDKTesting/app/src/main/java/aws
Create_ds/aws-sdk-cpp/tests/AndroidSDKTesting/app/src/main/java/aws/androidsdktesting/RunSDKTests.java
package aws.androidsdktesting; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class RunSDKTests extends AppCompatActivity { class TestTask extends AsyncTask<String, Void, Boolean> { private Activity m_source; private Map< String, ArrayList< String > > m_testLibraryDependencies; void InitializeLibraryDependencies() { m_testLibraryDependencies = new HashMap< String, ArrayList< String > >(); ArrayList< String > coreDependencies = new ArrayList< String >(); coreDependencies.add("runCoreUnitTests"); m_testLibraryDependencies.put("core", coreDependencies); ArrayList< String > cloudfrontDependencies = new ArrayList< String >(); cloudfrontDependencies.add("aws-cpp-sdk-cloudfront"); cloudfrontDependencies.add("runCloudfrontIntegrationTests"); m_testLibraryDependencies.put("cloudfront", cloudfrontDependencies); ArrayList< String > cognitoidentityDependencies = new ArrayList< String >(); cognitoidentityDependencies.add("aws-cpp-sdk-cognito-identity"); cognitoidentityDependencies.add("aws-cpp-sdk-iam"); cognitoidentityDependencies.add("aws-cpp-sdk-access-management"); cognitoidentityDependencies.add("runCognitoIntegrationTests"); m_testLibraryDependencies.put("cognito-identity", cognitoidentityDependencies); ArrayList< String > dynamodbDependencies = new ArrayList< String >(); dynamodbDependencies.add("aws-cpp-sdk-dynamodb"); dynamodbDependencies.add("runDynamoDBIntegrationTests"); m_testLibraryDependencies.put("dynamodb", dynamodbDependencies); ArrayList< String > identityDependencies = new ArrayList< String >(); identityDependencies.add("aws-cpp-sdk-identity-management"); identityDependencies.add("runIdentityManagementTests"); m_testLibraryDependencies.put("identity", identityDependencies); ArrayList< String > lambdaDependencies = new ArrayList< String >(); lambdaDependencies.add("aws-cpp-sdk-kinesis"); lambdaDependencies.add("aws-cpp-sdk-lambda"); lambdaDependencies.add("aws-cpp-sdk-cognito-identity"); lambdaDependencies.add("aws-cpp-sdk-iam"); lambdaDependencies.add("aws-cpp-sdk-access-management"); lambdaDependencies.add("runLambdaManagementTests"); m_testLibraryDependencies.put("lambda", lambdaDependencies); ArrayList< String > loggingDependencies = new ArrayList< String >(); loggingDependencies.add("aws-cpp-sdk-s3"); loggingDependencies.add("aws-cpp-sdk-logging"); loggingDependencies.add("runLoggingIntegrationTests"); m_testLibraryDependencies.put("logging", loggingDependencies); ArrayList< String > redshiftDependencies = new ArrayList< String >(); redshiftDependencies.add("aws-cpp-sdk-redshift"); redshiftDependencies.add("runRedshiftIntegrationTests"); m_testLibraryDependencies.put("redshift", redshiftDependencies); ArrayList< String > s3Dependencies = new ArrayList< String >(); s3Dependencies.add("aws-cpp-sdk-s3"); s3Dependencies.add("runS3IntegrationTests"); m_testLibraryDependencies.put("s3", s3Dependencies); ArrayList< String > sqsDependencies = new ArrayList< String >(); sqsDependencies.add("aws-cpp-sdk-sqs"); sqsDependencies.add("aws-cpp-sdk-cognito-identity"); sqsDependencies.add("aws-cpp-sdk-iam"); sqsDependencies.add("aws-cpp-sdk-access-management"); sqsDependencies.add("runSqsIntegrationTests"); m_testLibraryDependencies.put("sqs", sqsDependencies); ArrayList< String > transferDependencies = new ArrayList< String >(); transferDependencies.add("aws-cpp-sdk-s3"); transferDependencies.add("aws-cpp-sdk-transfer"); transferDependencies.add("runTransferIntegrationTests"); m_testLibraryDependencies.put("transfer", transferDependencies); ArrayList< String > unifiedDependencies = new ArrayList< String >(); unifiedDependencies.add("android-unified-tests"); m_testLibraryDependencies.put("unified", unifiedDependencies); } public TestTask(Activity taskSource) { m_source = taskSource; } protected Boolean doInBackground(String... testNames) { InitializeLibraryDependencies(); String testName = testNames[ 0 ]; Log.i("AwsNativeSDK", "Running test " + testName); if(!testName.equals("unified")) { Log.i("AwsNativeSDK", "Loading common libraries "); //System.loadLibrary("c"); try { System.loadLibrary("c++_shared"); } catch (Exception e) { ; } try { System.loadLibrary("gnustl_shared"); } catch (Exception e) { ; } System.loadLibrary("log"); System.loadLibrary("aws-cpp-sdk-core"); System.loadLibrary("testing-resources"); } ArrayList< String > testLibraries = m_testLibraryDependencies.get( testName ); if(testLibraries == null) { Log.i("AwsNativeSDK", "Test " + testName + " does not exist!"); return false; } Log.i("AwsNativeSDK", "Loading test libraries "); for(String testLibraryName : testLibraries) { Log.i("AwsNativeSDK", "Loading library " + testLibraryName); System.loadLibrary(testLibraryName); } Log.i("AwsNativeSDK", "Starting tests"); boolean success = runTests((Context)m_source) == 0; if(success) { Log.i("AwsNativeSDK", "Tests Succeeded!"); } else { Log.i("AwsNativeSDK", "Tests Failed =("); } return success; } protected void onPostExecute(Boolean testsSucceeded) { Log.i("AwsNativeSDK", "Shutting down TestActivity"); m_source.finish(); } } static public native int runTests(Context context); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_run_sdktests); String testName = getIntent().getStringExtra("test"); if(testName == null) { testName = "unified"; } new TestTask(this).execute(testName); } @Override public void onDestroy() { super.onDestroy(); Log.i("AwsNativeSDK", "OnDestroy called!"); } }
2,800
0
Create_ds/servo/servo-graphite/src/test/java/com/netflix/servo/publish
Create_ds/servo/servo-graphite/src/test/java/com/netflix/servo/publish/graphite/BasicGraphiteNamingConventionTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.graphite; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.publish.JmxMetricPoller; import com.netflix.servo.publish.LocalJmxConnector; import com.netflix.servo.publish.MetricPoller; import com.netflix.servo.publish.RegexMetricFilter; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.tag.TagList; import org.testng.annotations.Test; import javax.management.ObjectName; import java.util.List; import java.util.regex.Pattern; import static com.netflix.servo.publish.BasicMetricFilter.MATCH_NONE; import static org.testng.Assert.assertEquals; public class BasicGraphiteNamingConventionTest { @Test public void testJmxNaming() throws Exception { Metric m = getOSMetric("AvailableProcessors"); GraphiteNamingConvention convention = new BasicGraphiteNamingConvention(); String name = convention.getName(m); assertEquals(name, "java.lang.OperatingSystem.AvailableProcessors"); } @Test public void testMetricNamingEmptyTags() throws Exception { Metric m = new Metric("simpleMonitor", SortedTagList.EMPTY, 0, 1000.0); GraphiteNamingConvention convention = new BasicGraphiteNamingConvention(); String name = convention.getName(m); assertEquals(name, "simpleMonitor"); } @Test public void testMetricNamingWithTags() throws Exception { TagList tagList = BasicTagList.of("instance", "GetLogs", DataSourceType.KEY, "HystrixCommand"); Metric m = new Metric("simpleMonitor", tagList, 0, 1000.0); GraphiteNamingConvention convention = new BasicGraphiteNamingConvention(); String name = convention.getName(m); assertEquals(name, "HystrixCommand.GetLogs.simpleMonitor"); } public static Metric getOSMetric(String name) throws Exception { MetricPoller poller = new JmxMetricPoller(new LocalJmxConnector(), new ObjectName("java.lang:type=OperatingSystem"), MATCH_NONE); RegexMetricFilter filter = new RegexMetricFilter(null, Pattern.compile(name), false, false); List<Metric> metrics = poller.poll(filter); assertEquals(metrics.size(), 1); return metrics.get(0); } }
2,801
0
Create_ds/servo/servo-graphite/src/test/java/com/netflix/servo/publish
Create_ds/servo/servo-graphite/src/test/java/com/netflix/servo/publish/graphite/GraphiteMetricObserverTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.graphite; import com.netflix.servo.Metric; import org.testng.annotations.Test; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import static org.testng.Assert.assertEquals; public class GraphiteMetricObserverTest { private String getLocalHostIp() throws UnknownHostException { return "127.0.0.1"; } @Test(expectedExceptions = IllegalArgumentException.class) public void testBadAddress1() throws Exception { new GraphiteMetricObserver("serverA", getLocalHostIp()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testBadAddress2() throws Exception { new GraphiteMetricObserver("serverA", "http://google.com"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testBadAddress3() throws Exception { new GraphiteMetricObserver("serverA", "socket://" + getLocalHostIp() + ":808"); } private int getAvailablePort() { try (ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } catch (final IOException e) { throw new RuntimeException(e); } } @Test public void testSuccessfulSend() throws Exception { final int port = getAvailablePort(); SocketReceiverTester receiver = new SocketReceiverTester(port); receiver.start(); String host = getLocalHostIp() + ":" + port; GraphiteMetricObserver gw = new GraphiteMetricObserver("serverA", host); try { List<Metric> metrics = new ArrayList<>(); metrics.add(BasicGraphiteNamingConventionTest.getOSMetric("AvailableProcessors")); gw.update(metrics); receiver.waitForConnected(); String[] lines = receiver.waitForLines(1); assertEquals(1, lines.length); int found = lines[0].indexOf("serverA.java.lang.OperatingSystem.AvailableProcessors"); assertEquals(found, 0); } finally { receiver.stop(); gw.stop(); } } @Test public void testReconnection() throws Exception { final int port = getAvailablePort(); SocketReceiverTester receiver = new SocketReceiverTester(port); receiver.start(); String host = getLocalHostIp() + ":" + port; GraphiteMetricObserver gw = new GraphiteMetricObserver("serverA", host); try { List<Metric> metrics = new ArrayList<>(); metrics.add(BasicGraphiteNamingConventionTest.getOSMetric("AvailableProcessors")); gw.update(metrics); receiver.waitForConnected(); String[] lines = receiver.waitForLines(1); assertEquals(1, lines.length); int found = lines[0].indexOf("serverA.java.lang.OperatingSystem.AvailableProcessors"); assertEquals(found, 0); // restarting the receiver receiver.stop(); receiver = new SocketReceiverTester(port); receiver.start(); // the first write does not trigger exception given how TCP works gw.update(metrics); assertEquals(0, gw.getFailedUpdateCount()); // the second update will fail and thus closes the connection gw.update(metrics); assertEquals(1, gw.getFailedUpdateCount()); // the third update will establish a new connection gw.update(metrics); assertEquals(1, gw.getFailedUpdateCount()); receiver.waitForConnected(); receiver.waitForLines(1); found = lines[0].indexOf("serverA.java.lang.OperatingSystem.AvailableProcessors"); assertEquals(found, 0); } finally { receiver.stop(); gw.stop(); } } }
2,802
0
Create_ds/servo/servo-graphite/src/test/java/com/netflix/servo/publish
Create_ds/servo/servo-graphite/src/test/java/com/netflix/servo/publish/graphite/SocketReceiverTester.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.graphite; import javax.net.ServerSocketFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Arrays; public class SocketReceiverTester implements Runnable { private final ServerSocket acceptor; private Socket s; private final String[] lines = new String[100]; private volatile boolean running = true; private volatile boolean connected = false; private volatile int linesRead = 0; private volatile int linesWritten = 0; public SocketReceiverTester(int port) throws IOException { ServerSocketFactory socketFactory = ServerSocketFactory.getDefault(); acceptor = socketFactory.createServerSocket(); acceptor.setReuseAddress(true); acceptor.bind(new InetSocketAddress(port)); } @Override public void run() { while (running) { try { s = acceptor.accept(); synchronized (this) { connected = true; notify(); } BufferedReader stream = new BufferedReader( new InputStreamReader(s.getInputStream(), "UTF-8")); while (running) { String line = stream.readLine(); synchronized (this) { lines[linesWritten++ % lines.length] = line; notify(); } } } catch (IOException e) { synchronized (this) { connected = false; linesWritten = 0; linesRead = 0; notify(); } } } } private Thread thread; public void start() { thread = new Thread(this); thread.start(); } public void stop() throws Exception { running = false; if (s != null) { s.close(); } acceptor.close(); thread.interrupt(); thread.join(); } public String[] waitForLines(int waitingFor) throws Exception { long start = System.currentTimeMillis(); synchronized (this) { while (linesWritten < linesRead + waitingFor) { if (!connected) { throw new IllegalArgumentException("Not connected!"); } if (System.currentTimeMillis() - start > 1000) { throw new InterruptedException("Timed out!"); } wait(100); } return Arrays.copyOfRange(lines, linesRead, linesRead + waitingFor); } } public void waitForConnected() throws Exception { long start = System.currentTimeMillis(); synchronized (this) { while (!connected) { if (System.currentTimeMillis() - start > 1000) { throw new InterruptedException("Timed out!"); } wait(100); } } } }
2,803
0
Create_ds/servo/servo-graphite/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-graphite/src/main/java/com/netflix/servo/publish/graphite/BasicGraphiteNamingConvention.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.graphite; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; /** * A basic graphite naming convention that handles both "native servo" objects * and standard JMX objects pulled out of the JMX registry. */ public class BasicGraphiteNamingConvention implements GraphiteNamingConvention { private static final String JMX_DOMAIN_KEY = "JmxDomain"; @Override public String getName(Metric metric) { MonitorConfig config = metric.getConfig(); TagList tags = config.getTags(); Tag domainTag = tags.getTag(JMX_DOMAIN_KEY); if (domainTag != null) { // jmx metric return handleJmxMetric(config, tags); } else { return handleMetric(config, tags); } } private String handleMetric(MonitorConfig config, TagList tags) { String type = cleanValue(tags.getTag(DataSourceType.KEY), false); String instanceName = cleanValue(tags.getTag("instance"), false); String name = cleanupIllegalCharacters(config.getName(), false); String statistic = cleanValue(tags.getTag("statistic"), false); StringBuilder nameBuilder = new StringBuilder(); if (type != null) { nameBuilder.append(type).append("."); } if (instanceName != null) { nameBuilder.append(instanceName).append("."); } if (name != null) { nameBuilder.append(name).append("."); } if (statistic != null) { nameBuilder.append(statistic).append("."); } // remove trailing "." nameBuilder.deleteCharAt(nameBuilder.lastIndexOf(".")); return nameBuilder.toString(); } private String handleJmxMetric(MonitorConfig config, TagList tags) { String domain = cleanValue(tags.getTag(JMX_DOMAIN_KEY), true); String type = cleanValue(tags.getTag("Jmx.type"), false); String instanceName = cleanValue(tags.getTag("Jmx.instance"), false); String name = cleanValue(tags.getTag("Jmx.name"), false); String fieldName = cleanupIllegalCharacters(config.getName(), false); StringBuilder nameBuilder = new StringBuilder(); nameBuilder.append(domain).append("."); if (type != null) { nameBuilder.append(type).append("."); } if (instanceName != null) { nameBuilder.append(instanceName).append("."); } if (name != null) { nameBuilder.append(name).append("."); } if (fieldName != null) { nameBuilder.append(fieldName).append("."); } // remove trailing "." nameBuilder.deleteCharAt(nameBuilder.lastIndexOf(".")); return nameBuilder.toString(); } private String cleanValue(Tag tag, boolean allowPeriodsInName) { if (tag == null) { return null; } return cleanupIllegalCharacters(tag.getValue(), allowPeriodsInName); } private String cleanupIllegalCharacters(String s, boolean allowPeriodsInName) { String legalName = s.replace(" ", "_"); if (!allowPeriodsInName) { legalName = legalName.replace(".", "_"); } return legalName; } }
2,804
0
Create_ds/servo/servo-graphite/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-graphite/src/main/java/com/netflix/servo/publish/graphite/GraphiteMetricObserver.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.graphite; import com.netflix.servo.Metric; import com.netflix.servo.publish.BaseMetricObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.SocketFactory; import java.io.BufferedInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.util.List; /** * Observer that shunts metrics out to the excellent monitoring backend graphite. * <p/> * Developed and tested against version 0.9.10 of graphite. * <p/> * http://graphite.wikidot.com/ */ public class GraphiteMetricObserver extends BaseMetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(GraphiteMetricObserver.class); private final GraphiteNamingConvention namingConvention; private final String serverPrefix; private final SocketFactory socketFactory = SocketFactory.getDefault(); private final URI graphiteServerURI; private Socket socket = null; /** * Creates a new instance. * * @param metricPrefix base name to attach onto each metric published * ("metricPrefix.{rest of name}". If null * this section isn't attached. This section is useful to * differentiate between multiple * nodes of the same application server in a cluster. * @param graphiteServerAddress address of the graphite data port in "host:port" format. */ public GraphiteMetricObserver(String metricPrefix, String graphiteServerAddress) { this(metricPrefix, graphiteServerAddress, new BasicGraphiteNamingConvention()); } /** * Creates a new instance. * * @param metricPrefix base name to attach onto each metric published * ("metricPrefix.{rest of name}". If null * this section isn't attached. This section is useful to * differentiate between multiple * nodes of the same application server in a cluster. * @param graphiteServerAddress address of the graphite data port in "host:port" format. * @param namingConvention naming convention to extract a graphite compatible name from * each Metric */ public GraphiteMetricObserver(String metricPrefix, String graphiteServerAddress, GraphiteNamingConvention namingConvention) { super("GraphiteMetricObserver" + metricPrefix); this.namingConvention = namingConvention; this.serverPrefix = metricPrefix; this.graphiteServerURI = parseStringAsUri(graphiteServerAddress); } /** * Stop sending metrics to the graphite server. */ public void stop() { try { if (socket != null) { socket.close(); socket = null; LOGGER.info("Disconnected from graphite server: {}", graphiteServerURI); } } catch (IOException e) { LOGGER.warn("Error Stopping", e); } } @Override public void updateImpl(List<Metric> metrics) { try { if (connectionAvailable()) { write(socket, metrics); } } catch (IOException e) { LOGGER.warn("Graphite connection failed on write", e); incrementFailedCount(); // disconnect so next time when connectionAvailable is called it can try to reconnect stop(); } } private boolean connectionAvailable() throws IOException { if (socket == null || !socket.isConnected()) { if (socket != null) { socket.close(); } socket = socketFactory.createSocket(graphiteServerURI.getHost(), graphiteServerURI.getPort()); LOGGER.info("Connected to graphite server: {}", graphiteServerURI); } return socket.isConnected(); } private void write(Socket socket, Iterable<Metric> metrics) throws IOException { PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); int count = writeMetrics(metrics, writer); boolean checkError = writer.checkError(); if (checkError) { throw new IOException("Writing to socket has failed"); } checkNoReturnedData(socket); LOGGER.debug("Wrote {} metrics to graphite", count); } private int writeMetrics(Iterable<Metric> metrics, PrintWriter writer) { int count = 0; for (Metric metric : metrics) { String publishedName = namingConvention.getName(metric); StringBuilder sb = new StringBuilder(); if (serverPrefix != null) { sb.append(serverPrefix).append("."); } sb.append(publishedName).append(" ") .append(metric.getValue().toString()) .append(" ") .append(metric.getTimestamp() / 1000); LOGGER.debug("{}", sb); writer.write(sb.append("\n").toString()); count++; } return count; } /** * the graphite protocol is a "one-way" streaming protocol and as such there is no easy way * to check that we are sending the output to the wrong place. We can aim the graphite writer * at any listening socket and it will never care if the data is being correctly handled. By * logging any returned bytes we can help make it obvious that it's talking to the wrong * server/socket. In particular if its aimed at the web port of a * graphite server this will make it print out the HTTP error message. */ private void checkNoReturnedData(Socket socket) throws IOException { BufferedInputStream reader = new BufferedInputStream(socket.getInputStream()); if (reader.available() > 0) { byte[] buffer = new byte[1000]; int toRead = Math.min(reader.available(), 1000); int read = reader.read(buffer, 0, toRead); if (read > 0) { LOGGER.warn("Data returned by graphite server when expecting no response! " + "Probably aimed at wrong socket or server. Make sure you " + "are publishing to the data port, not the dashboard port. " + "First {} bytes of response: {}", read, new String(buffer, 0, read, "UTF-8")); } } } /** * It's a lot easier to configure and manage the location of the graphite server if we combine * the ip and port into a single string. Using a "fake" transport and the ipString means we get * standard host/port parsing (including domain names, ipv4 and ipv6) for free. */ private static URI parseStringAsUri(String ipString) { try { URI uri = new URI("socket://" + ipString); if (uri.getHost() == null || uri.getPort() == -1) { throw new URISyntaxException(ipString, "URI must have host and port parts"); } return uri; } catch (URISyntaxException e) { throw (IllegalArgumentException) new IllegalArgumentException( "Graphite server address needs to be defined as {host}:{port}.").initCause(e); } } }
2,805
0
Create_ds/servo/servo-graphite/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-graphite/src/main/java/com/netflix/servo/publish/graphite/GraphiteNamingConvention.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.graphite; import com.netflix.servo.Metric; /** * We want to allow the user to override the default graphite naming convention to massage the * objects into the right shape for their graphite setup. Naming conventions could also be applied * to other observers such as the file observer in the future. */ public interface GraphiteNamingConvention { /** * Get a name from a {@link Metric}. */ String getName(Metric metric); }
2,806
0
Create_ds/servo/servo-example/src/main/java/com/netflix/servo
Create_ds/servo/servo-example/src/main/java/com/netflix/servo/example/BaseHandler.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.example; import com.google.common.io.CountingInputStream; import com.google.common.io.CountingOutputStream; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Stopwatch; import com.netflix.servo.monitor.Timer; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import java.io.IOException; /** * Abstract base class for handling HTTP requests. */ public abstract class BaseHandler implements HttpHandler { private final Timer latency = Monitors.newTimer("latency"); private final Counter bytesReceived = Monitors.newCounter("bytesReceived"); private final Counter bytesSent = Monitors.newCounter("bytesSent"); public void init() { Monitors.registerObject(this); } @Override public void handle(HttpExchange exchange) throws IOException { CountingInputStream input = new CountingInputStream(exchange.getRequestBody()); CountingOutputStream output = new CountingOutputStream(exchange.getResponseBody()); exchange.setStreams(input, output); Stopwatch stopwatch = latency.start(); try { handleImpl(exchange); } finally { stopwatch.stop(); bytesReceived.increment(input.getCount()); bytesSent.increment(output.getCount()); } } protected abstract void handleImpl(HttpExchange exchange) throws IOException; }
2,807
0
Create_ds/servo/servo-example/src/main/java/com/netflix/servo
Create_ds/servo/servo-example/src/main/java/com/netflix/servo/example/EchoHandler.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.example; import com.google.common.io.ByteStreams; import com.sun.net.httpserver.HttpExchange; import java.io.IOException; public class EchoHandler extends BaseHandler { public EchoHandler() { super(); init(); } @Override protected void handleImpl(HttpExchange exchange) throws IOException { exchange.sendResponseHeaders(200, 0); ByteStreams.copy(exchange.getRequestBody(), exchange.getResponseBody()); exchange.close(); } }
2,808
0
Create_ds/servo/servo-example/src/main/java/com/netflix/servo
Create_ds/servo/servo-example/src/main/java/com/netflix/servo/example/ExitHandler.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.example; import com.sun.net.httpserver.HttpExchange; import java.io.Closeable; import java.io.IOException; public class ExitHandler extends BaseHandler { private final Closeable server; public ExitHandler(Closeable server) { super(); this.server = server; init(); } @Override protected void handleImpl(HttpExchange exchange) throws IOException { try { exchange.sendResponseHeaders(200, 0); exchange.close(); } finally { server.close(); } } }
2,809
0
Create_ds/servo/servo-example/src/main/java/com/netflix/servo
Create_ds/servo/servo-example/src/main/java/com/netflix/servo/example/Main.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.example; import com.netflix.servo.publish.AsyncMetricObserver; import com.netflix.servo.publish.BasicMetricFilter; import com.netflix.servo.publish.CounterToRateMetricTransform; import com.netflix.servo.publish.FileMetricObserver; import com.netflix.servo.publish.JvmMetricPoller; import com.netflix.servo.publish.MetricObserver; import com.netflix.servo.publish.MetricPoller; import com.netflix.servo.publish.MonitorRegistryMetricPoller; import com.netflix.servo.publish.PollRunnable; import com.netflix.servo.publish.PollScheduler; import com.netflix.servo.publish.atlas.AtlasMetricObserver; import com.netflix.servo.publish.atlas.ServoAtlasConfig; import com.netflix.servo.publish.graphite.GraphiteMetricObserver; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.TagList; import com.sun.net.httpserver.HttpServer; import java.io.Closeable; import java.io.File; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public final class Main { private static final String CLUSTER = "nf.cluster"; private static final String NODE = "nf.node"; private static final String UNKNOWN = "unknown"; private Main() { } private static MetricObserver rateTransform(MetricObserver observer) { final long heartbeat = 2 * Config.getPollInterval(); return new CounterToRateMetricTransform(observer, heartbeat, TimeUnit.SECONDS); } private static MetricObserver async(String name, MetricObserver observer) { final long expireTime = 2000 * Config.getPollInterval(); final int queueSize = 10; return new AsyncMetricObserver(name, observer, queueSize, expireTime); } private static MetricObserver createFileObserver() { final File dir = Config.getFileObserverDirectory(); return rateTransform(new FileMetricObserver("servo-example", dir)); } private static MetricObserver createGraphiteObserver() { final String prefix = Config.getGraphiteObserverPrefix(); final String addr = Config.getGraphiteObserverAddress(); return rateTransform(async("graphite", new GraphiteMetricObserver(prefix, addr))); } private static TagList getCommonTags() { final Map<String, String> tags = new HashMap<>(); final String cluster = System.getenv("NETFLIX_CLUSTER"); tags.put(CLUSTER, (cluster == null) ? UNKNOWN : cluster); try { tags.put(NODE, InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { tags.put(NODE, UNKNOWN); } return BasicTagList.copyOf(tags); } private static MetricObserver createAtlasObserver() { final ServoAtlasConfig cfg = Config.getAtlasConfig(); final TagList common = getCommonTags(); return rateTransform(async("atlas", new AtlasMetricObserver(cfg, common))); } private static void schedule(MetricPoller poller, List<MetricObserver> observers) { final PollRunnable task = new PollRunnable(poller, BasicMetricFilter.MATCH_ALL, true, observers); PollScheduler.getInstance().addPoller(task, Config.getPollInterval(), TimeUnit.SECONDS); } private static void initMetricsPublishing() throws Exception { final List<MetricObserver> observers = new ArrayList<>(); if (Config.isFileObserverEnabled()) { observers.add(createFileObserver()); } if (Config.isAtlasObserverEnabled()) { observers.add(createAtlasObserver()); } if (Config.isGraphiteObserverEnabled()) { observers.add(createGraphiteObserver()); } PollScheduler.getInstance().start(); schedule(new MonitorRegistryMetricPoller(), observers); if (Config.isJvmPollerEnabled()) { schedule(new JvmMetricPoller(), observers); } } private static void initHttpServer() throws Exception { // Setup default endpoints final HttpServer server = HttpServer.create(); server.createContext("/echo", new EchoHandler()); // Hook to allow for graceful exit final Closeable c = () -> { PollScheduler.getInstance().stop(); server.stop(5); }; server.createContext("/exit", new ExitHandler(c)); // Bind and start server server.bind(new InetSocketAddress(Config.getPort()), 0); server.start(); } public static void main(String[] args) throws Exception { initMetricsPublishing(); initHttpServer(); } }
2,810
0
Create_ds/servo/servo-example/src/main/java/com/netflix/servo
Create_ds/servo/servo-example/src/main/java/com/netflix/servo/example/Config.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.example; import com.netflix.servo.monitor.Pollers; import com.netflix.servo.publish.atlas.ServoAtlasConfig; import java.io.File; /** * Utility class dealing with different settings used to run the examples. */ public final class Config { private Config() { } /** * Port number for the http server to listen on. */ public static int getPort() { return Integer.parseInt(System.getProperty("servo.example.port", "12345")); } /** * How frequently to poll metrics in seconds and report to observers. */ public static long getPollInterval() { return Pollers.getPollingIntervals().get(0) / 1000L; } /** * Should we report metrics to the file observer? Default is true. */ public static boolean isFileObserverEnabled() { return Boolean.valueOf(System.getProperty("servo.example.isFileObserverEnabled", "true")); } /** * Default directory for writing metrics files. Default is /tmp. */ public static File getFileObserverDirectory() { return new File(System.getProperty("servo.example.fileObserverDirectory", "/tmp")); } /** * Should we report metrics to graphite? Default is false. */ public static boolean isGraphiteObserverEnabled() { return Boolean.valueOf(System.getProperty("servo.example.isGraphiteObserverEnabled", "false")); } /** * Prefix to use when reporting data to graphite. Default is servo. */ public static String getGraphiteObserverPrefix() { return System.getProperty("servo.example.graphiteObserverPrefix", "servo"); } /** * Address for reporting to graphite. Default is localhost:2003. */ public static String getGraphiteObserverAddress() { return System.getProperty("servo.example.graphiteObserverAddress", "localhost:2003"); } /** * Should we report metrics to atlas? Default is false. */ public static boolean isAtlasObserverEnabled() { return Boolean.valueOf(System.getProperty("servo.example.isAtlasObserverEnabled", "false")); } /** * Prefix to use when reporting data to graphite. Default is servo. */ public static String getAtlasObserverUri() { return System.getProperty("servo.example.atlasObserverUri", "http://localhost:7101/api/v1/publish"); } /** * Should we poll the standard jvm mbeans? Default is true. */ public static boolean isJvmPollerEnabled() { return Boolean.valueOf(System.getProperty("servo.example.isJvmPollerEnabled", "true")); } /** * Get config for the atlas observer. */ public static ServoAtlasConfig getAtlasConfig() { return new ServoAtlasConfig() { @Override public String getAtlasUri() { return getAtlasObserverUri(); } @Override public int getPushQueueSize() { return 1000; } @Override public boolean shouldSendMetrics() { return isAtlasObserverEnabled(); } @Override public int batchSize() { return 10000; } }; } }
2,811
0
Create_ds/servo/servo-atlas/src/test/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/test/java/com/netflix/servo/publish/atlas/AtlasPrettyPrinterTest.java
package com.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.servo.Metric; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.TagList; import org.testng.annotations.Test; import java.io.StringWriter; import static org.testng.Assert.assertEquals; public class AtlasPrettyPrinterTest { @Test public void testPayload() throws Exception { TagList commonTags = BasicTagList.of("nf.app", "example", "nf.cluster", "example-main", "nf.region", "us-west-3"); Metric m1 = new Metric("foo1", BasicTagList.of("id", "ab"), 1000L, 1.0); Metric m2 = new Metric("foo2", BasicTagList.of("id", "bc", "class", "klz"), 1000L, 2.0); Metric m3 = new Metric("foo3", BasicTagList.EMPTY, 1000L, 3.0); Metric[] metrics = new Metric[] {m1, m2, m3}; JsonPayload update = new UpdateRequest(commonTags, metrics, metrics.length); JsonFactory factory = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator generator = factory.createGenerator(writer); generator.setPrettyPrinter(new AtlasPrettyPrinter()); update.toJson(generator); generator.close(); writer.close(); String expected = "{\n\"tags\":{\"nf.app\":\"example\",\"nf.cluster\":\"example-main\",\"nf.region\":\"us-west-3\"},\n\"metrics\":[\n" + "{\"tags\":{\"name\":\"foo1\",\"id\":\"ab\"},\"start\":1000,\"value\":1.0},\n" + "{\"tags\":{\"name\":\"foo2\",\"class\":\"klz\",\"id\":\"bc\"},\"start\":1000,\"value\":2.0},\n" + "{\"tags\":{\"name\":\"foo3\"},\"start\":1000,\"value\":3.0}]\n" + "}"; assertEquals(writer.toString(), expected); } }
2,812
0
Create_ds/servo/servo-atlas/src/test/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/test/java/com/netflix/servo/publish/atlas/ValidCharactersTest.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.servo.Metric; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.BasicTag; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringWriter; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertFalse; public class ValidCharactersTest { @Test public void testValidStrIsUnchanged() throws Exception { String valid = "abc09.-_"; assertEquals(ValidCharacters.toValidCharset(valid), valid); } @Test public void testInvalidStrIsFixed() throws Exception { String str = "Aabc09.-~^_ abc"; assertEquals(ValidCharacters.toValidCharset(str), "Aabc09.-____abc"); String boundaries = "\u0000\u0128\uffff"; assertEquals(ValidCharacters.toValidCharset(boundaries), "___"); } @Test public void testValidStr() throws Exception { String valid = "AZabc09.-_"; assertFalse(ValidCharacters.hasInvalidCharacters(valid)); } @Test public void testInvalidStr() throws Exception { String caret = "abc09.-_^abc"; assertTrue(ValidCharacters.hasInvalidCharacters(caret)); String tilde = "abc09.-_~abc"; assertTrue(ValidCharacters.hasInvalidCharacters(tilde)); String str = "abc09.-_ abc"; assertTrue(ValidCharacters.hasInvalidCharacters(str)); String boundaries = "\u0000\u0128\uffff"; assertTrue(ValidCharacters.hasInvalidCharacters(boundaries)); } @Test public void testValidValue() throws Exception { MonitorConfig cfg = MonitorConfig.builder("foo^bar") .withTag("nf.asg", "foo~1") .withTag("nf.cluster", "foo^1.0") .withTag("key^1.0", "val~1.0") .build(); Metric metric = new Metric(cfg, 0, 0.0); Metric fixed = ValidCharacters.toValidValue(metric); Metric expected = new Metric("foo_bar", BasicTagList.of("nf.asg", "foo~1", "nf.cluster", "foo^1.0", "key_1.0", "val_1.0"), 0, 0.0); assertEquals(fixed, expected); } private static JsonFactory factory = new JsonFactory(); static { factory.enable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); } private static String toJson(Tag tag) throws IOException { StringWriter writer = new StringWriter(); JsonGenerator generator = factory.createGenerator(writer); generator.writeStartObject(); ValidCharacters.tagToJson(generator, tag); generator.writeEndObject(); generator.close(); return writer.toString(); } @Test public void testTagToJson() throws Exception { Tag valid = new BasicTag("key", "value"); assertEquals(toJson(valid), "{\"key\":\"value\"}"); Tag invalidKey = new BasicTag("key~^a", "value"); assertEquals(toJson(invalidKey), "{\"key__a\":\"value\"}"); Tag invalidValue = new BasicTag("key", "value~^ 1"); assertEquals(toJson(invalidValue), "{\"key\":\"value___1\"}"); Tag relaxedValue = new BasicTag("nf.asg", "value~^ 1"); assertEquals(toJson(relaxedValue), "{\"nf.asg\":\"value~^_1\"}"); } }
2,813
0
Create_ds/servo/servo-atlas/src/test/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/test/java/com/netflix/servo/publish/atlas/HttpHelperTest.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import org.testng.annotations.Test; import rx.Observable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; /** * Basic tests for {@link HttpHelper}. */ public class HttpHelperTest { @Test public void testSendAll() throws Exception { List<Observable<Integer>> batches = new ArrayList<>(); int expectedSum = 0; for (int i = 1; i <= 5; ++i) { batches.add(Observable.just(i)); expectedSum += i; } HttpHelper httpHelper = new HttpHelper(null); int sent = httpHelper.sendAll(batches, expectedSum, 100L); assertEquals(sent, expectedSum); // now add an observable that should timeout batches.add(Observable.<Integer>never()); int partial = httpHelper.sendAll(batches, expectedSum, 100L); assertEquals(partial, expectedSum); } @Test public void testSendAllSlow() throws Exception { Observable<Integer> interval = Observable.interval(400, TimeUnit.MILLISECONDS).map(l -> l.intValue() + 1); // now add an observable that should timeout List<Observable<Integer>> batches = new ArrayList<>(); batches.add(interval); int expectedSum = 3; // 1 + 2 should have been received from interval for (int i = 1; i <= 5; ++i) { batches.add(Observable.just(i)); expectedSum += i; } HttpHelper httpHelper = new HttpHelper(null); int partial = httpHelper.sendAll(batches, expectedSum, 1000L); assertEquals(partial, expectedSum); } }
2,814
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/JsonPayload.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonGenerator; import java.io.IOException; /** * payload that can be serialized to json. */ public interface JsonPayload { /** * Serialize the current entity to JSON using the given generator. */ void toJson(JsonGenerator gen) throws IOException; }
2,815
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/AtlasMetricObserver.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.archaius.config.EmptyConfig; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.BasicGauge; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Gauge; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Pollers; import com.netflix.servo.monitor.Stopwatch; import com.netflix.servo.monitor.Timer; import com.netflix.servo.publish.MetricObserver; import com.netflix.servo.tag.BasicTag; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import iep.com.netflix.iep.http.BasicServerRegistry; import iep.com.netflix.iep.http.RxHttp; import iep.io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.netty.buffer.ByteBuf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; /** * Observer that forwards metrics to atlas. In addition to being MetricObserver, it also supports * a push model that sends metrics as soon as possible (asynchronously). */ public class AtlasMetricObserver implements MetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(AtlasMetricObserver.class); private static final Tag ATLAS_COUNTER_TAG = new BasicTag("atlas.dstype", "counter"); private static final Tag ATLAS_GAUGE_TAG = new BasicTag("atlas.dstype", "gauge"); private static final UpdateTasks NO_TASKS = new UpdateTasks(0, null, -1L); private static final String FILE_DATE_FORMAT = "yyyy_MM_dd_HH_mm_ss_SSS"; private final JsonFactory jsonFactory = new JsonFactory(); protected final HttpHelper httpHelper; protected final ServoAtlasConfig config; protected final long sendTimeoutMs; // in milliseconds protected final long stepMs; // in milliseconds private final Counter numMetricsTotal = Monitors.newCounter("numMetricsTotal"); private final Timer updateTimer = Monitors.newTimer("update"); private final Counter numMetricsDroppedSendTimeout = newErrCounter("numMetricsDropped", "sendTimeout"); private final Counter numMetricsDroppedQueueFull = newErrCounter("numMetricsDropped", "sendQueueFull"); private final Counter numMetricsDroppedHttpErr = newErrCounter("numMetricsDropped", "httpError"); private final Counter numMetricsSent = Monitors.newCounter("numMetricsSent"); private final TagList commonTags; private final BlockingQueue<UpdateTasks> pushQueue; @SuppressWarnings("unused") private final Gauge<Integer> pushQueueSize = new BasicGauge<>( MonitorConfig.builder("pushQueue").build(), new Callable<Integer>() { @Override public Integer call() throws Exception { return pushQueue.size(); } }); protected boolean shouldDumpPayload() { return false; } protected String getPayloadDirectory() { String tmp = System.getProperty("java.io.tmpdir"); return tmp != null ? tmp : "/tmp"; } private final Thread pushThread; private final AtomicBoolean shouldPushMetrics = new AtomicBoolean(true); /** * Create an observer that can send metrics to atlas with a given * config and list of common tags. * This method will use the default poller index of 0. */ public AtlasMetricObserver(ServoAtlasConfig config, TagList commonTags) { this(config, commonTags, 0); } /** * Create an observer that can send metrics to atlas with a given config, list of common tags, * and poller index. */ public AtlasMetricObserver(ServoAtlasConfig config, TagList commonTags, int pollerIdx) { this(config, commonTags, pollerIdx, new HttpHelper(new RxHttp(EmptyConfig.INSTANCE, new BasicServerRegistry()))); } /** * Create an atlas observer. For internal use of servo only. */ public AtlasMetricObserver(ServoAtlasConfig config, TagList commonTags, int pollerIdx, HttpHelper httpHelper) { this.httpHelper = httpHelper; this.config = config; this.stepMs = Pollers.getPollingIntervals().get(pollerIdx); this.sendTimeoutMs = stepMs * 9 / 10; this.commonTags = commonTags; pushQueue = new LinkedBlockingQueue<>(config.getPushQueueSize()); pushThread = new Thread(new PushProcessor(), "BaseAtlasMetricObserver-Push"); pushThread.setDaemon(true); pushThread.start(); } /** * Stop attempting to send metrics to atlas. * Cleans up the thread that is created by this observer. */ public void stop() { shouldPushMetrics.set(false); // since we're probably blocking on getting an element from the // push queue, interrupt the thread now pushThread.interrupt(); } protected static Counter newErrCounter(String name, String err) { return new BasicCounter(MonitorConfig.builder(name).withTag("error", err).build()); } protected static Metric asGauge(Metric m) { return new Metric(m.getConfig().withAdditionalTag(ATLAS_GAUGE_TAG), m.getTimestamp(), m.getValue()); } protected static Metric asCounter(Metric m) { return new Metric(m.getConfig().withAdditionalTag(ATLAS_COUNTER_TAG), m.getTimestamp(), m.getValue()); } protected static boolean isCounter(Metric m) { final TagList tags = m.getConfig().getTags(); final String value = tags.getValue(DataSourceType.KEY); return value != null && value.equals(DataSourceType.COUNTER.name()); } protected static boolean isGauge(Metric m) { final TagList tags = m.getConfig().getTags(); final String value = tags.getValue(DataSourceType.KEY); return value != null && value.equals(DataSourceType.GAUGE.name()); } protected static boolean isRate(Metric m) { final TagList tags = m.getConfig().getTags(); final String value = tags.getValue(DataSourceType.KEY); return DataSourceType.RATE.name().equals(value) || DataSourceType.NORMALIZED.name().equals(value); } protected static List<Metric> identifyDsTypes(List<Metric> metrics) { // since we never generate atlas.dstype = counter we can do the following: return metrics.stream().map(m -> isRate(m) ? m : asGauge(m)).collect(Collectors.toList()); } @Override public String getName() { return "atlas"; } private List<Metric> identifyCountersForPush(List<Metric> metrics) { List<Metric> transformed = new ArrayList<>(metrics.size()); for (Metric m : metrics) { Metric toAdd = m; if (isCounter(m)) { toAdd = asCounter(m); } else if (isGauge(m)) { toAdd = asGauge(m); } transformed.add(toAdd); } return transformed; } /** * Immediately send metrics to the backend. * * @param rawMetrics Metrics to be sent. Names and tags will be sanitized. */ public void push(List<Metric> rawMetrics) { List<Metric> validMetrics = ValidCharacters.toValidValues(filter(rawMetrics)); List<Metric> metrics = transformMetrics(validMetrics); LOGGER.debug("Scheduling push of {} metrics", metrics.size()); final UpdateTasks tasks = getUpdateTasks(BasicTagList.EMPTY, identifyCountersForPush(metrics)); final int maxAttempts = 5; int attempts = 1; while (!pushQueue.offer(tasks) && attempts <= maxAttempts) { ++attempts; final UpdateTasks droppedTasks = pushQueue.remove(); LOGGER.warn("Removing old push task due to queue full. Dropping {} metrics.", droppedTasks.numMetrics); numMetricsDroppedQueueFull.increment(droppedTasks.numMetrics); } if (attempts >= maxAttempts) { LOGGER.error("Unable to push update of {}", tasks); numMetricsDroppedQueueFull.increment(tasks.numMetrics); } else { LOGGER.debug("Queued push of {}", tasks); } } protected void sendNow(UpdateTasks updateTasks) { if (updateTasks.numMetrics == 0) { return; } final Stopwatch s = updateTimer.start(); int totalSent = 0; try { totalSent = httpHelper.sendAll(updateTasks.tasks, updateTasks.numMetrics, sendTimeoutMs); LOGGER.debug("Sent {}/{} metrics to atlas", totalSent, updateTasks.numMetrics); } finally { s.stop(); int dropped = updateTasks.numMetrics - totalSent; numMetricsDroppedSendTimeout.increment(dropped); } } protected boolean shouldIncludeMetric(Metric metric) { return true; } /** * Return metrics to be sent to the main atlas deployment. * Metrics will be sent if their publishing policy matches atlas and if they * will *not* be sent to the aggregation cluster. */ protected List<Metric> filter(List<Metric> metrics) { final List<Metric> filtered = metrics.stream().filter(this::shouldIncludeMetric) .collect(Collectors.toList()); LOGGER.debug("Filter: input {} metrics, output {} metrics", metrics.size(), filtered.size()); return filtered; } protected List<Metric> transformMetrics(List<Metric> metrics) { return metrics; } @Override public void update(List<Metric> rawMetrics) { List<Metric> valid = ValidCharacters.toValidValues(rawMetrics); List<Metric> metrics = identifyDsTypes(filter(valid)); List<Metric> transformed = transformMetrics(metrics); sendNow(getUpdateTasks(getCommonTags(), transformed)); } private UpdateTasks getUpdateTasks(TagList tags, List<Metric> metrics) { if (!config.shouldSendMetrics()) { LOGGER.debug("Plugin disabled or running on a dev environment. Not sending metrics."); return NO_TASKS; } if (metrics.isEmpty()) { LOGGER.debug("metrics list is empty, no data being sent to server"); return NO_TASKS; } final int numMetrics = metrics.size(); final Metric[] atlasMetrics = new Metric[metrics.size()]; metrics.toArray(atlasMetrics); numMetricsTotal.increment(numMetrics); final List<Observable<Integer>> tasks = new ArrayList<>(); final String uri = config.getAtlasUri(); LOGGER.debug("writing {} metrics to atlas ({})", numMetrics, uri); int i = 0; while (i < numMetrics) { final int remaining = numMetrics - i; final int batchSize = Math.min(remaining, config.batchSize()); final Metric[] batch = new Metric[batchSize]; System.arraycopy(atlasMetrics, i, batch, 0, batchSize); final Observable<Integer> sender = getSenderObservable(tags, batch); tasks.add(sender); i += batchSize; } assert i == numMetrics; LOGGER.debug("succeeded in creating {} observable(s) to send metrics with total size {}", tasks.size(), numMetrics); return new UpdateTasks(numMetrics * getNumberOfCopies(), tasks, System.currentTimeMillis()); } protected int getNumberOfCopies() { return 1; } private String getPayloadPrefix() { SimpleDateFormat fmt = new SimpleDateFormat(FILE_DATE_FORMAT); fmt.setTimeZone(TimeZone.getTimeZone("UTC")); return fmt.format(new Date()); } protected void dumpPayload(File out, JsonPayload payload) throws IOException { try (JsonGenerator generator = jsonFactory.createGenerator(out, JsonEncoding.UTF8)) { generator.setPrettyPrinter(new AtlasPrettyPrinter()); payload.toJson(generator); } } protected Observable<Integer> getSenderObservable(TagList tags, Metric[] batch) { JsonPayload payload = new UpdateRequest(tags, batch, batch.length); if (shouldDumpPayload()) { String prefix = getPayloadPrefix(); try { Path tempFile = Files.createTempFile(Paths.get(getPayloadDirectory()), prefix, ".json"); dumpPayload(tempFile.toFile(), payload); } catch (IOException ex) { LOGGER.debug("Ignoring error writing payload sent to atlas: {}", ex.getMessage()); } } return httpHelper.postSmile(config.getAtlasUri(), payload) .map(withBookkeeping(batch.length)); } /** * Get the list of common tags that will be added to all metrics sent by this Observer. */ protected TagList getCommonTags() { return commonTags; } /** * Utility function to map an Observable&lt;ByteBuf> to an Observable&lt;Integer> while also * updating our counters for metrics sent and errors. */ protected Func1<HttpClientResponse<ByteBuf>, Integer> withBookkeeping(final int batchSize) { return response -> { boolean ok = response.getStatus().code() == 200; if (ok) { numMetricsSent.increment(batchSize); } else { LOGGER.info("Status code: {} - Lost {} metrics", response.getStatus().code(), batchSize); numMetricsDroppedHttpErr.increment(batchSize); } return batchSize; }; } private static class UpdateTasks { private final int numMetrics; private final List<Observable<Integer>> tasks; private final long timestamp; UpdateTasks(int numMetrics, List<Observable<Integer>> tasks, long timestamp) { this.numMetrics = numMetrics; this.tasks = tasks; this.timestamp = timestamp; } @Override public String toString() { return "UpdateTasks{numMetrics=" + numMetrics + ", tasks=" + tasks + ", timestamp=" + timestamp + '}'; } } private class PushProcessor implements Runnable { @Override public void run() { while (shouldPushMetrics.get()) { try { sendNow(pushQueue.take()); } catch (InterruptedException e) { LOGGER.debug("Interrupted trying to get next UpdateTask to push"); break; } catch (Exception t) { LOGGER.info("Caught unexpected exception pushing metrics", t); } } } } }
2,816
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/ValidCharacters.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.servo.Metric; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Utility class to deal with rewriting keys/values to the character set accepted by atlas. */ public final class ValidCharacters { /** * Only allow letters, numbers, underscores, dashes and dots in our identifiers. */ private static final boolean[] CHARS_ALLOWED = new boolean[128]; private static final boolean[] CHARS_ALLOWED_GROUPS = new boolean[128]; static { CHARS_ALLOWED['.'] = true; CHARS_ALLOWED['-'] = true; CHARS_ALLOWED['_'] = true; for (char ch = '0'; ch <= '9'; ch++) { CHARS_ALLOWED[ch] = true; } for (char ch = 'A'; ch <= 'Z'; ch++) { CHARS_ALLOWED[ch] = true; } for (char ch = 'a'; ch <= 'z'; ch++) { CHARS_ALLOWED[ch] = true; } // relax rules a bit for tags describing groups System.arraycopy(CHARS_ALLOWED, 0, CHARS_ALLOWED_GROUPS, 0, CHARS_ALLOWED.length); CHARS_ALLOWED_GROUPS['^'] = true; CHARS_ALLOWED_GROUPS['~'] = true; } private ValidCharacters() { // utility class } private static boolean hasInvalidCharactersTable(boolean[] table, String str) { final int n = str.length(); for (int i = 0; i < n; i++) { final char c = str.charAt(i); if (c >= table.length || !table[c]) { return true; } } return false; } /** * Check whether a given string contains an invalid character. */ public static boolean hasInvalidCharacters(String str) { return hasInvalidCharactersTable(CHARS_ALLOWED, str); } private static String toValidCharsetTable(boolean[] table, String str) { if (hasInvalidCharactersTable(table, str)) { final int n = str.length(); final StringBuilder buf = new StringBuilder(n + 1); for (int i = 0; i < n; i++) { final char c = str.charAt(i); if (c < table.length && table[c]) { buf.append(c); } else { buf.append('_'); } } return buf.toString(); } else { return str; } } /** * Convert a given string to one where all characters are valid. */ public static String toValidCharset(String str) { return toValidCharsetTable(CHARS_ALLOWED, str); } private static final List<String> RELAXED_GROUP_KEYS = Arrays.asList("nf.asg", "nf.cluster"); /** * Return a new metric where the name and all tags are using the valid character * set. */ public static Metric toValidValue(Metric metric) { MonitorConfig cfg = metric.getConfig(); MonitorConfig.Builder cfgBuilder = MonitorConfig.builder(toValidCharset(cfg.getName())); for (Tag orig : cfg.getTags()) { final String key = orig.getKey(); if (RELAXED_GROUP_KEYS.contains(key)) { cfgBuilder.withTag(key, toValidCharsetTable(CHARS_ALLOWED_GROUPS, orig.getValue())); } else { cfgBuilder.withTag(toValidCharset(key), toValidCharset(orig.getValue())); } } cfgBuilder.withPublishingPolicy(cfg.getPublishingPolicy()); return new Metric(cfgBuilder.build(), metric.getTimestamp(), metric.getValue()); } /** * Create a new list of metrics where all metrics are using the valid character set. */ public static List<Metric> toValidValues(List<Metric> metrics) { return metrics.stream().map(ValidCharacters::toValidValue).collect(Collectors.toList()); } /** * Serialize a tag to the given JsonGenerator. */ public static void tagToJson(JsonGenerator gen, Tag tag) throws IOException { final String key = tag.getKey(); if (RELAXED_GROUP_KEYS.contains(key)) { gen.writeStringField(key, toValidCharsetTable(CHARS_ALLOWED_GROUPS, tag.getValue())); } else { gen.writeStringField(toValidCharset(tag.getKey()), toValidCharset(tag.getValue())); } } }
2,817
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/AtlasMetric.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.servo.Metric; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import com.netflix.servo.util.Objects; import com.netflix.servo.util.Preconditions; import java.io.IOException; /** * A metric that can be reported to Atlas. */ class AtlasMetric implements JsonPayload { private final MonitorConfig config; private final long start; private final double value; AtlasMetric(Metric m) { this(m.getConfig(), m.getTimestamp(), m.getNumberValue()); } AtlasMetric(MonitorConfig config, long start, Number value) { this.config = Preconditions.checkNotNull(config, "config"); this.value = Preconditions.checkNotNull(value, "value").doubleValue(); this.start = start; } MonitorConfig getConfig() { return config; } long getStartTime() { return start; } @Override public boolean equals(Object obj) { if (!(obj instanceof AtlasMetric)) { return false; } AtlasMetric m = (AtlasMetric) obj; return config.equals(m.getConfig()) && start == m.getStartTime() && Double.compare(value, m.value) == 0; } @Override public int hashCode() { return Objects.hash(config, start, value); } @Override public String toString() { return "AtlasMetric{config=" + config + ", start=" + start + ", value=" + value + '}'; } @Override public void toJson(JsonGenerator gen) throws IOException { gen.writeStartObject(); gen.writeObjectFieldStart("tags"); gen.writeStringField("name", config.getName()); for (Tag tag : config.getTags()) { ValidCharacters.tagToJson(gen, tag); } gen.writeEndObject(); gen.writeNumberField("start", start); gen.writeNumberField("value", value); gen.writeEndObject(); gen.flush(); } }
2,818
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/AtlasPrettyPrinter.java
/** * Copyright 2017 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.PrettyPrinter; import java.io.IOException; /** * A simple Jackson Pretty Printer that helps dump atlas payloads in a format that is easy to grep. */ class AtlasPrettyPrinter implements PrettyPrinter { private int nesting = 0; @Override public void writeRootValueSeparator(JsonGenerator jg) throws IOException { } @Override public void writeStartObject(JsonGenerator gen) throws IOException { gen.writeRaw('{'); if (nesting == 0) { gen.writeRaw('\n'); } ++nesting; } @Override public void writeEndObject(JsonGenerator gen, int nrOfEntries) throws IOException { --nesting; gen.writeRaw('}'); } @Override public void writeObjectEntrySeparator(JsonGenerator gen) throws IOException { gen.writeRaw(','); if (nesting <= 1) { gen.writeRaw('\n'); } } @Override public void writeObjectFieldValueSeparator(JsonGenerator gen) throws IOException { gen.writeRaw(':'); } @Override public void writeStartArray(JsonGenerator gen) throws IOException { gen.writeRaw("[\n"); } @Override public void writeEndArray(JsonGenerator gen, int nrOfValues) throws IOException { gen.writeRaw("]\n"); } @Override public void writeArrayValueSeparator(JsonGenerator gen) throws IOException { gen.writeRaw(','); if (nesting == 1) { gen.writeRaw('\n'); } } @Override public void beforeArrayValues(JsonGenerator gen) throws IOException { } @Override public void beforeObjectEntries(JsonGenerator gen) throws IOException { } }
2,819
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/BasicAtlasConfig.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; /** * A simple implementation of {@link ServoAtlasConfig} that uses system properties to get * values. */ public class BasicAtlasConfig implements ServoAtlasConfig { @Override public String getAtlasUri() { return System.getProperty("servo.atlas.uri"); } @Override public int getPushQueueSize() { String pushQueueSize = System.getProperty("servo.atlas.queueSize", "1000"); return Integer.parseInt(pushQueueSize); } @Override public boolean shouldSendMetrics() { String enabled = System.getProperty("servo.atlas.enabled", "true"); return Boolean.parseBoolean(enabled); } @Override public int batchSize() { String batch = System.getProperty("servo.atlas.batchSize", "10000"); return Integer.parseInt(batch); } }
2,820
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/HttpHelper.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.dataformat.smile.SmileFactory; import com.netflix.servo.util.Throwables; import iep.com.netflix.iep.http.RxHttp; import iep.io.reactivex.netty.protocol.http.client.HttpClientRequest; import iep.io.reactivex.netty.protocol.http.client.HttpClientResponse; import iep.io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import io.netty.buffer.ByteBuf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; import rx.exceptions.CompositeException; import rx.functions.Func1; import rx.functions.Func2; import rx.schedulers.Schedulers; import javax.inject.Inject; import javax.inject.Singleton; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Helper class to make http requests using rxhttp. For internal use of servo only. */ @Singleton public final class HttpHelper { private static final JsonFactory SMILE_FACTORY = new SmileFactory(); private static final Logger LOGGER = LoggerFactory.getLogger(HttpHelper.class); private static final String SMILE_CONTENT_TYPE = "application/x-jackson-smile"; private final RxHttp rxHttp; /** * An HTTP Response. For internal use of servo only. */ public static class Response { private int status; private byte[] body; private HttpResponseHeaders headers; /** * Get the HTTP status code. */ public int getStatus() { return status; } /** * Get the body of the response as a byte array. */ public byte[] getBody() { return Arrays.copyOf(body, body.length); } /** * Get the rxnetty {@link HttpResponseHeaders} for this response. */ public HttpResponseHeaders getHeaders() { return headers; } } /** * Create a new HttpHelper using the given {@link RxHttp} instance. */ @Inject public HttpHelper(RxHttp rxHttp) { this.rxHttp = rxHttp; } /** * Get the underlying {@link RxHttp} instance. */ public RxHttp getRxHttp() { return rxHttp; } /** * POST to the given URI the passed {@link JsonPayload}. */ public Observable<HttpClientResponse<ByteBuf>> postSmile(String uriStr, JsonPayload payload) { byte[] entity = toByteArray(SMILE_FACTORY, payload); URI uri = URI.create(uriStr); return rxHttp.post(uri, SMILE_CONTENT_TYPE, entity); } private byte[] toByteArray(JsonFactory factory, JsonPayload payload) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (JsonGenerator gen = factory.createGenerator(baos, JsonEncoding.UTF8)) { payload.toJson(gen); } baos.close(); return baos.toByteArray(); } catch (IOException e) { throw Throwables.propagate(e); } } private void logErr(String prefix, Throwable e, int sent, int total) { if (LOGGER.isWarnEnabled()) { final Throwable cause = e.getCause() != null ? e.getCause() : e; String msg = String.format("%s exception %s:%s Sent %d/%d", prefix, cause.getClass().getSimpleName(), cause.getMessage(), sent, total); LOGGER.warn(msg); if (cause instanceof CompositeException) { CompositeException ce = (CompositeException) cause; for (Throwable t : ce.getExceptions()) { LOGGER.warn(" Exception {}: {}", t.getClass().getSimpleName(), t.getMessage()); } } } } /** * Attempt to send all the batches totalling numMetrics in the allowed time. * * @return The total number of metrics sent. */ public int sendAll(Iterable<Observable<Integer>> batches, final int numMetrics, long timeoutMillis) { final AtomicBoolean err = new AtomicBoolean(false); final AtomicInteger updated = new AtomicInteger(0); LOGGER.debug("Got {} ms to send {} metrics", timeoutMillis, numMetrics); try { final CountDownLatch completed = new CountDownLatch(1); final Subscription s = Observable.mergeDelayError(Observable.from(batches)) .timeout(timeoutMillis, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.immediate()) .subscribe(updated::addAndGet, exc -> { logErr("onError caught", exc, updated.get(), numMetrics); err.set(true); completed.countDown(); }, completed::countDown); try { completed.await(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { err.set(true); s.unsubscribe(); LOGGER.warn("Timed out sending metrics. {}/{} sent", updated.get(), numMetrics); } } catch (Exception e) { err.set(true); logErr("Unexpected ", e, updated.get(), numMetrics); } if (updated.get() < numMetrics && !err.get()) { LOGGER.warn("No error caught, but only {}/{} sent.", updated.get(), numMetrics); } return updated.get(); } /** * Perform an HTTP get in the allowed time. */ public Response get(HttpClientRequest<ByteBuf> req, long timeout, TimeUnit timeUnit) { final String uri = req.getUri(); final Response result = new Response(); try { final Func1<HttpClientResponse<ByteBuf>, Observable<byte[]>> process = response -> { result.status = response.getStatus().code(); result.headers = response.getHeaders(); final Func2<ByteArrayOutputStream, ByteBuf, ByteArrayOutputStream> accumulator = (baos, bb) -> { try { bb.readBytes(baos, bb.readableBytes()); } catch (IOException e) { throw new RuntimeException(e); } return baos; }; return response.getContent() .reduce(new ByteArrayOutputStream(), accumulator) .map(ByteArrayOutputStream::toByteArray); }; result.body = rxHttp.submit(req) .flatMap(process) .subscribeOn(Schedulers.io()) .toBlocking() .toFuture() .get(timeout, timeUnit); return result; } catch (Exception e) { throw new RuntimeException("failed to get url: " + uri, e); } } }
2,821
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/ServoAtlasConfig.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; /** * Configuration for the servo to atlas interface. */ public interface ServoAtlasConfig { /** * Return the URI used to POST values to atlas. */ String getAtlasUri(); /** * Return the size of the queue to be used when pushing metrics to * the atlas backends. A value of 1000 is quite safe here, but might need * to be tweaked if attempting to send hundreds of batches per second. */ int getPushQueueSize(); /** * Whether we should send metrics to atlas. This can be used when running in a dev environment * for example to avoid affecting production metrics by dev machines. */ boolean shouldSendMetrics(); /** * The maximum size of the batch of metrics to be sent to atlas. * If attempting to send more metrics than this value, * the {@link AtlasMetricObserver} will split them into batches before sending * them to the atlas backends. * <p/> * A value of 10000 works well for most workloads. */ int batchSize(); }
2,822
0
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/UpdateRequest.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.servo.Metric; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Objects; import com.netflix.servo.util.Preconditions; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * A Request sent to the atlas-publish API. */ public final class UpdateRequest implements JsonPayload { private final TagList tags; private final List<AtlasMetric> metrics; /** * Create an UpdateRequest to be sent to atlas. * * @param tags common tags for all metrics in the request. * @param metricsToSend Array of metrics to send. * @param numMetrics How many metrics in the array metricsToSend should be sent. Note * that this value needs to be lower or equal to metricsToSend.length */ public UpdateRequest(TagList tags, Metric[] metricsToSend, int numMetrics) { Preconditions.checkArgument(metricsToSend.length > 0, "metricsToSend is empty"); Preconditions.checkArgument(numMetrics > 0 && numMetrics <= metricsToSend.length, "numMetrics is 0 or out of bounds"); this.metrics = new ArrayList<>(numMetrics); for (int i = 0; i < numMetrics; ++i) { Metric m = metricsToSend[i]; if (m.hasNumberValue()) { metrics.add(new AtlasMetric(m)); } } this.tags = tags; } TagList getTags() { return tags; } List<AtlasMetric> getMetrics() { return metrics; } @Override public boolean equals(Object obj) { if (!(obj instanceof UpdateRequest)) { return false; } UpdateRequest req = (UpdateRequest) obj; return tags.equals(req.getTags()) && metrics.equals(req.getMetrics()); } @Override public int hashCode() { return Objects.hash(tags, metrics); } @Override public String toString() { return "UpdateRequest{tags=" + tags + ", metrics=" + metrics + '}'; } @Override public void toJson(JsonGenerator gen) throws IOException { gen.writeStartObject(); // common tags gen.writeObjectFieldStart("tags"); for (Tag tag : tags) { ValidCharacters.tagToJson(gen, tag); } gen.writeEndObject(); gen.writeArrayFieldStart("metrics"); for (AtlasMetric m : metrics) { m.toJson(gen); } gen.writeEndArray(); gen.writeEndObject(); gen.flush(); } }
2,823
0
Create_ds/servo/servo-atlas/src/jmh/java/com/netflix/servo/publish
Create_ds/servo/servo-atlas/src/jmh/java/com/netflix/servo/publish/atlas/ValidCharactersBench.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish.atlas; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.infra.Blackhole; import java.util.regex.Pattern; @State(Scope.Thread) public class ValidCharactersBench { private static final Pattern INVALID_CHARS = Pattern.compile("[^a-zA-Z0-9_\\-\\.]"); static String oldRegexMethod(String str) { return INVALID_CHARS.matcher(str).replaceAll("_"); } @Threads(1) @Benchmark public void testUsingRegex(Blackhole bh) { String sourceStr = "netflix.streaming.vhs.server.pbstats.bitrate.playedSecs"; bh.consume(oldRegexMethod(sourceStr)); } @Threads(1) @Benchmark public void testNewByHand(Blackhole bh) { String sourceStr = "netflix.streaming.vhs.server.pbstats.bitrate.playedSecs"; bh.consume(ValidCharacters.toValidCharset(sourceStr)); } }
2,824
0
Create_ds/servo/servo-tomcat/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-tomcat/src/main/java/com/netflix/servo/publish/tomcat/TomcatPoller.java
/* * Copyright 2015 Netflix, Inc. * * Licensed 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.netflix.servo.publish.tomcat; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.publish.BaseMetricPoller; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; /** * Fetch Tomcat metrics from JMX. */ public class TomcatPoller extends BaseMetricPoller { private static final List<Metric> EMPTY_LIST = Collections.emptyList(); private static final Logger LOGGER = LoggerFactory.getLogger(TomcatPoller.class); private static String normalizeName(String name) { return "tomcat." + ("activeCount".equals(name) ? "currentThreadsBusy" : name); } private static Metric toMetric(long t, ObjectName name, Attribute attribute, Tag dsType) { Tag id = Tags.newTag("id", name.getKeyProperty("name")); Tag clazz = Tags.newTag("class", name.getKeyProperty("type")); TagList list = BasicTagList.of(id, clazz, dsType); return new Metric(normalizeName(attribute.getName()), list, t, attribute.getValue()); } private static Metric toGauge(long t, ObjectName name, Attribute attribute) { return toMetric(t, name, attribute, DataSourceType.GAUGE); } private static Metric toCounter(long t, ObjectName name, Attribute attribute) { return toMetric(t, name, attribute, DataSourceType.COUNTER); } private static final String[] THREAD_POOL_ATTRS = new String[]{ "maxThreads", "currentThreadCount", "currentThreadsBusy", "backlog" }; private static final String[] GLOBAL_REQ_ATTRS = new String[]{ "requestCount", "errorCount", "bytesSent", "bytesReceived", "processingTime", "maxTime" }; private static final String[] EXECUTOR_ATTRS = new String[]{ "maxThreads", "completedTaskCount", "queueSize", "poolSize", "activeCount" }; private static void addMetric(List<Metric> metrics, Metric metric) { if (metric.getNumberValue().doubleValue() >= 0.0) { final MonitorConfig c = metric.getConfig(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding {} {} {}", c.getName(), c.getTags(), metric.getNumberValue()); } metrics.add(metric); } else { LOGGER.debug("Ignoring {}", metric); } } private static void fetchRequestProcessorMetrics(long now, MBeanServer mbs, List<Metric> metrics) throws JMException { final ObjectName globalName = new ObjectName("Catalina:type=GlobalRequestProcessor,*"); final Set<ObjectName> names = mbs.queryNames(globalName, null); if (names == null) { return; } for (ObjectName name : names) { AttributeList list = mbs.getAttributes(name, GLOBAL_REQ_ATTRS); for (Attribute a : list.asList()) { // the only gauge here is maxTime addMetric(metrics, a.getName().equals("maxTime") ? toGauge(now, name, a) : toCounter(now, name, a)); } } } private static void fetchThreadPoolMetrics(long now, MBeanServer mbs, List<Metric> metrics) throws JMException { final ObjectName threadPoolName = new ObjectName("Catalina:type=ThreadPool,*"); final Set<ObjectName> names = mbs.queryNames(threadPoolName, null); if (names == null) { return; } for (ObjectName name : names) { AttributeList list = mbs.getAttributes(name, THREAD_POOL_ATTRS); // determine whether the shared threadPool is used boolean isUsed = true; for (Attribute a : list.asList()) { if (a.getName().equals("maxThreads")) { Number v = (Number) a.getValue(); isUsed = v.doubleValue() >= 0.0; break; } } if (isUsed) { // only add the attributes if the metric is used. for (Attribute a : list.asList()) { addMetric(metrics, toGauge(now, name, a)); } } } } private static void fetchExecutorMetrics(long now, MBeanServer mbs, List<Metric> metrics) throws JMException { final ObjectName executorName = new ObjectName("Catalina:type=Executor,*"); final Set<ObjectName> names = mbs.queryNames(executorName, null); if (names == null) { return; } for (ObjectName name : names) { AttributeList list = mbs.getAttributes(name, EXECUTOR_ATTRS); for (Attribute a : list.asList()) { addMetric(metrics, a.getName().equals("completedTaskCount") ? toCounter(now, name, a) : toGauge(now, name, a)); } } } List<Metric> pollImpl(long timestamp) { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); List<Metric> metrics = new ArrayList<>(); fetchThreadPoolMetrics(timestamp, mbs, metrics); fetchRequestProcessorMetrics(timestamp, mbs, metrics); fetchExecutorMetrics(timestamp, mbs, metrics); return metrics; } catch (JMException e) { logger.error("Could not get Tomcat JMX metrics", e); return EMPTY_LIST; } } /** * {@inheritDoc} */ @Override public List<Metric> pollImpl(boolean reset) { return pollImpl(System.currentTimeMillis()); } }
2,825
0
Create_ds/servo/servo-apache/src/test/java/com/netflix/servo/publish
Create_ds/servo/servo-apache/src/test/java/com/netflix/servo/publish/apache/ApacheStatusPollerTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo.publish.apache; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.testng.Assert.assertEquals; public class ApacheStatusPollerTest { private static final int OPEN_SLOTS = 20430; private static final long TIMESTAMP = 1234L; private static final int TOTAL_ACCESSES = 3020567; private static final int KBYTES = 46798223; private static final int UPTIME = 3204689; private static final double RPS = .942546; private static final double BPS = 14953.5; private static final int BPR = 15865; private static final int BUSY_WORKERS = 5; private static final int IDLE_WORKERS = 45; private static String repeat(char c, int n) { char[] result = new char[n]; Arrays.fill(result, c); return new String(result); } private static Metric metric(String name, double value, Tag metricType) { MonitorConfig config = MonitorConfig.builder(name).withTag(metricType) .withTag("class", "ApacheStatusPoller").build(); return new Metric(config, TIMESTAMP, value); } private static Metric scoreboard(String state, double value) { MonitorConfig config = MonitorConfig.builder("Scoreboard") .withTag(DataSourceType.GAUGE) .withTag("state", state) .withTag("class", "ApacheStatusPoller").build(); return new Metric(config, TIMESTAMP, value); } private static Metric counter(String name, double value) { return metric(name, value, DataSourceType.COUNTER); } private static Metric gauge(String name, double value) { return metric(name, value, DataSourceType.GAUGE); } @Test public void testParse() throws Exception { final String statusText = "Total Accesses: " + TOTAL_ACCESSES + "\n" + "Total kBytes: " + KBYTES + "\n" + "CPULoad: .044688\n" + "Uptime: " + UPTIME + "\n" + "ReqPerSec: " + RPS + "\n" + "BytesPerSec: " + BPS + "\n" + "BytesPerReq: " + BPR + "\n" + "BusyWorkers: " + BUSY_WORKERS + "\n" + "IdleWorkers: " + IDLE_WORKERS + "\n" + "Scoreboard: __________________K___W_K_____K______________K____" + repeat('.', OPEN_SLOTS) + "\n"; ApacheStatusPoller.StatusFetcher fetcher = () -> new ByteArrayInputStream(statusText.getBytes("UTF-8")); ApacheStatusPoller poller = new ApacheStatusPoller(fetcher); List<Metric> metrics = poller.pollImpl(TIMESTAMP); Metric accesses = counter("Total_Accesses", TOTAL_ACCESSES); Metric kBytes = counter("Total_kBytes", KBYTES); Metric uptime = counter("Uptime", UPTIME); List<Metric> counters = UnmodifiableList.of(accesses, kBytes, uptime); Metric busyWorkers = gauge("BusyWorkers", BUSY_WORKERS); Metric idleWorkers = gauge("IdleWorkers", IDLE_WORKERS); List<Metric> gauges = UnmodifiableList.of(busyWorkers, idleWorkers); Metric waitingForConnection = scoreboard("WaitingForConnection", 45.0); Metric startingUp = scoreboard("StartingUp", 0.0); Metric readingRequest = scoreboard("ReadingRequest", 0.0); Metric sendingReply = scoreboard("SendingReply", 1.0); Metric keepalive = scoreboard("Keepalive", 4.0); Metric dnsLookup = scoreboard("DnsLookup", 0.0); Metric closingConnection = scoreboard("ClosingConnection", 0.0); Metric logging = scoreboard("Logging", 0.0); Metric gracefullyFinishing = scoreboard("GracefullyFinishing", 0.0); Metric idleCleanupOfWorker = scoreboard("IdleCleanupOfWorker", 0.0); Metric unknownState = scoreboard("UnknownState", 0.0); List<Metric> scoreboard = UnmodifiableList.of(waitingForConnection, startingUp, readingRequest, sendingReply, keepalive, dnsLookup, closingConnection, logging, gracefullyFinishing, idleCleanupOfWorker, unknownState); List<Metric> expected = new ArrayList<>(); expected.addAll(counters); expected.addAll(gauges); expected.addAll(scoreboard); assertEquals(metrics, expected); } @Test public void testParseNewFormat() throws Exception { final String statusText = "localhost\n" + "ServerVersion: Apache/2.4.16 (Ubuntu)\n" + "ServerMPM: worker\n" + "Server Built: 2015-09-08T00:00:00\n" + "CurrentTime: Tuesday, 08-Sep-2015 21:07:08 UTC\n" + "RestartTime: Tuesday, 08-Sep-2015 19:51:38 UTC\n" + "ParentServerConfigGeneration: 1\n" + "ParentServerMPMGeneration: 0\n" + "ServerUptimeSeconds: \n" + "ServerUptime: 1 hour 15 minutes 29 seconds\n" + "Load1: 0.04\n" + "Load5: 0.03\n" + "Load15: 0.05\n" + "Total Accesses: " + TOTAL_ACCESSES + "\n" + "Total kBytes: " + KBYTES + "\n" + "CPUUser: .36\n" + "CPUSystem: .26\n" + "CPUChildrenUser: 0\n" + "CPUChildrenSystem: 0\n" + "CPULoad: .044688\n" + "Uptime: " + UPTIME + "\n" + "ReqPerSec: " + RPS + "\n" + "BytesPerSec: " + BPS + "\n" + "BytesPerReq: " + BPR + "\n" + "BusyWorkers: " + BUSY_WORKERS + "\n" + "IdleWorkers: " + IDLE_WORKERS + "\n" + "Scoreboard: __________________K___W_K_____K______________K____" + repeat('.', OPEN_SLOTS) + "\n"; ApacheStatusPoller.StatusFetcher fetcher = () -> new ByteArrayInputStream(statusText.getBytes("UTF-8")); ApacheStatusPoller poller = new ApacheStatusPoller(fetcher); List<Metric> metrics = poller.pollImpl(TIMESTAMP); Metric accesses = counter("Total_Accesses", TOTAL_ACCESSES); Metric kBytes = counter("Total_kBytes", KBYTES); Metric uptime = counter("Uptime", UPTIME); List<Metric> counters = UnmodifiableList.of(accesses, kBytes, uptime); Metric busyWorkers = gauge("BusyWorkers", BUSY_WORKERS); Metric idleWorkers = gauge("IdleWorkers", IDLE_WORKERS); List<Metric> gauges = UnmodifiableList.of(busyWorkers, idleWorkers); Metric waitingForConnection = scoreboard("WaitingForConnection", 45.0); Metric startingUp = scoreboard("StartingUp", 0.0); Metric readingRequest = scoreboard("ReadingRequest", 0.0); Metric sendingReply = scoreboard("SendingReply", 1.0); Metric keepalive = scoreboard("Keepalive", 4.0); Metric dnsLookup = scoreboard("DnsLookup", 0.0); Metric closingConnection = scoreboard("ClosingConnection", 0.0); Metric logging = scoreboard("Logging", 0.0); Metric gracefullyFinishing = scoreboard("GracefullyFinishing", 0.0); Metric idleCleanupOfWorker = scoreboard("IdleCleanupOfWorker", 0.0); Metric unknownState = scoreboard("UnknownState", 0.0); List<Metric> scoreboard = UnmodifiableList.of(waitingForConnection, startingUp, readingRequest, sendingReply, keepalive, dnsLookup, closingConnection, logging, gracefullyFinishing, idleCleanupOfWorker, unknownState); List<Metric> expected = new ArrayList<>(); expected.addAll(counters); expected.addAll(gauges); expected.addAll(scoreboard); assertEquals(metrics, expected); } }
2,826
0
Create_ds/servo/servo-apache/src/main/java/com/netflix/servo/publish
Create_ds/servo/servo-apache/src/main/java/com/netflix/servo/publish/apache/ApacheStatusPoller.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo.publish.apache; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.publish.BaseMetricPoller; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.Tags; import com.netflix.servo.util.UnmodifiableList; import com.netflix.servo.util.UnmodifiableSet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Base class for simple pollers that do not benefit from filtering in advance. * Sub-classes implement {@link #pollImpl} to return a list and all filtering * will be taken care of by the provided implementation of {@link #poll}. */ public class ApacheStatusPoller extends BaseMetricPoller { private final StatusFetcher fetcher; private static final List<Metric> EMPTY_LIST = Collections.emptyList(); /** * Mechanism used to fetch a status page. */ public interface StatusFetcher { /** * Return the apache status page as an {@link InputStream}. */ InputStream fetchStatus() throws IOException; } /** * Simple class to fetch a status page using the {@link java.net.URL} class. */ public static class URLStatusFetcher implements StatusFetcher { private final URL url; /** * Fetch an apache status page using the given URL passed as a String. */ public URLStatusFetcher(String url) throws MalformedURLException { this(new URL(url)); } /** * Fetch an apache status page using the given URL. */ public URLStatusFetcher(URL url) { this.url = url; } @Override public InputStream fetchStatus() throws IOException { final URLConnection con = url.openConnection(); con.setConnectTimeout(1000); con.setReadTimeout(2000); return con.getInputStream(); } } private static final class StatusPageParserUtil { private StatusPageParserUtil() { // utility class } private static final Pattern INVALID_CHARS = Pattern.compile("[^a-zA-Z0-9_\\-\\.]"); private static final Pattern STAT_LINE = Pattern.compile("^([^:]+): ([.\\d]+)$"); private static final Pattern SCOREBOARD_LINE = Pattern.compile("^Scoreboard: (\\S+)$"); private static final char[] SCOREBOARD_CHARS = { '_', 'S', 'R', 'W', 'K', 'D', 'C', 'L', 'G', 'I', '.', '*'}; private static final Tag CLASS_TAG = Tags.newTag("class", "ApacheStatusPoller"); /** * Metrics that should be included. */ private static final Set<String> WHITELISTED_METRICS = UnmodifiableSet.of("Total_Accesses", "Total_kBytes", "Uptime", "BusyWorkers", "IdleWorkers", "ConnsTotal", "ConnsAsyncWriting", "ConnsAsyncKeepAlive", "ConnsAsyncClosing"); private static final int ASCII_CHARS = 128; private static final String SCOREBOARD = "Scoreboard"; private static String getScoreboardName(char c) { switch (c) { case '_': return "WaitingForConnection"; case 'S': return "StartingUp"; case 'R': return "ReadingRequest"; case 'W': return "SendingReply"; case 'K': return "Keepalive"; case 'D': return "DnsLookup"; case 'C': return "ClosingConnection"; case 'L': return "Logging"; case 'G': return "GracefullyFinishing"; case 'I': return "IdleCleanupOfWorker"; case '.': return "OpenSlotWithNoCurrentProcess"; default: return "UnknownState"; } } static List<Metric> parseStatLine(String line, long timestamp) { final Matcher m = STAT_LINE.matcher(line); if (!m.matches()) { return EMPTY_LIST; } final String name = INVALID_CHARS.matcher(m.group(1)).replaceAll("_"); if (!WHITELISTED_METRICS.contains(name)) { return EMPTY_LIST; } final double value = Double.parseDouble(m.group(2)); final Tag metricType = (name.startsWith("Total") || name.startsWith("Uptime")) ? DataSourceType.COUNTER : DataSourceType.GAUGE; final MonitorConfig monitorConfig = MonitorConfig.builder(name) .withTag(metricType) .withTag(CLASS_TAG) .build(); Metric metric = new Metric(monitorConfig, timestamp, value); return UnmodifiableList.of(metric); } /* * "_" Waiting for Connection, * "S" Starting up, * "R" Reading Request, * "W" Sending Reply, * "K" Keepalive (read), * "D" DNS Lookup, * "C" Closing connection, * "L" Logging, * "G" Gracefully finishing, * "I" Idle cleanup of worker, * ." Open slot with no current process (ignored) */ static List<Metric> parseScoreboardLine(String line, long timestamp) { final Matcher m = SCOREBOARD_LINE.matcher(line); if (!m.matches()) { return EMPTY_LIST; } final char[] scoreboard = m.group(1).toCharArray(); final double[] tally = new double[ASCII_CHARS]; for (final char item : SCOREBOARD_CHARS) { tally[item] = 0; } for (final char item : scoreboard) { final int idx = item % ASCII_CHARS; tally[idx]++; } final List<Metric> scoreboardMetrics = new ArrayList<>(); for (final char item : SCOREBOARD_CHARS) { if (item == '.') { // Open slots are not particularly useful to track continue; } final double value = tally[item]; final String state = getScoreboardName(item); final MonitorConfig monitorConfig = MonitorConfig.builder(SCOREBOARD) .withTag(DataSourceType.GAUGE) .withTag(CLASS_TAG) .withTag("state", state) .build(); final Metric metric = new Metric(monitorConfig, timestamp, value); scoreboardMetrics.add(metric); } return Collections.unmodifiableList(scoreboardMetrics); } static List<Metric> parse(InputStream input, long timestamp) throws IOException { final List<Metric> metrics = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"))) { String line = reader.readLine(); while (line != null) { if (line.startsWith(SCOREBOARD)) { metrics.addAll(parseScoreboardLine(line, timestamp)); } else { metrics.addAll(parseStatLine(line, timestamp)); } line = reader.readLine(); } } return Collections.unmodifiableList(metrics); } } /** * Create a new ApacheStatusPoller with a given mechanism to fetch the status page. * * @param fetcher The {@link StatusFetcher} that will be used to refresh the metrics. */ public ApacheStatusPoller(StatusFetcher fetcher) { super(); this.fetcher = fetcher; } List<Metric> pollImpl(long timestamp) { try { try (InputStream statusStream = fetcher.fetchStatus()) { return StatusPageParserUtil.parse(statusStream, timestamp); } } catch (IOException e) { logger.error("Could not fetch status page", e); return EMPTY_LIST; } } /** * {@inheritDoc} */ @Override public List<Metric> pollImpl(boolean reset) { return pollImpl(System.currentTimeMillis()); } }
2,827
0
Create_ds/servo/servo-core/src/test/java/com/netflix
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/MetricTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.tag.TagList; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; public class MetricTest { private final TagList tags1 = SortedTagList.builder().withTag("cluster", "foo") .withTag("asg", "foo-v000").build(); private final TagList tags2 = SortedTagList.builder().withTag("cluster", "foo") .withTag("asg", "foo-v001").build(); @Test(expectedExceptions = NullPointerException.class) public void testNullName() throws Exception { long now = System.currentTimeMillis(); new Metric(null, tags1, now, 42); } @Test public void testNullTags() throws Exception { long now = System.currentTimeMillis(); Metric m = new Metric("a", null, now, 42); assertEquals(m.getConfig(), new MonitorConfig.Builder("a").build()); } @Test(expectedExceptions = NullPointerException.class) public void testNullValue() throws Exception { long now = System.currentTimeMillis(); new Metric("a", tags1, now, null); } @Test public void testAccessors() throws Exception { long now = System.currentTimeMillis(); Metric m1 = new Metric("a", tags1, now, 42); assertEquals(m1.getConfig(), new MonitorConfig.Builder("a").withTags(tags1).build()); assertEquals(m1.getTimestamp(), now); assertEquals(m1.getValue(), 42); } @Test public void testEquals() throws Exception { long now = System.currentTimeMillis(); Metric m1 = new Metric("a", tags1, now, 42); Metric m2 = new Metric("a", tags2, now, 42); Metric m3 = new Metric("a", tags1, now, 42); assertNotNull(m1); assertFalse(m1.toString().equals(m2.toString())); assertTrue(m1.equals(m1)); assertFalse(m1.equals(m2)); assertTrue(m1.equals(m3)); } @Test public void testHashCode() throws Exception { long now = System.currentTimeMillis(); Metric m1 = new Metric("a", tags1, now, 42); Metric m2 = new Metric("a", tags2, now, 42); Metric m3 = new Metric("a", tags1, now, 42); assertTrue(m1.hashCode() == m1.hashCode()); assertTrue(m1.hashCode() != m2.hashCode()); assertTrue(m1.hashCode() == m3.hashCode()); } }
2,828
0
Create_ds/servo/servo-core/src/test/java/com/netflix
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/DefaultMonitorRegistryTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo; import com.netflix.servo.jmx.ObjectNameMapper; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.MonitorConfig; import org.testng.annotations.Test; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.Properties; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class DefaultMonitorRegistryTest { @Test public void testCustomJmxObjectMapper() { Properties props = new Properties(); props.put("com.netflix.servo.DefaultMonitorRegistry.registryClass", "com.netflix.servo.jmx.JmxMonitorRegistry"); props.put("com.netflix.servo.DefaultMonitorRegistry.jmxMapperClass", "com.netflix.servo.DefaultMonitorRegistryTest$ChangeDomainMapper"); DefaultMonitorRegistry registry = new DefaultMonitorRegistry(props); BasicCounter counter = new BasicCounter( new MonitorConfig.Builder("testCustomJmxObjectMapper").build()); registry.register(counter); ObjectName expectedName = new ChangeDomainMapper().createObjectName("com.netflix.servo", counter); assertEquals(expectedName.getDomain(), "com.netflix.servo.Renamed"); assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered(expectedName)); } @Test public void testInvalidMapperDefaults() { Properties props = new Properties(); props.put("com.netflix.servo.DefaultMonitorRegistry.registryClass", "com.netflix.servo.jmx.JmxMonitorRegistry"); props.put("com.netflix.servo.DefaultMonitorRegistry.jmxMapperClass", "com.my.invalid.class"); DefaultMonitorRegistry registry = new DefaultMonitorRegistry(props); BasicCounter counter = new BasicCounter( new MonitorConfig.Builder("testInvalidMapperDefaults").build()); registry.register(counter); ObjectName expectedName = ObjectNameMapper.DEFAULT.createObjectName("com.netflix.servo", counter); assertEquals(expectedName.getDomain(), "com.netflix.servo"); assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered(expectedName)); } public static class ChangeDomainMapper implements ObjectNameMapper { @Override public ObjectName createObjectName(String domain, Monitor<?> monitor) { return ObjectNameMapper.DEFAULT.createObjectName(domain + ".Renamed", monitor); } } }
2,829
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/BucketTimerTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.util.UnmodifiableSet; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; public class BucketTimerTest extends AbstractMonitorTest<BucketTimer> { @Override public BucketTimer newInstance(String name) { return new BucketTimer( MonitorConfig.builder(name).build(), new BucketConfig.Builder().withBuckets(new long[]{10L, 20L}).build() ); } @Test public void testRecord() throws Exception { BucketTimer c = newInstance("foo"); Map<String, Number> expectedValues; expectedValues = new HashMap<>(); expectedValues.put("totalTime", 0L); expectedValues.put("min", 0L); expectedValues.put("max", 0L); expectedValues.put("bucket=10ms", 0L); expectedValues.put("bucket=20ms", 0L); expectedValues.put("bucket=overflow", 0L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 0L); c.record(40); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 40L); expectedValues.put("min", 40L); expectedValues.put("max", 40L); expectedValues.put("bucket=10ms", 0L); expectedValues.put("bucket=20ms", 0L); expectedValues.put("bucket=overflow", 1L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 1L); c.record(10); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 50L); expectedValues.put("min", 10L); expectedValues.put("max", 40L); expectedValues.put("bucket=10ms", 1L); expectedValues.put("bucket=20ms", 0L); expectedValues.put("bucket=overflow", 1L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 2L); c.record(5); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 55L); expectedValues.put("min", 5L); expectedValues.put("max", 40L); expectedValues.put("bucket=10ms", 2L); expectedValues.put("bucket=20ms", 0L); expectedValues.put("bucket=overflow", 1L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 3L); c.record(20); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 75L); expectedValues.put("min", 5L); expectedValues.put("max", 40L); expectedValues.put("bucket=10ms", 2L); expectedValues.put("bucket=20ms", 1L); expectedValues.put("bucket=overflow", 1L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 4L); c.record(125); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 200L); expectedValues.put("min", 5L); expectedValues.put("max", 125L); expectedValues.put("bucket=10ms", 2L); expectedValues.put("bucket=20ms", 1L); expectedValues.put("bucket=overflow", 2L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 5L); } @Test public void testRecordDifferentUnits() throws Exception { BucketTimer c = new BucketTimer( MonitorConfig.builder("foo").build(), new BucketConfig.Builder().withBuckets(new long[]{10000L, 20000L}).withTimeUnit(TimeUnit.NANOSECONDS).build(), TimeUnit.MICROSECONDS );; Map<String, Number> expectedValues; expectedValues = new HashMap<>(); expectedValues.put("totalTime", 0L); expectedValues.put("min", 0L); expectedValues.put("max", 0L); expectedValues.put("bucket=10000ns", 0L); expectedValues.put("bucket=20000ns", 0L); expectedValues.put("bucket=overflow", 0L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 0L); c.record(40); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 40L); expectedValues.put("min", 40L); expectedValues.put("max", 40L); expectedValues.put("bucket=10000ns", 0L); expectedValues.put("bucket=20000ns", 0L); expectedValues.put("bucket=overflow", 1L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 1L); c.record(10); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 50L); expectedValues.put("min", 10L); expectedValues.put("max", 40L); expectedValues.put("bucket=10000ns", 1L); expectedValues.put("bucket=20000ns", 0L); expectedValues.put("bucket=overflow", 1L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 2L); c.record(5); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 55L); expectedValues.put("min", 5L); expectedValues.put("max", 40L); expectedValues.put("bucket=10000ns", 2L); expectedValues.put("bucket=20000ns", 0L); expectedValues.put("bucket=overflow", 1L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 3L); c.record(20); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 75L); expectedValues.put("min", 5L); expectedValues.put("max", 40L); expectedValues.put("bucket=10000ns", 2L); expectedValues.put("bucket=20000ns", 1L); expectedValues.put("bucket=overflow", 1L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 4L); c.record(125); expectedValues = new HashMap<>(); expectedValues.put("totalTime", 200L); expectedValues.put("min", 5L); expectedValues.put("max", 125L); expectedValues.put("bucket=10000ns", 2L); expectedValues.put("bucket=20000ns", 1L); expectedValues.put("bucket=overflow", 2L); assertMonitors(c.getMonitors(), expectedValues); assertEquals(c.getCount(0).longValue(), 5L); } private void assertMonitors(List<Monitor<?>> monitors, Map<String, Number> expectedValues) { Set<String> exclude = UnmodifiableSet.of("count", "min", "max"); String[] namespaces = new String[]{"statistic", "servo.bucket"}; for (Monitor<?> monitor : monitors) { for (String namespace : namespaces) { final String tag = monitor.getConfig().getTags().getValue(namespace); if (tag != null && !exclude.contains(tag)) { final Number actual = (Number) monitor.getValue(); final Number expected = expectedValues.get(tag); assertEquals(actual, expected, namespace + "." + tag); } } } } @Test public void testEqualsCount() throws Exception { BucketTimer c1 = newInstance("foo"); BucketTimer c2 = newInstance("foo"); assertEquals(c1, c2); c1.record(42); assertNotEquals(c1, c2); c2.record(42); assertEquals(c1, c2); c1.record(11); assertNotEquals(c1, c2); c2.record(11); assertEquals(c1, c2); } @Test public void testHashCode() throws Exception { BucketTimer c1 = newInstance("foo"); BucketTimer c2 = newInstance("foo"); assertEquals(c1.hashCode(), c2.hashCode()); c1.record(42); assertNotEquals(c1.hashCode(), c2.hashCode()); c2.record(42); assertEquals(c1.hashCode(), c2.hashCode()); c1.record(11); assertNotEquals(c1.hashCode(), c2.hashCode()); c2.record(11); assertEquals(c1.hashCode(), c2.hashCode()); } }
2,830
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/DurationTimerTest.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.util.ManualClock; import org.testng.annotations.Test; import java.util.List; import static org.testng.AssertJUnit.assertEquals; public class DurationTimerTest extends AbstractMonitorTest { @Override public Monitor<?> newInstance(String name) { return new DurationTimer(MonitorConfig.builder(name).build()); } @SuppressWarnings("unchecked") private static Monitor<Long> getDuration(List<Monitor<?>> monitors) { return (Monitor<Long>) monitors.get(0); } @SuppressWarnings("unchecked") private static Monitor<Long> getActiveTasks(List<Monitor<?>> monitors) { return (Monitor<Long>) monitors.get(1); } @Test public void testGetMonitors() throws Exception { List<Monitor<?>> monitors = ((CompositeMonitor<?>) newInstance("test")).getMonitors(); assertEquals(monitors.size(), 2); Monitor<Long> duration = getDuration(monitors); Monitor<Long> activeTasks = getActiveTasks(monitors); assertEquals(duration.getConfig().getName(), "test.duration"); assertEquals(activeTasks.getConfig().getName(), "test.activeTasks"); assertEquals(duration.getValue().longValue(), 0L); assertEquals(activeTasks.getValue().longValue(), 0L); } @Test public void testTimer() throws Exception { ManualClock clock = new ManualClock(0); DurationTimer timer = new DurationTimer(MonitorConfig.builder("test").build(), clock); Stopwatch s = timer.start(); clock.set(10 * 1000L); assertEquals(10, s.getDuration()); Monitor<Long> duration = getDuration(timer.getMonitors()); Monitor<Long> activeTasks = getActiveTasks(timer.getMonitors()); assertEquals(10L, duration.getValue().longValue()); assertEquals(1L, activeTasks.getValue().longValue()); clock.set(20 * 1000L); assertEquals(20L, duration.getValue().longValue()); assertEquals(1L, activeTasks.getValue().longValue()); Stopwatch anotherTask = timer.start(); assertEquals(20L, duration.getValue().longValue()); assertEquals(2L, activeTasks.getValue().longValue()); clock.set(30 * 1000L); assertEquals(40L, duration.getValue().longValue()); // 30s for the first, 10s for the second assertEquals(2L, activeTasks.getValue().longValue()); s.stop(); assertEquals(10L, duration.getValue().longValue()); // 30s for the first, 10s for the second assertEquals(1L, activeTasks.getValue().longValue()); anotherTask.stop(); assertEquals(0L, duration.getValue().longValue()); assertEquals(0L, activeTasks.getValue().longValue()); } @Test public void testValue() throws Exception { ManualClock clock = new ManualClock(0L); DurationTimer timer = new DurationTimer(MonitorConfig.builder("test").build(), clock); assertEquals(0L, timer.getValue().longValue()); Stopwatch s = timer.start(); clock.set(10 * 1000L); assertEquals(10L, timer.getValue().longValue()); s.stop(); assertEquals(0L, timer.getValue().longValue()); } @Test public void testReset() throws Exception { ManualClock clock = new ManualClock(0L); DurationTimer timer = new DurationTimer(MonitorConfig.builder("test").build(), clock); Stopwatch s = timer.start(); clock.set(10 * 1000L); assertEquals(10L, timer.getValue().longValue()); s.reset(); assertEquals(0L, timer.getValue().longValue()); clock.set(20 * 1000L); assertEquals(10L, timer.getValue().longValue()); } }
2,831
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/StatsMonitorTest.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.stats.StatsConfig; import com.netflix.servo.util.ManualClock; import org.testng.annotations.Test; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class StatsMonitorTest { @Test public void testExpiration() throws Exception { ManualClock clock = new ManualClock(0); StatsMonitor monitor = new StatsMonitor(MonitorConfig.builder("m1").build(), new StatsConfig.Builder().withComputeFrequencyMillis(1).build(), Executors.newSingleThreadScheduledExecutor(), "total", false, clock); clock.set(TimeUnit.MINUTES.toMillis(20)); monitor.computeStats(); assertTrue(monitor.isExpired()); monitor.record(42); monitor.computeStats(); assertFalse(monitor.isExpired()); } }
2,832
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/LongGaugeTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class LongGaugeTest extends AbstractMonitorTest<LongGauge> { @Override public LongGauge newInstance(String name) { return new LongGauge(MonitorConfig.builder(name).build()); } @Test public void testSet() throws Exception { LongGauge gauge = newInstance("test"); gauge.set(10L); assertEquals(gauge.getValue().longValue(), 10L); } @Test public void testGetValue() throws Exception { LongGauge gauge = newInstance("test"); assertEquals(gauge.getValue().longValue(), 0L); gauge.set(10L); assertEquals(gauge.getValue().longValue(), 10L); } @Test public void testGetConfig() throws Exception { LongGauge gauge = newInstance("test"); MonitorConfig expectedConfig = MonitorConfig.builder("test") .withTag(DataSourceType.GAUGE).build(); assertEquals(gauge.getConfig(), expectedConfig); } }
2,833
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/BasicCounterTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.Tag; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; public class BasicCounterTest extends AbstractMonitorTest<BasicCounter> { public BasicCounter newInstance(String name) { return new BasicCounter(MonitorConfig.builder(name).build()); } @Test public void testHasCounterTag() throws Exception { Tag type = newInstance("foo").getConfig().getTags().getTag(DataSourceType.KEY); assertEquals(type.getValue(), "COUNTER"); } @Test public void testGetValue() throws Exception { BasicCounter c = newInstance("foo"); assertEquals(c.getValue().longValue(), 0L); c.increment(); assertEquals(c.getValue().longValue(), 1L); c.increment(13); assertEquals(c.getValue().longValue(), 14L); } @Test public void testEqualsCount() throws Exception { BasicCounter c1 = newInstance("foo"); BasicCounter c2 = newInstance("foo"); assertEquals(c1, c2); c1.increment(); assertNotEquals(c1, c2); c2.increment(); assertEquals(c1, c2); } }
2,834
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/BasicGaugeTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.Test; import java.util.concurrent.Callable; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; public class BasicGaugeTest extends AbstractMonitorTest<BasicGauge<Long>> { private static class TestFunc implements Callable<Long> { private final long value; public TestFunc(long v) { value = v; } public Long call() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TestFunc testFunc = (TestFunc) o; return value == testFunc.value; } @Override public int hashCode() { return (int) (value ^ (value >>> 32)); } } public BasicGauge<Long> newInstance(String name) { long v = Long.parseLong(name); return new BasicGauge<>(MonitorConfig.builder(name).build(), new TestFunc(v)); } @Test public void testGetValue() throws Exception { BasicGauge<Long> c = newInstance("42"); assertEquals(c.getValue().longValue(), 42L); } @Test public void testEqualsCount() throws Exception { BasicGauge<Long> c1 = newInstance("42"); BasicGauge<Long> c2 = newInstance("43"); BasicGauge<Long> c3 = newInstance("43"); assertNotEquals(c1, c2); assertEquals(c2, c3); } }
2,835
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/PeakRateCounterTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.Tag; import com.netflix.servo.util.ManualClock; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class PeakRateCounterTest extends AbstractMonitorTest<PeakRateCounter> { final ManualClock clock = new ManualClock(0); @Override public PeakRateCounter newInstance(String name) { return new PeakRateCounter(MonitorConfig.builder(name).build(), clock); } @Test public void testIncrement() throws Exception { PeakRateCounter c = newInstance("foo"); assertEquals(c.getValue().longValue(), 0L); for (int i = 0; i < 5; i++) { clock.set(i * 1000L); c.increment(); } assertEquals(c.getValue().longValue(), 1L, "Delta of 5 in 5 seconds, e.g. peak rate = average, 1 per second"); for (int i = 0; i < 5; i++) { clock.set((5 + i) * 1000L); c.increment(3); } assertEquals(c.getValue().longValue(), 3L, "Delta of 15 in 5 seconds, e.g. peak rate = average, 3 per second"); clock.set(10 * 1000L); c.increment(10); for (int i = 0; i < 3; i++) { clock.set((11 + i) * 1000L); c.increment(3); } c.increment(); assertEquals(c.getValue().longValue(), 10L, "Delta of 15 in 5 seconds, e.g. peak rate = 10, average = 3, min = 1 per second"); clock.set(19 * 1000L); assertEquals(c.getValue().longValue(), 10L, "Delta of 0 in 5 seconds, e.g. peak rate = previous max, 10 per second"); } @Test public void testHasRightType() throws Exception { Tag type = newInstance("foo").getConfig().getTags().getTag(DataSourceType.KEY); assertEquals(type.getValue(), "GAUGE"); } @Test public void testEqualsAndHashCodeName() throws Exception { PeakRateCounter c1 = newInstance("1234567890"); PeakRateCounter c2 = newInstance("1234567890"); assertEquals(c1, c2); assertEquals(c1.hashCode(), c2.hashCode()); c2 = c1; assertEquals(c2, c1); } }
2,836
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/MonitorsTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.TagList; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static org.testng.Assert.*; public class MonitorsTest { @Test public void testAddMonitorsAnon() throws Exception { List<Monitor<?>> monitors = new ArrayList<>(); ClassWithMonitors obj = new ClassWithMonitors() { final Counter c1 = Monitors.newCounter("publicCounter"); @com.netflix.servo.annotations.Monitor( name = "primitiveGauge", type = DataSourceType.GAUGE) static final long A1 = 0L; }; TagList tags = BasicTagList.of("abc", "def"); Monitors.addMonitors(monitors, null, tags, obj); assertEquals(monitors.size(), 10); for (Monitor m : monitors) { assertEquals(m.getConfig().getTags().getValue("class"), "MonitorsTest", String.format("%s should have class MonitorsTest", m.getConfig().getName())); } } @Test public void testAddMonitorFields() throws Exception { List<Monitor<?>> monitors = new ArrayList<>(); ClassWithMonitors obj = new ClassWithMonitors(); TagList tags = BasicTagList.of("abc", "def"); Monitors.addMonitorFields(monitors, null, tags, obj); Monitors.addMonitorFields(monitors, "foo", null, obj); //System.out.println(monitors); assertEquals(monitors.size(), 8); Monitor<?> m = monitors.get(0); assertEquals(m.getConfig().getTags().getTag("class").getValue(), "ClassWithMonitors"); assertEquals(m.getConfig().getTags().getTag("abc").getValue(), "def"); } @Test public void testAddAnnotatedFields() throws Exception { List<Monitor<?>> monitors = new ArrayList<>(); ClassWithMonitors obj = new ClassWithMonitors(); Monitors.addAnnotatedFields(monitors, null, null, obj); Monitors.addAnnotatedFields(monitors, "foo", null, obj); //System.out.println(monitors); assertEquals(monitors.size(), 8); } @Test public void testNewObjectMonitor() throws Exception { ClassWithMonitors obj = new ClassWithMonitors(); List<Monitor<?>> monitors = Monitors.newObjectMonitor(obj).getMonitors(); //System.err.println(monitors); assertEquals(monitors.size(), 8); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNewObjectMonitorWithBadAnnotation() throws Exception { ClassWithBadAnnotation obj = new ClassWithBadAnnotation(); Monitors.newObjectMonitor(obj); } @Test public void testNewObjectMonitorWithParentClass() throws Exception { ParentHasMonitors obj = new ParentHasMonitors(); List<Monitor<?>> monitors = Monitors.newObjectMonitor(obj).getMonitors(); for (Monitor m : monitors) { assertEquals(m.getConfig().getTags().getValue("class"), "ParentHasMonitors", String.format("%s should have class ParentHasMonitors", m.getConfig().getName())); } assertEquals(monitors.size(), 10); } @Test public void testNewObjectConfig() throws Exception { ClassWithMonitors obj = new ClassWithMonitors() { }; List<Monitor<?>> monitors = Monitors.newObjectMonitor(obj).getMonitors(); for (Monitor m : monitors) { assertEquals(m.getConfig().getTags().getValue("class"), "MonitorsTest", String.format("%s should have class MonitorsTest", m.getConfig().getName())); } assertEquals(monitors.size(), 8); } @Test public void testAddMonitorsAnnoHierarchical() throws Exception { SuperClassWithMonitors.ChildClassWithMonitors obj = new SuperClassWithMonitors.ChildClassWithMonitors(); CompositeMonitor compositeMonitor = Monitors.newObjectMonitor(obj); @SuppressWarnings("unchecked") List<Monitor> monitors = compositeMonitor.getMonitors(); assertEquals(monitors.size(), 4); for(Monitor m : monitors) { String tagValue = m.getConfig().getTags().asMap().get("tag1"); assertNotNull(tagValue, "tag value not returned"); assertEquals(tagValue, "tag2", "tag value is not tag2"); } } }
2,837
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/BucketConfigTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; public class BucketConfigTest { @Test(expectedExceptions = NullPointerException.class) public void testNullTimeUnit() throws Exception { new BucketConfig.Builder().withTimeUnit(null).build(); } @Test(expectedExceptions = NullPointerException.class) public void testNullBuckets() throws Exception { new BucketConfig.Builder().withBuckets(null).build(); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyBuckets() throws Exception { new BucketConfig.Builder().withBuckets(new long[0]).build(); } @Test(expectedExceptions = IllegalArgumentException.class) public void testOutOfOrderBuckets() throws Exception { new BucketConfig.Builder().withBuckets(new long[]{0, 2, 1}).build(); } @Test(expectedExceptions = IllegalArgumentException.class) public void testDuplicateBuckets() throws Exception { new BucketConfig.Builder().withBuckets(new long[]{0, 1, 1, 2}).build(); } @Test public void testAccessors() throws Exception { BucketConfig config = new BucketConfig.Builder() .withTimeUnit(TimeUnit.SECONDS) .withBuckets(new long[]{7, 8, 9}) .build(); assertEquals(config.getTimeUnit(), TimeUnit.SECONDS); assertEquals(config.getBuckets(), new long[]{7, 8, 9}); } @Test public void testEquals() throws Exception { BucketConfig config1 = new BucketConfig.Builder() .withTimeUnit(TimeUnit.SECONDS) .withBuckets(new long[]{7, 8, 9}) .build(); BucketConfig config2 = new BucketConfig.Builder() .withTimeUnit(TimeUnit.SECONDS) .withBuckets(new long[]{7, 8, 9}) .build(); BucketConfig config3 = new BucketConfig.Builder() .withTimeUnit(TimeUnit.SECONDS) .withBuckets(new long[]{7, 8, 91}) .build(); assertNotNull(config1); assertFalse(config1.toString().equals(config3.toString())); assertTrue(config1.equals(config1)); assertTrue(config1.equals(config2)); assertFalse(config1.equals(config3)); } @Test public void testHashCode() throws Exception { BucketConfig config1 = new BucketConfig.Builder() .withTimeUnit(TimeUnit.SECONDS) .withBuckets(new long[]{7, 8, 9}) .build(); BucketConfig config2 = new BucketConfig.Builder() .withTimeUnit(TimeUnit.SECONDS) .withBuckets(new long[]{7, 8, 9}) .build(); BucketConfig config3 = new BucketConfig.Builder() .withTimeUnit(TimeUnit.SECONDS) .withBuckets(new long[]{7, 8, 91}) .build(); assertTrue(config1.hashCode() == config1.hashCode()); assertTrue(config1.hashCode() == config2.hashCode()); assertTrue(config1.hashCode() != config3.hashCode()); } }
2,838
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/MonitorConfigTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.tag.TagList; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; public class MonitorConfigTest { private final TagList tags1 = new BasicTagList(SortedTagList.builder().withTag("cluster", "foo") .withTag("asg", "foo-v000").build()); private final TagList tags2 = new BasicTagList(SortedTagList.builder().withTag("cluster", "foo") .withTag("asg", "foo-v001").build()); @Test(expectedExceptions = NullPointerException.class) public void testNullName() throws Exception { new MonitorConfig.Builder((String) null).withTags(tags1).build(); } @Test public void testNullTags() throws Exception { MonitorConfig m = new MonitorConfig.Builder("a").build(); assertEquals(m, new MonitorConfig.Builder("a").build()); } @Test public void testAccessors() throws Exception { MonitorConfig m1 = new MonitorConfig.Builder("a").withTags(tags1).build(); assertEquals(m1.getName(), "a"); assertEquals(m1.getTags(), tags1); } @Test public void testEquals() throws Exception { MonitorConfig m1 = new MonitorConfig.Builder("a").withTags(tags1).build(); MonitorConfig m2 = new MonitorConfig.Builder("a").withTags(tags2).build(); MonitorConfig m3 = new MonitorConfig.Builder("a").withTags(tags1).build(); assertNotNull(m1); assertFalse(m1.toString().equals(m2.toString())); assertTrue(m1.equals(m1)); assertFalse(m1.equals(m2)); assertTrue(m1.equals(m3)); } @Test public void testHashCode() throws Exception { MonitorConfig m1 = new MonitorConfig.Builder("a").withTags(tags1).build(); MonitorConfig m2 = new MonitorConfig.Builder("a").withTags(tags2).build(); MonitorConfig m3 = new MonitorConfig.Builder("a").withTags(tags1).build(); assertTrue(m1.hashCode() == m1.hashCode()); assertTrue(m1.hashCode() != m2.hashCode()); assertTrue(m1.hashCode() == m3.hashCode()); } @Test public void testBuilderMonitorConfig() throws Exception { MonitorConfig m1 = new MonitorConfig.Builder("a").build(); MonitorConfig m2 = new MonitorConfig.Builder(m1).build(); assertEquals(m1, m2); MonitorConfig m3 = new MonitorConfig.Builder(m1).withTag("k", "v").build(); assertNotEquals(m1, m3); assertEquals(m1.getName(), m3.getName()); assertNotEquals(m1.getTags(), m3.getTags()); assertEquals(m1.getPublishingPolicy(), m3.getPublishingPolicy()); } }
2,839
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/BasicTimerTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; public class BasicTimerTest extends AbstractMonitorTest<BasicTimer> { public BasicTimer newInstance(String name) { return new BasicTimer(MonitorConfig.builder(name).build()); } @Test public void testGetValue() throws Exception { BasicTimer c = newInstance("foo"); assertEquals(c.getValue().longValue(), 0L); assertEquals(c.getTotalTime().longValue(), 0L); assertEquals(c.getCount().longValue(), 0L); assertEquals(c.getMax().longValue(), 0L); c.record(42, TimeUnit.MILLISECONDS); assertEquals(c.getValue().longValue(), 42L); assertEquals(c.getTotalTime().longValue(), 42L); assertEquals(c.getCount().longValue(), 1L); assertEquals(c.getMax().longValue(), 42L); c.record(21, TimeUnit.MILLISECONDS); assertEquals(c.getValue().longValue(), 31L); assertEquals(c.getTotalTime().longValue(), 63L); assertEquals(c.getCount().longValue(), 2L); assertEquals(c.getMax().longValue(), 42L); c.record(84, TimeUnit.MILLISECONDS); assertEquals(c.getValue().longValue(), 49L); assertEquals(c.getTotalTime().longValue(), 147L); assertEquals(c.getCount().longValue(), 3L); assertEquals(c.getMax().longValue(), 84L); assertEquals(c.getValue().longValue(), 49L); assertEquals(c.getTotalTime().longValue(), 147L); assertEquals(c.getCount().longValue(), 3L); assertEquals(c.getMax().longValue(), 84L); } @Test public void testRecord0() throws Exception { BasicTimer c = newInstance("foo"); assertEquals(c.getCount().longValue(), 0L); c.record(42, TimeUnit.MILLISECONDS); assertEquals(c.getCount().longValue(), 1L); // Explicit 0 should be counted c.record(0, TimeUnit.MILLISECONDS); assertEquals(c.getCount().longValue(), 2L); // Negative values should be ignored c.record(-1, TimeUnit.MILLISECONDS); assertEquals(c.getCount().longValue(), 2L); } @Test public void testFractional() throws Exception { BasicTimer timer = newInstance("foo"); timer.record(1000, TimeUnit.NANOSECONDS); assertEquals(timer.getTotalTime(), 0.001); assertEquals(timer.getMax(), 0.001); } }
2,840
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/BasicStopwatchTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertTrue; public class BasicStopwatchTest { private BasicStopwatch testStopwatch; @BeforeMethod public void setupTest() throws Exception { testStopwatch = new BasicStopwatch(); } @Test public void testReset() throws Exception { testStopwatch.start(); Thread.sleep(10); testStopwatch.stop(); assertTrue(testStopwatch.getDuration() > 0); testStopwatch.reset(); assertTrue(testStopwatch.getDuration() == 0); } @Test public void testGetDuration() throws Exception { testStopwatch.start(); Thread.sleep(10); testStopwatch.stop(); assertTrue(testStopwatch.getDuration() > 9000000); } @Test public void testGetDurationBeforeStop() throws Exception { testStopwatch.start(); Thread.sleep(10); assertTrue(testStopwatch.getDuration() > 9000000); testStopwatch.stop(); assertTrue(testStopwatch.getDuration() > 9000000); } @Test public void testGetDurationWithUnit() throws Exception { testStopwatch.start(); Thread.sleep(10); testStopwatch.stop(); assertTrue(testStopwatch.getDuration() > 12); } }
2,841
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/BasicDistributionSummaryTest.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class BasicDistributionSummaryTest extends AbstractMonitorTest<BasicDistributionSummary> { public BasicDistributionSummary newInstance(String name) { return new BasicDistributionSummary(MonitorConfig.builder(name).build()); } @Test public void testGetValue() throws Exception { BasicDistributionSummary m = newInstance("foo"); // initial values assertEquals(m.getValue().longValue(), 0L); assertEquals(m.getCount().longValue(), 0L); assertEquals(m.getTotalAmount().longValue(), 0L); assertEquals(m.getMax().longValue(), 0L); assertEquals(m.getMin().longValue(), 0L); m.record(42); assertEquals(m.getValue().longValue(), 42L); assertEquals(m.getTotalAmount().longValue(), 42L); assertEquals(m.getCount().longValue(), 1L); assertEquals(m.getMax().longValue(), 42L); assertEquals(m.getMin().longValue(), 42L); m.record(21); assertEquals(m.getValue().longValue(), 31L); assertEquals(m.getTotalAmount().longValue(), 63L); assertEquals(m.getCount().longValue(), 2L); assertEquals(m.getMax().longValue(), 42L); assertEquals(m.getMin().longValue(), 21L); } @Test public void testRecord0() throws Exception { BasicDistributionSummary c = newInstance("foo"); assertEquals(c.getCount().longValue(), 0L); c.record(42); assertEquals(c.getCount().longValue(), 1L); // Explicit 0 should be counted c.record(0); assertEquals(c.getCount().longValue(), 2L); // Negative values should be ignored c.record(-1); assertEquals(c.getCount().longValue(), 2L); } }
2,842
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/DynamicTimerTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo.monitor; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.ExpiringCache; import com.netflix.servo.util.ManualClock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.lang.reflect.Field; import java.util.List; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; public class DynamicTimerTest { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicTimerTest.class); private DynamicTimer getInstance() throws Exception { Field theInstance = DynamicTimer.class.getDeclaredField("INSTANCE"); theInstance.setAccessible(true); return (DynamicTimer) theInstance.get(null); } private List<Monitor<?>> getTimers() throws Exception { return getInstance().getMonitors(); } private final TagList tagList = BasicTagList.of("PLATFORM", "true"); private Timer getByName(String name) throws Exception { List<Monitor<?>> timers = getTimers(); for (Monitor<?> m : timers) { String monitorName = m.getConfig().getName(); if (name.equals(monitorName)) { return (Timer) m; } } return null; } @SuppressWarnings("unchecked") @Test public void testHasUnitTag() throws Exception { DynamicTimer.start("test1", tagList); CompositeMonitor c = (CompositeMonitor<Long>) getByName("test1"); assert c != null; List<Monitor<?>> monitors = c.getMonitors(); for (Monitor<?> m : monitors) { Tag type = m.getConfig().getTags().getTag("unit"); assertEquals(type.getValue(), "MILLISECONDS"); } } final ManualClock clock = new ManualClock(0L); /** * Erase all previous timers by creating a new loading cache with a short expiration time */ @BeforeMethod public void setupInstance() throws Exception { LOGGER.info("Setting up DynamicTimer instance with a new cache"); DynamicTimer theInstance = getInstance(); Field timers = DynamicTimer.class.getDeclaredField("timers"); timers.setAccessible(true); ExpiringCache<DynamicTimer.ConfigUnit, Timer> newShortExpiringCache = new ExpiringCache<>(1000L, configUnit -> new BasicTimer(configUnit.getConfig(), configUnit.getUnit()), 100L, clock); timers.set(theInstance, newShortExpiringCache); } @Test public void testGetValue() throws Exception { Stopwatch s = DynamicTimer.start("test1", tagList); Timer c = getByName("test1"); s.stop(); // we don't call s.stop(), so we only have one recorded value assert c != null; assertEquals(c.getValue().longValue(), s.getDuration(TimeUnit.MILLISECONDS)); c.record(13, TimeUnit.MILLISECONDS); long expected = (13 + s.getDuration(TimeUnit.MILLISECONDS)) / 2; assertEquals(c.getValue().longValue(), expected); } @Test public void testExpiration() throws Exception { clock.set(0L); DynamicTimer.start("test1", tagList); DynamicTimer.start("test2", tagList); clock.set(500L); DynamicTimer.start("test1", tagList); clock.set(1000L); Stopwatch s = DynamicTimer.start("test1", tagList); clock.set(1200L); s.stop(); Timer c1 = getByName("test1"); assert c1 != null; assertEquals(c1.getValue().longValue(), s.getDuration(TimeUnit.MILLISECONDS)); Thread.sleep(200L); Timer c2 = getByName("test2"); assertNull(c2, "Timers not used in a while should expire"); } @Test public void testByStrings() throws Exception { Stopwatch s = DynamicTimer.start("byName"); Stopwatch s2 = DynamicTimer.start("byName2", "key", "value"); Thread.sleep(100L); s.stop(); s2.stop(); Timer c1 = getByName("byName"); assert c1 != null; assertEquals(c1.getValue().longValue(), s.getDuration(TimeUnit.MILLISECONDS)); Timer c2 = getByName("byName2"); assert c2 != null; assertEquals(c2.getValue().longValue(), s2.getDuration(TimeUnit.MILLISECONDS)); } }
2,843
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/BasicInformationalTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; public class BasicInformationalTest extends AbstractMonitorTest<BasicInformational> { public BasicInformational newInstance(String name) { return new BasicInformational(MonitorConfig.builder(name).build()); } @Test public void testGetValue() throws Exception { BasicInformational c = newInstance("foo"); assertEquals(c.getValue(), null); c.setValue("bar"); assertEquals(c.getValue(), "bar"); } @Test public void testEqualsSet() throws Exception { BasicInformational c1 = newInstance("foo"); BasicInformational c2 = newInstance("foo"); assertEquals(c1, c2); c1.setValue("bar"); assertNotEquals(c1, c2); c2.setValue("bar"); assertEquals(c1, c2); } }
2,844
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/StepCounterTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.util.ManualClock; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class StepCounterTest { private static final double DELTA = 1e-06; private final ManualClock clock = new ManualClock(50 * Pollers.POLLING_INTERVALS[1]); public StepCounter newInstance(String name) { return new StepCounter(MonitorConfig.builder(name).build(), clock); } private long time(long t) { return t * 1000 + Pollers.POLLING_INTERVALS[1]; } @Test public void testSimpleTransition() { long start = time(1); clock.set(start); StepCounter c = newInstance("c"); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 0L); clock.set(start + 2000); c.increment(); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 1L); clock.set(start + 8000); c.increment(); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 2L); clock.set(start + 12000); c.increment(); assertEquals(c.getValue(1).doubleValue(), 2.0 / 10.0, DELTA); assertEquals(c.getCurrentCount(1), 1L); } @Test public void testInitialPollIsZero() { clock.set(time(1)); StepCounter c = newInstance("foo"); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); } @Test public void testHasRightType() throws Exception { assertEquals(newInstance("foo").getConfig().getTags().getValue(DataSourceType.KEY), "NORMALIZED"); } @Test public void testBoundaryTransition() { clock.set(time(1)); StepCounter c = newInstance("foo"); // Should all go to one bucket c.increment(); clock.set(time(4)); c.increment(); clock.set(time(9)); c.increment(); // Should cause transition clock.set(time(10)); c.increment(); clock.set(time(19)); c.increment(); // Check counts assertEquals(c.getValue(1).doubleValue(), 0.3, DELTA); assertEquals(c.getCurrentCount(1), 2); } @Test public void testResetPreviousValue() { clock.set(time(1)); StepCounter c = newInstance("foo"); for (int i = 1; i <= 100000; ++i) { c.increment(); clock.set(time(i * 10 + 1)); assertEquals(c.getValue(1).doubleValue(), 0.1, DELTA); } } @Test public void testMissedInterval() { clock.set(time(1)); StepCounter c = newInstance("foo"); c.getValue(1); // Multiple updates without polling c.increment(1); clock.set(time(4)); c.increment(1); clock.set(time(14)); c.increment(1); clock.set(time(24)); c.increment(1); clock.set(time(34)); c.increment(1); // Check counts assertEquals(c.getValue(1).doubleValue(), 0.1); assertEquals(c.getCurrentCount(1), 1); } @Test public void testMissedIntervalNoIncrements() { clock.set(time(1)); StepCounter c = newInstance("foo"); c.getValue(1); // Gaps without polling c.increment(5); clock.set(time(34)); // Check counts, previous and current interval should be 0 assertEquals(c.getValue(1).doubleValue(), 0.0); assertEquals(c.getCurrentCount(1), 0); } @Test public void testNonMonotonicClock() { clock.set(time(1)); StepCounter c = newInstance("foo"); c.getValue(1); c.increment(); c.increment(); clock.set(time(10)); c.increment(); clock.set(time(9)); // Should get ignored c.increment(); assertEquals(c.getCurrentCount(1), 2); c.increment(); clock.set(time(10)); c.increment(); c.increment(); assertEquals(c.getCurrentCount(1), 5); // Check rate for previous interval assertEquals(c.getValue(1).doubleValue(), 0.2, DELTA); } @Test public void testGetValueTwice() { ManualClock manualClock = new ManualClock(60000L); StepCounter c = new StepCounter(MonitorConfig.builder("test").build(), manualClock); c.increment(); for (int i = 2; i < 10; ++i) { manualClock.set(i * 60000L); c.increment(); c.getValue(0); assertEquals(c.getValue(0).doubleValue(), 1 / 60.0, DELTA); } } @Test public void testIncrAfterMissedSteps() { clock.set(time(1)); StepCounter c = newInstance("foo"); c.increment(); clock.set(time(11)); assertEquals(c.getValue(1).doubleValue(), 0.1, DELTA); clock.set(time(31)); c.increment(); c.increment(); c.increment(); clock.set(time(41)); assertEquals(c.getValue(1).doubleValue(), 0.3, DELTA); } }
2,845
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/MaxGaugeTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.util.ManualClock; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class MaxGaugeTest extends AbstractMonitorTest<MaxGauge> { private final ManualClock clock = new ManualClock(0L); @Override public MaxGauge newInstance(String name) { return new MaxGauge(MonitorConfig.builder(name).build(), clock); } @Test public void testUpdate() throws Exception { clock.set(0L); MaxGauge maxGauge = newInstance("max1"); maxGauge.update(42L); assertEquals(maxGauge.getValue().longValue(), 0L); clock.set(60000L); assertEquals(maxGauge.getValue().longValue(), 42L); } @Test public void testUpdate2() throws Exception { clock.set(0L); MaxGauge maxGauge = newInstance("max1"); maxGauge.update(42L); maxGauge.update(420L); clock.set(60000L); assertEquals(maxGauge.getValue().longValue(), 420L); } @Test public void testUpdate3() throws Exception { clock.set(0L); MaxGauge maxGauge = newInstance("max1"); maxGauge.update(42L); maxGauge.update(420L); maxGauge.update(1L); clock.set(60000L); assertEquals(maxGauge.getValue().longValue(), 420L); } }
2,846
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/DoubleGaugeTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class DoubleGaugeTest extends AbstractMonitorTest<DoubleGauge> { @Override public DoubleGauge newInstance(String name) { return new DoubleGauge(MonitorConfig.builder(name).build()); } @Test public void testSet() throws Exception { DoubleGauge gauge = newInstance("test"); gauge.set(10.0); assertEquals(gauge.getValue().doubleValue(), 10.0); } @Test public void testGetConfig() throws Exception { DoubleGauge gauge = newInstance("test"); MonitorConfig expectedConfig = MonitorConfig.builder("test") .withTag(DataSourceType.GAUGE).build(); assertEquals(gauge.getConfig(), expectedConfig); } }
2,847
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/ClassWithBadAnnotation.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import java.util.concurrent.atomic.AtomicLong; import static com.netflix.servo.annotations.DataSourceType.COUNTER; import static com.netflix.servo.annotations.DataSourceType.GAUGE; import static com.netflix.servo.annotations.DataSourceType.INFORMATIONAL; public class ClassWithBadAnnotation { @com.netflix.servo.annotations.Monitor(name = "badGauge", type = GAUGE) private final String badGauge = "foo"; @com.netflix.servo.annotations.Monitor(name = "annoGauge", type = GAUGE) private final AtomicLong a1 = new AtomicLong(0L); @com.netflix.servo.annotations.Monitor(name = "annoCounter", type = COUNTER) public final AtomicLong a2 = new AtomicLong(0L); @com.netflix.servo.annotations.Monitor(name = "annoInfo", type = INFORMATIONAL) private String getInfo() { return "foo"; } }
2,848
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/ParentHasMonitors.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import java.util.concurrent.atomic.AtomicLong; import static com.netflix.servo.annotations.DataSourceType.GAUGE; public class ParentHasMonitors extends ClassWithMonitors { private final Counter c = Monitors.newCounter("myCounter"); @com.netflix.servo.annotations.Monitor(name = "myGauge", type = GAUGE) private final AtomicLong a1 = new AtomicLong(0L); }
2,849
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/MinGaugeTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.util.ManualClock; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class MinGaugeTest extends AbstractMonitorTest<MinGauge> { private final ManualClock clock = new ManualClock(0L); @Override public MinGauge newInstance(String name) { MonitorConfig config = MonitorConfig.builder(name).build(); return new MinGauge(config, clock); } @Test public void testUpdate() throws Exception { clock.set(0L); MinGauge minGauge = newInstance("min1"); minGauge.update(42L); clock.set(60000L); assertEquals(minGauge.getValue().longValue(), 42L); } @Test public void testUpdate2() throws Exception { clock.set(0L); MinGauge minGauge = newInstance("min1"); minGauge.update(42L); minGauge.update(420L); clock.set(60000L); assertEquals(minGauge.getValue().longValue(), 42L); } @Test public void testUpdate3() throws Exception { clock.set(0L); MinGauge minGauge = newInstance("min1"); minGauge.update(42L); minGauge.update(420L); minGauge.update(1L); clock.set(60000L); assertEquals(minGauge.getValue().longValue(), 1L); } }
2,850
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/DynamicCounterTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.ExpiringCache; import com.netflix.servo.util.ManualClock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.lang.reflect.Field; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; public class DynamicCounterTest { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicCounterTest.class); private DynamicCounter getInstance() throws Exception { Field theInstance = DynamicCounter.class.getDeclaredField("INSTANCE"); theInstance.setAccessible(true); return (DynamicCounter) theInstance.get(null); } private List<Monitor<?>> getCounters() throws Exception { return getInstance().getMonitors(); } private final TagList tagList = BasicTagList.of("PLATFORM", "true"); private StepCounter getByName(String name) throws Exception { List<Monitor<?>> counters = getCounters(); for (Monitor<?> m : counters) { String monitorName = m.getConfig().getName(); if (name.equals(monitorName)) { return (StepCounter) m; } } return null; } @Test public void testHasRightType() throws Exception { DynamicCounter.increment("test1", tagList); StepCounter c = getByName("test1"); assert c != null; Tag type = c.getConfig().getTags().getTag(DataSourceType.KEY); assertEquals(type.getValue(), "NORMALIZED"); } final ManualClock clock = new ManualClock(0L); /** * Erase all previous counters by creating a new loading cache with a short expiration time. */ @BeforeMethod public void setupInstance() throws Exception { LOGGER.info("Setting up DynamicCounter instance with a new cache"); DynamicCounter theInstance = getInstance(); Field counters = DynamicCounter.class.getDeclaredField("counters"); counters.setAccessible(true); ExpiringCache<MonitorConfig, Counter> newShortExpiringCache = new ExpiringCache<>(60000L, config -> new StepCounter(config, clock), 100L, clock); counters.set(theInstance, newShortExpiringCache); } @Test public void testGetValue() throws Exception { clock.set(0L); DynamicCounter.increment("test1", tagList); StepCounter c = getByName("test1"); clock.set(60000L); assert c != null; assertEquals(c.getCount(0), 1L); c.increment(13); clock.set(120000L); assertEquals(c.getCount(0), 13L); } @Test public void testExpiration() throws Exception { clock.set(0L); DynamicCounter.increment("test1", tagList); DynamicCounter.increment("test2", tagList); clock.set(500L); DynamicCounter.increment("test1", tagList); clock.set(1000L); DynamicCounter.increment("test1", tagList); clock.set(60200L); StepCounter c1 = getByName("test1"); assert c1 != null; assertEquals(c1.getCount(0), 3L); // the expiration task is not using Clock Thread.sleep(200); StepCounter c2 = getByName("test2"); assertNull(c2, "Counters not used in a while should expire"); } @Test public void testByStrings() throws Exception { clock.set(1L); DynamicCounter.increment("byName"); DynamicCounter.increment("byName"); StepCounter c = getByName("byName"); clock.set(60001L); assert c != null; assertEquals(c.getCount(0), 2L); DynamicCounter.increment("byName2", "key", "value", "key2", "value2"); DynamicCounter.increment("byName2", "key", "value", "key2", "value2"); StepCounter c2 = getByName("byName2"); clock.set(120001L); assert c2 != null; assertEquals(c2.getCount(0), 2L); } @Test public void testShouldNotThrow() throws Exception { DynamicCounter.increment("name", "", ""); } }
2,851
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/StatsTimerTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.stats.StatsConfig; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static org.testng.Assert.assertEquals; public class StatsTimerTest extends AbstractMonitorTest<StatsTimer> { @Override public StatsTimer newInstance(String name) { final double[] percentiles = {50.0, 95.0, 99.0, 99.5}; final StatsConfig statsConfig = new StatsConfig.Builder() .withSampleSize(200000) .withPercentiles(percentiles) .withPublishStdDev(true) .withComputeFrequencyMillis(1000) .build(); final MonitorConfig config = MonitorConfig.builder(name).build(); return new StatsTimer(config, statsConfig); } @Test public void testNoRecordedValues() throws Exception { final StatsTimer timer = newInstance("novalue"); assertEquals(timer.getCount(), 0L); assertEquals(timer.getTotalTime(), 0L); final long timerValue = timer.getValue(); assertEquals(timerValue, 0L); } @Test public void testStats() throws Exception { final StatsTimer timer = newInstance("t1"); final Map<String, Number> expectedValues = new HashMap<>(); final int n = 200 * 1000; expectedValues.put("count", (long) n); expectedValues.put("totalTime", (long) n * (n - 1) / 2); expectedValues.put("stdDev", 57735.17); expectedValues.put("percentile_50", 100 * 1000.0); expectedValues.put("percentile_95", 190 * 1000.0); expectedValues.put("percentile_99", 198 * 1000.0); expectedValues.put("percentile_99.50", 199 * 1000.0); for (int i = 0; i < n; ++i) { timer.record(i); } timer.computeStats(); assertStats(timer.getMonitors(), expectedValues); } private void assertStats(List<Monitor<?>> monitors, Map<String, Number> expectedValues) { for (Monitor<?> monitor : monitors) { final String stat = monitor.getConfig().getTags().getValue("statistic"); final Number actual = (Number) monitor.getValue(); final Number expected = expectedValues.get(stat); if (expected instanceof Double) { double e = expected.doubleValue(); double a = actual.doubleValue(); assertEquals(a, e, 0.5, stat); } else { assertEquals(actual, expected, stat); } } } private static class TimerTask implements Runnable { final StatsTimer timer; final int value; TimerTask(StatsTimer timer, int value) { this.timer = timer; this.value = value; } @Override public void run() { timer.record(value); } } @Test public void testMultiThreadStats() throws Exception { final StatsTimer timer = newInstance("t1"); final Map<String, Number> expectedValues = new HashMap<>(); final int n = 10 * 1000; expectedValues.put("count", (long) n); expectedValues.put("totalTime", (long) n * (n - 1) / 2); expectedValues.put("stdDev", 2886.766); expectedValues.put("percentile_50", 5 * 1000.0); expectedValues.put("percentile_95", 9.5 * 1000.0); expectedValues.put("percentile_99", 9.9 * 1000.0); expectedValues.put("percentile_99.50", 9.95 * 1000.0); final int poolSize = Runtime.getRuntime().availableProcessors(); ExecutorService service = Executors.newFixedThreadPool(poolSize); List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < n; ++i) { futures.add(service.submit(new TimerTask(timer, i))); } // Wait for all submitted tasks to complete for (Future<?> f : futures) { f.get(); } timer.computeStats(); assertStats(timer.getMonitors(), expectedValues); } }
2,852
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/PollersTest.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class PollersTest { @Test public void testParseOneEntry() throws Exception { long[] expected1 = {1L}; assertEquals(Pollers.parse("1"), expected1); long[] expected2 = {42000L}; assertEquals(Pollers.parse("42000"), expected2); } @Test public void testParseInvalid() throws Exception { assertEquals(Pollers.parse("0"), Pollers.DEFAULT_PERIODS); assertEquals(Pollers.parse("-1"), Pollers.DEFAULT_PERIODS); assertEquals(Pollers.parse("1L"), Pollers.DEFAULT_PERIODS); assertEquals(Pollers.parse("100,-1"), Pollers.DEFAULT_PERIODS); assertEquals(Pollers.parse("100,0"), Pollers.DEFAULT_PERIODS); } @Test public void testParseMultiple() throws Exception { long[] expected = {60000L, 10000L, 2000L}; assertEquals(Pollers.parse("60000,10000,2000"), expected); } }
2,853
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/TimedInterfaceTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.TagList; import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TimedInterfaceTest { /** * Dummy interface to test our timer. */ private interface IDummy { void method1(); boolean method2(int n); Object method3(Object a, Object b); } private interface IDummyExtended extends IDummy { void method4(); } private static class DummyImpl implements IDummy { private void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException ignored) { // Ignored } } @Override public void method1() { sleep(20); } @Override public boolean method2(int n) { sleep(40); return n > 0; } @Override public Object method3(Object a, Object b) { sleep(60); return a; } } private static class ExtendedDummy extends DummyImpl implements IDummyExtended { @Override public void method4() { // do nothing } } @SuppressWarnings("unchecked") @Test public void testTimedInterface() { final IDummy dummy = TimedInterface.newProxy(IDummy.class, new DummyImpl(), "id"); final CompositeMonitor<Long> compositeMonitor = (CompositeMonitor<Long>) dummy; final List<Monitor<?>> monitors = compositeMonitor.getMonitors(); assertEquals(monitors.size(), 3); assertEquals(compositeMonitor.getValue().longValue(), 3L); // you'd register the CompositeMonitor as: DefaultMonitorRegistry.getInstance().register((CompositeMonitor) dummy); for (int i = 0; i < 42; i++) { dummy.method1(); if (i % 2 == 0) { dummy.method2(i); } } final TagList tagList = BasicTagList.of( TimedInterface.CLASS_TAG, "DummyImpl", TimedInterface.INTERFACE_TAG, "IDummy", TimedInterface.ID_TAG, "id"); final MonitorConfig expectedConfig = MonitorConfig.builder(TimedInterface.TIMED_INTERFACE) .withTags(tagList).build(); assertEquals(compositeMonitor.getConfig(), expectedConfig); for (Monitor<?> monitor : monitors) { final MonitorConfig config = monitor.getConfig(); final String method = config.getName(); final MonitorConfig expected = MonitorConfig.builder(method).withTags(tagList).build(); assertEquals(config, expected); switch (method) { case "method1": { // expected result is 20, but let's give it a fudge factor to account for // slow machines long value = ((Monitor<Long>) monitor).getValue() - 20; assertTrue(value >= 0 && value <= 9); break; } case "method2": { // expected result is 40, but let's give it a fudge factor to account for // slow machines long value = ((Monitor<Long>) monitor).getValue() - 40; assertTrue(value >= 0 && value <= 9); break; } default: { assertEquals(method, "method3"); long value = ((Monitor<Long>) monitor).getValue(); assertEquals(value, 0); break; } } } } @SuppressWarnings("unchecked") @Test public void testTimedInterfaceNoId() { final IDummy dummy = TimedInterface.newProxy(IDummy.class, new DummyImpl()); // you'd register the CompositeMonitor as: DefaultMonitorRegistry.getInstance().register((CompositeMonitor) dummy); final CompositeMonitor<Long> compositeMonitor = (CompositeMonitor<Long>) dummy; final TagList tagList = BasicTagList.of( TimedInterface.CLASS_TAG, "DummyImpl", TimedInterface.INTERFACE_TAG, "IDummy"); final MonitorConfig expectedConfig = MonitorConfig.builder(TimedInterface.TIMED_INTERFACE) .withTags(tagList).build(); assertEquals(compositeMonitor.getConfig(), expectedConfig); } @SuppressWarnings("unchecked") @Test public void testInterfaceInheritence() { final List<String> expectedNames = Arrays.asList("method1", "method2", "method3", "method4"); final IDummyExtended extendedDummy = TimedInterface.newProxy(IDummyExtended.class, new ExtendedDummy()); final CompositeMonitor<Long> compositeMonitor = (CompositeMonitor<Long>) extendedDummy; DefaultMonitorRegistry.getInstance().register(compositeMonitor); assertEquals(compositeMonitor.getMonitors().size(), 4); assertEquals(compositeMonitor.getValue().longValue(), 4L); assertEquals(compositeMonitor.getValue(100).longValue(), 4L); final List<Monitor<?>> monitors = compositeMonitor.getMonitors(); for (Monitor<?> monitor : monitors) { assertTrue(expectedNames.contains(monitor.getConfig().getName())); } } }
2,854
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/AbstractMonitorTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; /** * Common test cases for all monitor implementations. */ public abstract class AbstractMonitorTest<T extends Monitor<?>> { public abstract T newInstance(String name); @Test public void testEqualsName() throws Exception { assertEquals(newInstance("1234567890"), newInstance("1234567890")); } @Test public void testNotEqualsName() throws Exception { assertNotEquals(newInstance("1234567890"), newInstance("47")); } @Test public void testHashCodeName() throws Exception { assertEquals(newInstance("1234567890").hashCode(), newInstance("1234567890").hashCode()); } @Test public void testNotHashCodeName() throws Exception { assertNotEquals(newInstance("1234567890").hashCode(), newInstance("47").hashCode()); } @Test public void testToStringIncludesName() throws Exception { assertTrue(newInstance("1234567890").toString().contains("1234567890")); assertTrue(newInstance("47").toString().contains("47")); } }
2,855
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/ClassWithMonitors.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import java.util.concurrent.atomic.AtomicLong; import static com.netflix.servo.annotations.DataSourceType.COUNTER; import static com.netflix.servo.annotations.DataSourceType.GAUGE; import static com.netflix.servo.annotations.DataSourceType.INFORMATIONAL; public class ClassWithMonitors { public final Counter c1 = Monitors.newCounter("publicCounter"); final Counter c2 = Monitors.newCounter("packageCounter"); protected final Counter c3 = Monitors.newCounter("protectedCounter"); private final Counter c4 = Monitors.newCounter("privateCounter"); @com.netflix.servo.annotations.Monitor(name = "annoGauge", type = GAUGE) private final AtomicLong a1 = new AtomicLong(0L); @com.netflix.servo.annotations.Monitor(name = "annoCounter", type = COUNTER) public final AtomicLong a2 = new AtomicLong(0L); @com.netflix.servo.annotations.Monitor(name = "primitiveGauge", type = GAUGE) public final long a3 = 0L; @com.netflix.servo.annotations.Monitor(name = "annoInfo", type = INFORMATIONAL) private String getInfo() { return "foo"; } }
2,856
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/SpectatorIntegrationTest.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.SpectatorContext; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.stats.StatsConfig; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ManualClock; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Statistic; import com.netflix.spectator.api.Tag; import com.netflix.spectator.api.patterns.PolledMeter; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; public class SpectatorIntegrationTest { private static final MonitorConfig CONFIG = new MonitorConfig.Builder("test").build(); private static final Id ID = new DefaultRegistry() .createId(CONFIG.getName()) .withTags(CONFIG.getTags().asMap()); private static final Tag COUNTER = new BasicTag("type", "COUNTER"); private Registry registry; @BeforeMethod public void before() { DefaultMonitorRegistry.getInstance().getRegisteredMonitors().forEach( m -> DefaultMonitorRegistry.getInstance().unregister(m) ); registry = new DefaultRegistry(); SpectatorContext.setRegistry(registry); } private void register(com.netflix.servo.monitor.Monitor<?> monitor) { DefaultMonitorRegistry.getInstance().register(monitor); } @Test public void testUnregisteredBasicCounter() { BasicCounter c = new BasicCounter(CONFIG); assertEquals(0, registry.counters().count()); } @Test public void testUnregisteredBasicCounterIncrement() { BasicCounter c = new BasicCounter(CONFIG); c.increment(); assertEquals(1, registry.counters().count()); assertEquals(1, registry.counter("test").count()); } @Test public void testUnregisteredBasicTimer() { BasicTimer t = new BasicTimer(CONFIG); assertEquals(0, registry.timers().count()); } @Test public void testUnregisteredBasicTimerIncrement() { BasicTimer t = new BasicTimer(CONFIG); t.record(42, TimeUnit.MILLISECONDS); Id id = registry.createId("test") .withTag("unit", "MILLISECONDS"); assertEquals(3, registry.counters().count()); assertEquals(0, registry.timers().count()); assertEquals(1, registry.gauges().count()); assertEquals(0, registry.distributionSummaries().count()); assertEquals(1, registry.counter(id.withTag(Statistic.count)).count()); assertEquals(42, registry.counter(id.withTag(Statistic.totalTime)).count()); assertEquals(42 * 42, registry.counter(id.withTag(Statistic.totalOfSquares)).count()); assertEquals(42.0, registry.maxGauge(id.withTag(Statistic.max)).value()); } @Test public void testBasicCounterIncrement() { BasicCounter c = new BasicCounter(CONFIG); register(c); c.increment(); assertEquals(1, registry.counter(ID).count()); } @Test public void testBasicCounterIncrementAmount() { BasicCounter c = new BasicCounter(CONFIG); register(c); c.increment(42); assertEquals(42, registry.counter(ID).count()); } @Test public void testStepCounterIncrement() { StepCounter c = new StepCounter(CONFIG); register(c); c.increment(); assertEquals(1, registry.counter(ID).count()); } @Test public void testStepCounterIncrementAmount() { StepCounter c = new StepCounter(CONFIG); register(c); c.increment(42); assertEquals(42, registry.counter(ID).count()); } @Test public void testDynamicCounterIncrement() { DynamicCounter.increment(CONFIG); assertEquals(1, registry.counter(ID).count()); } @Test public void testDoubleCounterAdd() { DoubleCounter c = new DoubleCounter(CONFIG, Clock.WALL); register(c); c.increment(0.2); assertEquals(0.2, registry.counter(ID).actualCount()); } @Test public void testAnnotatedCounter() { AnnotateExample ex = new AnnotateExample("foo"); PolledMeter.update(registry); Id id = registry.createId("counter") .withTag("class", "AnnotateExample") .withTag("level", "INFO") .withTag("id", "foo"); assertEquals(1, registry.counter(id).count()); } @Test public void testMemberCounter() { AnnotateExample ex = new AnnotateExample("foo"); ex.update(); Id id = registry.createId("test") .withTag("class", "AnnotateExample") .withTag("id", "foo"); assertEquals(1, registry.counter(id).count()); } @Test public void testContextualCounter() { TagList context = BasicTagList.of("a", "1"); ContextualCounter c = new ContextualCounter(CONFIG, () -> context, BasicCounter::new); c.increment(); Id id = ID.withTag("a", "1"); assertEquals(1, registry.counter(id).count()); } @Test public void testContextualMemberCounter() { ContextualExample c = new ContextualExample("foo"); c.update(); Id id = registry.createId("counter") .withTag("a", "2") .withTag("id", "foo") .withTag("class", "ContextualExample"); assertEquals(1, registry.counter(id).count()); } @Test public void testCustomCompositeMemberCounter() { CustomCompositeExample c = new CustomCompositeExample("foo"); c.update("2"); Id id = registry.createId("test").withTag("c", "2"); assertEquals(1, registry.counter(id).count()); } @Test public void testPeakRateCounter() { PeakRateCounter c = new PeakRateCounter(CONFIG); DefaultMonitorRegistry.getInstance().register(c); c.increment(); PolledMeter.update(registry); assertEquals(1.0, registry.gauge(ID).value()); } @Test public void testPeakRateCounterRemove() { PeakRateCounter c = new PeakRateCounter(CONFIG); DefaultMonitorRegistry.getInstance().register(c); DefaultMonitorRegistry.getInstance().unregister(c); c.increment(); PolledMeter.update(registry); assertEquals(0, registry.stream().count()); } @Test public void testCustomCounter() { CustomCounter c = new CustomCounter(); register(c); c.increment(); PolledMeter.update(registry); assertEquals(1, registry.counter(ID).count()); } @Test public void testDoubleGauge() { DoubleGauge c = new DoubleGauge(CONFIG); register(c); c.set(42.0); assertEquals(42.0, registry.gauge(ID).value(), 1e-12); } @Test public void testNumberGauge() { Number n = 42.0; NumberGauge c = new NumberGauge(CONFIG, n); register(c); PolledMeter.update(registry); assertEquals(42.0, registry.gauge(ID).value(), 1e-12); } @Test public void testBasicGauge() { BasicGauge<Double> c = new BasicGauge<>(CONFIG, () -> 42.0); register(c); PolledMeter.update(registry); assertEquals(42.0, registry.gauge(ID).value(), 1e-12); } @Test public void testAnnotatedGauge() { AnnotateExample ex = new AnnotateExample("foo"); PolledMeter.update(registry); Id id = registry.createId("gauge") .withTag("class", "AnnotateExample") .withTag("level", "INFO") .withTag("id", "foo"); assertEquals(42.0, registry.gauge(id).value(), 1e-12); } @Test public void testDynamicGauge() { DynamicGauge.set(CONFIG, 42.0); assertEquals(42.0, registry.gauge(ID).value(), 1e-12); } @Test public void testDoubleMaxGauge() { DoubleGauge c = new DoubleGauge(CONFIG); register(c); c.set(42.0); assertEquals(42.0, registry.maxGauge(ID).value(), 1e-12); } @Test public void testMinGauge() { ManualClock clock = new ManualClock(0); MinGauge g = new MinGauge(CONFIG, clock); DefaultMonitorRegistry.getInstance().register(g); g.update(42); clock.set(60000); PolledMeter.update(registry); assertEquals(42.0, registry.gauge(ID).value()); } @Test public void testMinGaugeRemove() { MinGauge g = new MinGauge(CONFIG); DefaultMonitorRegistry.getInstance().register(g); DefaultMonitorRegistry.getInstance().unregister(g); g.update(42); PolledMeter.update(registry); assertEquals(0, registry.stream().count()); } @Test public void testBasicDistributionSummaryRecord() { BasicDistributionSummary d = new BasicDistributionSummary(CONFIG); register(d); d.record(42); assertEquals(1, registry.counter(ID.withTag(Statistic.count)).count()); assertEquals(42, registry.counter(ID.withTag(Statistic.totalAmount)).count()); assertEquals(42.0, registry.maxGauge(ID.withTag(Statistic.max)).value(), 1e-12); } @Test public void testBasicTimerRecordMillis() { BasicTimer d = new BasicTimer(CONFIG); register(d); d.record(42, TimeUnit.NANOSECONDS); Id id = ID.withTag("unit", "MILLISECONDS"); assertEquals(1, registry.counter(id.withTag(Statistic.count)).count()); assertEquals(42e-6, registry.counter(id.withTag(Statistic.totalTime)).actualCount(), 1e-12); assertEquals(42e-6 * 42e-6, registry.counter(id.withTag(Statistic.totalOfSquares)).actualCount(), 1e-12); assertEquals(42e-6, registry.maxGauge(id.withTag(Statistic.max)).value(), 1e-12); } @Test public void testBasicTimerRecordSeconds() { BasicTimer d = new BasicTimer(CONFIG, TimeUnit.SECONDS); register(d); d.record(42, TimeUnit.NANOSECONDS); Id id = ID.withTag("unit", "SECONDS"); assertEquals(1, registry.counter(id.withTag(Statistic.count)).count()); assertEquals(42e-9, registry.counter(id.withTag(Statistic.totalTime)).actualCount(), 1e-12); assertEquals(42e-9 * 42e-9, registry.counter(id.withTag(Statistic.totalOfSquares)).actualCount(), 1e-12); assertEquals(42e-9, registry.maxGauge(id.withTag(Statistic.max)).value(), 1e-12); } @Test public void testDynamicTimerRecordSeconds() { DynamicTimer.record(CONFIG, 42); Id id = ID.withTag("unit", "MILLISECONDS"); assertEquals(1, registry.counter(id.withTag(Statistic.count)).count()); assertEquals(42, registry.counter(id.withTag(Statistic.totalTime)).actualCount(), 1e-12); assertEquals(42 * 42, registry.counter(id.withTag(Statistic.totalOfSquares)).actualCount(), 1e-12); assertEquals(42, registry.maxGauge(id.withTag(Statistic.max)).value(), 1e-12); } @Test public void testBucketTimerRecordMillis() { BucketConfig bc = new BucketConfig.Builder() .withBuckets(new long[] {10L, 50L}) .withTimeUnit(TimeUnit.MILLISECONDS) .build(); BucketTimer d = new BucketTimer(CONFIG, bc); register(d); d.record(42, TimeUnit.MILLISECONDS); Id id = ID.withTag("unit", "MILLISECONDS"); assertEquals(1, registry.counter(id.withTag(Statistic.count).withTag("servo.bucket", "bucket=50ms")).count()); assertEquals(42.0, registry.counter(id.withTag(Statistic.totalTime)).actualCount(), 1e-12); assertEquals(42.0, registry.maxGauge(id.withTag(Statistic.max)).value(), 1e-12); } @Test public void testStatsTimerRecordMillis() { StatsConfig sc = new StatsConfig.Builder() .withPercentiles(new double[] {50.0, 95.0}) .withPublishCount(true) .withPublishMax(true) .withPublishMean(true) .withSampleSize(10) .build(); StatsTimer d = new StatsTimer(CONFIG, sc); register(d); d.record(42, TimeUnit.MILLISECONDS); d.computeStats(); Id id = ID.withTag("unit", "MILLISECONDS"); assertEquals(1, registry.counter(id.withTag(Statistic.count)).count()); assertEquals(42.0, registry.counter(id.withTag(Statistic.totalTime)).actualCount(), 1e-12); assertEquals(42.0, registry.maxGauge(id.withTag(Statistic.max)).value(), 1e-12); assertEquals(42.0, registry.gauge(id.withTag("statistic", "percentile_50")).value(), 1e-12); assertEquals(42.0, registry.gauge(id.withTag("statistic", "percentile_95")).value(), 1e-12); assertEquals(42.0, registry.gauge(id.withTag("statistic", "avg")).value(), 1e-12); } @Test public void testContextualTimerRecordMillis() { TagList context = BasicTagList.of("a", "1"); ContextualTimer d = new ContextualTimer(CONFIG, () -> context, BasicTimer::new); d.record(42, TimeUnit.NANOSECONDS); Id id = ID.withTag("unit", "MILLISECONDS").withTag("a", "1"); assertEquals(1, registry.counter(id.withTag(Statistic.count)).count()); assertEquals(42e-6, registry.counter(id.withTag(Statistic.totalTime)).actualCount(), 1e-12); assertEquals(42e-6 * 42e-6, registry.counter(id.withTag(Statistic.totalOfSquares)).actualCount(), 1e-12); assertEquals(42e-6, registry.maxGauge(id.withTag(Statistic.max)).value(), 1e-12); } public static class AnnotateExample { private long count = 0; private final BasicCounter c = new BasicCounter(CONFIG); public AnnotateExample(String id) { Monitors.registerObject(id, this); } public void update() { c.increment(); } @Monitor(name = "gauge", type = DataSourceType.GAUGE) private double gauge() { return 42.0; } @Monitor(name = "counter", type = DataSourceType.COUNTER) private long counter() { return count++; } } public static class ContextualExample { private final TagList context = BasicTagList.of("a", "2"); private final ContextualCounter c = new ContextualCounter( new MonitorConfig.Builder("counter").build(), () -> context, BasicCounter::new ); private final ContextualTimer t = new ContextualTimer( new MonitorConfig.Builder("timer").build(), () -> context, BasicTimer::new ); public ContextualExample(String id) { Monitors.registerObject(id, this); } public void update() { c.increment(); t.record(42, TimeUnit.NANOSECONDS); } } public static class CustomCompositeExample { private final DynCounter c = new DynCounter(CONFIG); public CustomCompositeExample(String id) { Monitors.registerObject(id, this); } public void update(String v) { c.increment(v); } } public static class DynCounter extends AbstractMonitor<Long> implements CompositeMonitor<Long> { private final Map<String, BasicCounter> counters = new HashMap<>(); private final MonitorConfig baseConfig; public DynCounter(MonitorConfig baseConfig) { super(baseConfig); this.baseConfig = baseConfig; } public void increment(String value) { counters.computeIfAbsent(value, v -> { MonitorConfig c = baseConfig.withAdditionalTag(new com.netflix.servo.tag.BasicTag("c", v)); return new BasicCounter(c); }).increment(); } @Override public List<com.netflix.servo.monitor.Monitor<?>> getMonitors() { return new ArrayList<>(counters.values()); } @Override public Long getValue(int pollerIndex) { return 0L; } } public static class CustomCounter implements com.netflix.servo.monitor.Monitor<Long> { private final MonitorConfig config = CONFIG.withAdditionalTag(DataSourceType.COUNTER); private long value = 0L; public void increment() { ++value; } @Override public Long getValue() { return value; } @Override public Long getValue(int pollerIndex) { return value; } @Override public MonitorConfig getConfig() { return config; } } }
2,857
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/AnnotationsTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static com.netflix.servo.annotations.DataSourceType.COUNTER; import static com.netflix.servo.annotations.DataSourceType.GAUGE; import static com.netflix.servo.annotations.DataSourceType.INFORMATIONAL; import static org.testng.Assert.assertEquals; public class AnnotationsTest { static class Metrics { @com.netflix.servo.annotations.Monitor(type = GAUGE) private final AtomicLong annoGauge = new AtomicLong(0L); @com.netflix.servo.annotations.Monitor(type = COUNTER) public final AtomicLong annoCounter = new AtomicLong(0L); @com.netflix.servo.annotations.Monitor(type = GAUGE) public final long primitiveGauge = 0L; @com.netflix.servo.annotations.Monitor(type = INFORMATIONAL) private String annoInfo() { return "foo"; } } @Test public void testDefaultNames() throws Exception { Metrics m = new Metrics(); List<Monitor<?>> monitors = new ArrayList<>(); Monitors.addAnnotatedFields(monitors, null, null, m); List<String> expectedNames = UnmodifiableList.of( "annoCounter", "annoGauge", "annoInfo", "primitiveGauge"); List<String> actualNames = monitors.stream().map( monitor -> monitor.getConfig().getName()).collect(Collectors.toList()); Collections.sort(actualNames); assertEquals(actualNames, expectedNames); } }
2,858
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/PublishingPolicyTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; public class PublishingPolicyTest extends AbstractMonitorTest<BasicCounter> { public BasicCounter newInstance(String name) { return new BasicCounter(MonitorConfig.builder(name).build()); } @Test public void testDefaultPolicy() throws Exception { assertEquals( newInstance("A").getConfig().getPublishingPolicy(), DefaultPublishingPolicy.getInstance()); } private static class OtherPolicy implements PublishingPolicy { static final OtherPolicy INSTANCE = new OtherPolicy(); } @Test public void testEqualsPolicy() throws Exception { BasicCounter other = new BasicCounter( MonitorConfig.builder("name").withPublishingPolicy(OtherPolicy.INSTANCE).build()); BasicCounter dflt = newInstance("name"); assertNotEquals(other, dflt); assertNotEquals(other.hashCode(), dflt.hashCode()); } }
2,859
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/DoubleCounterTest.java
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.util.ManualClock; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class DoubleCounterTest { private static final double DELTA = 1e-06; final ManualClock clock = new ManualClock(Pollers.POLLING_INTERVALS[1]); public DoubleCounter newInstance(String name) { return new DoubleCounter(MonitorConfig.builder(name).build(), clock); } private long time(long t) { return t * 1000 + Pollers.POLLING_INTERVALS[1]; } @Test public void testIncrement() { assertEquals(Pollers.POLLING_INTERVALS[0], 60000L); DoubleCounter c = newInstance("c"); c.increment(1.0); assertEquals(c.getCurrentCount(0), 1.0); } @Test public void testSimpleTransition() { clock.set(time(1)); DoubleCounter c = newInstance("c"); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 0.0); clock.set(time(3)); c.increment(1); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 1.0); clock.set(time(6)); c.increment(1); assertEquals(c.getValue(1).doubleValue(), 0.0, DELTA); assertEquals(c.getCurrentCount(1), 2.0); clock.set(time(12)); c.increment(1); assertEquals(c.getCurrentCount(1), 1.0); assertEquals(c.getValue(1).doubleValue(), 2.0 / 10.0); } @Test public void testInitialPollIsZero() { clock.set(time(1)); DoubleCounter c = newInstance("foo"); assertEquals(c.getValue(1).doubleValue(), 0.0); } @Test public void testHasRightType() throws Exception { assertEquals(newInstance("foo").getConfig().getTags().getValue(DataSourceType.KEY), "NORMALIZED"); } @Test public void testBoundaryTransition() { clock.set(time(1)); DoubleCounter c = newInstance("foo"); // Should all go to one bucket c.increment(1); clock.set(time(4)); c.increment(1); clock.set(time(9)); c.increment(1); // Should cause transition clock.set(time(10)); c.increment(1); clock.set(time(19)); c.increment(1); // Check counts assertEquals(c.getValue(1).doubleValue(), 0.3); assertEquals(c.getCurrentCount(1), 2.0); } @Test public void testResetPreviousValue() { clock.set(time(1)); DoubleCounter c = newInstance("foo"); for (int i = 1; i <= 100000; ++i) { c.increment(1); clock.set(time(i * 10 + 1)); assertEquals(c.getValue(1).doubleValue(), 0.1); } } @Test public void testNonMonotonicClock() { clock.set(time(1)); DoubleCounter c = newInstance("foo"); c.getValue(1); c.increment(1); c.increment(1); clock.set(time(10)); c.increment(1); clock.set(time(9)); // Should get ignored c.increment(1); assertEquals(c.getCurrentCount(1), 2.0); c.increment(1); clock.set(time(10)); c.increment(1); c.increment(1); assertEquals(c.getCurrentCount(1), 5.0); // Check rate for previous interval assertEquals(c.getValue(1).doubleValue(), 0.2); } @Test public void testGetValueTwice() { ManualClock manualClock = new ManualClock(0L); DoubleCounter c = new DoubleCounter(MonitorConfig.builder("test").build(), manualClock); c.increment(1); for (int i = 1; i < 10; ++i) { manualClock.set(i * 60000L); c.increment(1); c.getValue(0); assertEquals(c.getValue(0).doubleValue(), 1 / 60.0); } } }
2,860
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/monitor/SuperClassWithMonitors.java
package com.netflix.servo.monitor; import com.netflix.servo.annotations.*; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.TagList; public class SuperClassWithMonitors { @com.netflix.servo.annotations.Monitor public Integer monitor1; private Integer monitor2; public Integer getMonitor1() { return monitor1; } public void setMonitor1(Integer monitor1) { this.monitor1 = monitor1; } @com.netflix.servo.annotations.Monitor public Integer getMonitor2() { return monitor2; } public void setMonitor2(Integer monitor2) { this.monitor2 = monitor2; } public static class ChildClassWithMonitors extends SuperClassWithMonitors { @com.netflix.servo.annotations.Monitor public Integer monitor3; private Integer monitor4; @MonitorTags private TagList tags; public ChildClassWithMonitors() { this.tags = BasicTagList.of("tag1", "tag2"); } public Integer getMonitor3() { return monitor3; } public void setMonitor3(Integer monitor3) { this.monitor3 = monitor3; } @com.netflix.servo.annotations.Monitor public Integer getMonitor4() { return monitor4; } public void setMonitor4(Integer monitor4) { this.monitor4 = monitor4; } public TagList getTags() { return tags; } public void setTags(TagList tags) { this.tags = tags; } } }
2,861
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/util/StringsTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo.util; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class StringsTest { @Test public void testIsNullOrEmpty() throws Exception { assertTrue(Strings.isNullOrEmpty(null)); assertTrue(Strings.isNullOrEmpty("")); assertFalse(Strings.isNullOrEmpty(" ")); assertFalse(Strings.isNullOrEmpty("adsf")); } private static <T> Iterator<T> emptyIterator() { return new Iterator<T>() { @Override public boolean hasNext() { return false; } @Override public T next() { throw new NoSuchElementException(); } @Override public void remove() { throw new IllegalStateException(); } }; } @Test public void testJoin() throws Exception { assertEquals(Strings.join(", ", emptyIterator()), ""); assertEquals(Strings.join(", ", Collections.singletonList(1).iterator()), "1"); assertEquals(Strings.join(", ", Arrays.asList(1, 2).iterator()), "1, 2"); } }
2,862
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/util/ExpiringCacheTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.util; import org.testng.annotations.Test; import java.util.function.Function; import static org.testng.Assert.assertEquals; public class ExpiringCacheTest { static class CountingFun implements Function<String, Integer> { int numCalled = 0; @Override public Integer apply(String s) { ++numCalled; return s.length(); } } @Test public void testGet() throws Exception { ManualClock clock = new ManualClock(0L); CountingFun fun = new CountingFun(); ExpiringCache<String, Integer> map = new ExpiringCache<>(100L, fun, 100L, clock); Integer three = map.get("foo"); assertEquals(three, Integer.valueOf(3)); Integer threeAgain = map.get("foo"); assertEquals(threeAgain, Integer.valueOf(3)); assertEquals(fun.numCalled, 1, "Properly caches computations"); clock.set(200L); Thread.sleep(200L); Integer threeOnceMore = map.get("foo"); assertEquals(threeOnceMore, Integer.valueOf(3)); assertEquals(fun.numCalled, 2, "Properly expires unused entries"); } }
2,863
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/jmx/DefaultObjectNameMapperTest.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.jmx; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.MonitorConfig; import org.testng.annotations.Test; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import static org.testng.Assert.assertEquals; public class DefaultObjectNameMapperTest { private static final ObjectNameMapper DEFAULT_MAPPER = new DefaultObjectNameMapper(); private static final String TEST_DOMAIN = "testDomain"; @Test public void testStandardMapping() { MonitorConfig config = MonitorConfig.builder("testName").withTag("foo", "bar").build(); ObjectName name = DEFAULT_MAPPER.createObjectName(TEST_DOMAIN, new BasicCounter(config)); assertEquals(name.getDomain(), TEST_DOMAIN); // note that this assumes that DataSourceType.KEY is greater than 'foo' // for String#compareTo purposes assertEquals(name.getKeyPropertyListString(), String.format("name=testName,foo=bar,%s=COUNTER", DataSourceType.KEY)); } @Test public void testMultipleTags() throws MalformedObjectNameException { BasicCounter counter = new BasicCounter( MonitorConfig.builder("testName") .withTag("bbb", "foo") .withTag("aaa", "bar") .withTag("zzz", "test") .build()); ObjectName name = DEFAULT_MAPPER.createObjectName(TEST_DOMAIN, counter); assertEquals(name.getDomain(), TEST_DOMAIN); assertEquals(name.getKeyPropertyListString(), String.format("name=testName,aaa=bar,bbb=foo,%s=COUNTER,zzz=test", DataSourceType.KEY)); } }
2,864
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/jmx/OrderedObjectNameMapperTest.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.jmx; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.MonitorConfig; import org.testng.annotations.Test; import javax.management.ObjectName; import java.util.Arrays; import static org.testng.Assert.assertEquals; public class OrderedObjectNameMapperTest { private static final String TEST_DOMAIN = "testDomain"; private static final Counter TEST_COUNTER = new BasicCounter( MonitorConfig.builder("testName") .withTag("zzz", "zzzVal") .withTag("foo", "bar") .withTag("aaa", "aaaVal") .build()); @Test public void testOrderedTagsWithAppend() { ObjectNameMapper mapper = new OrderedObjectNameMapper(true, "name", DataSourceType.KEY, "foo", "notPresentKey"); ObjectName name = mapper.createObjectName(TEST_DOMAIN, TEST_COUNTER); assertEquals(name.getDomain(), TEST_DOMAIN); assertEquals(name.getKeyPropertyListString(), String.format("name=testName,%s=COUNTER,foo=bar,aaa=aaaVal,zzz=zzzVal", DataSourceType.KEY)); } @Test public void testOrderedTagsWithoutAppend() { ObjectNameMapper mapper = new OrderedObjectNameMapper(false, Arrays.asList("name", DataSourceType.KEY, "foo", "notPresentKey")); ObjectName name = mapper.createObjectName(TEST_DOMAIN, TEST_COUNTER); assertEquals(name.getDomain(), TEST_DOMAIN); assertEquals(name.getKeyPropertyListString(), String.format("name=testName,%s=COUNTER,foo=bar", DataSourceType.KEY)); } @Test public void testOrderedTagsWithoutNameExplicitlyOrdered() { ObjectNameMapper mapper = new OrderedObjectNameMapper(true, "foo", DataSourceType.KEY); ObjectName name = mapper.createObjectName(TEST_DOMAIN, TEST_COUNTER); assertEquals(name.getDomain(), TEST_DOMAIN); assertEquals(name.getKeyPropertyListString(), String.format("foo=bar,%s=COUNTER,name=testName,aaa=aaaVal,zzz=zzzVal", DataSourceType.KEY)); } }
2,865
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/jmx/ObjectNameBuilderTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo.jmx; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tags; import org.testng.annotations.Test; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; public class ObjectNameBuilderTest { @Test public void testInvalidCharactersSanitized() { ObjectName name = ObjectNameBuilder.forDomain("test*Domain&") .addProperty("foo%", "$bar") .build(); assertEquals(name.getDomain(), "test_Domain_"); assertEquals(name.getKeyPropertyListString(), "foo_=_bar"); } @Test public void testAddTagList() { ObjectName name = ObjectNameBuilder.forDomain("testDomain") .addProperties(BasicTagList.of("foo", "bar", "test", "stuff")) .build(); assertEquals(name.getDomain(), "testDomain"); assertEquals(name.getKeyPropertyListString(), "foo=bar,test=stuff"); } @Test public void testTagByTag() { // Order will be in the order tags were added to the builder ObjectName name = ObjectNameBuilder.forDomain("testDomain") .addProperty(Tags.newTag("foo", "bar")) .addProperty(Tags.newTag("test", "stuff")) .build(); assertEquals(name.getDomain(), "testDomain"); assertEquals(name.getKeyPropertyListString(), "foo=bar,test=stuff"); } @Test public void testBuildWithoutPropertyAdded() { try { ObjectNameBuilder.forDomain("testDomain").build(); fail("Should have thrown an exception without keys being added!"); } catch (RuntimeException expected) { assertEquals(expected.getCause().getClass(), MalformedObjectNameException.class); } } }
2,866
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/MemoryMetricObserverTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.assertEquals; public class MemoryMetricObserverTest { private List<Metric> mkList(int v) { return UnmodifiableList.of(new Metric("m", SortedTagList.EMPTY, 0L, v)); } @Test public void testUpdate() throws Exception { MemoryMetricObserver mmo = new MemoryMetricObserver("test", 2); mmo.update(mkList(1)); assertEquals(mmo.getObservations(), UnmodifiableList.of(mkList(1))); } @Test public void testExceedN() throws Exception { MemoryMetricObserver mmo = new MemoryMetricObserver("test", 2); mmo.update(mkList(1)); mmo.update(mkList(2)); mmo.update(mkList(3)); assertEquals(mmo.getObservations(), UnmodifiableList.of(mkList(2), mkList(3))); } }
2,867
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/MonitorRegistryMetricPollerTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.BasicMonitorRegistry; import com.netflix.servo.Metric; import com.netflix.servo.MonitorRegistry; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.AbstractMonitor; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import org.testng.annotations.Test; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.concurrent.atomic.AtomicLong; import static com.netflix.servo.publish.BasicMetricFilter.MATCH_ALL; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class MonitorRegistryMetricPollerTest { private static final long TEN_SECONDS = 10 * 1000; private static final long ONE_MINUTE = 60 * 1000; private static final long ONE_HOUR = 60 * ONE_MINUTE; @Test public void testBasic() throws Exception { MonitorRegistry registry = new BasicMonitorRegistry(); registry.register(Monitors.newCounter("test")); MetricPoller poller = new MonitorRegistryMetricPoller(registry); Metric metric = poller.poll(MATCH_ALL).get(0); MonitorConfig expected = MonitorConfig.builder("test") .withTag(DataSourceType.COUNTER) .build(); assertEquals(metric.getConfig(), expected); } @Test public void testSlowMonitor() throws Exception { MonitorRegistry registry = new BasicMonitorRegistry(); registry.register(new SlowCounter("slow")); registry.register(Monitors.newCounter("test")); MetricPoller poller = new MonitorRegistryMetricPoller(registry); long start = System.currentTimeMillis(); Metric metric = poller.poll(MATCH_ALL).get(0); long end = System.currentTimeMillis(); // Verify we didn't wait too long, we should only wait 1 second but allow up to // 10 to make it less likely to have spurious test failures assertTrue(end - start < TEN_SECONDS); MonitorConfig expected = MonitorConfig.builder("test") .withTag(DataSourceType.COUNTER) .build(); assertEquals(metric.getConfig(), expected); } @Test(enabled = false) public void testShutdown() throws Exception { MonitorRegistry registry = new BasicMonitorRegistry(); registry.register(Monitors.newCounter("test")); final String threadPrefix = "ServoMonitorGetValueLimiter"; Thread.sleep(1000); int baseCount = countThreadsWithName(threadPrefix); MonitorRegistryMetricPoller[] pollers = new MonitorRegistryMetricPoller[10]; for (int i = 0; i < pollers.length; ++i) { pollers[i] = new MonitorRegistryMetricPoller(registry); pollers[i].poll(MATCH_ALL); } int retries = 0; for (; retries < 10; ++retries) { int currentThreads = countThreadsWithName(threadPrefix); if (currentThreads >= 10 + baseCount) { break; } System.err.println(String.format("currentThreads: %d/%d", currentThreads, baseCount)); Thread.sleep(200); } assertTrue(retries < 10); for (MonitorRegistryMetricPoller poller : pollers) { poller.shutdown(); } Thread.sleep(1000); assertTrue(countThreadsWithName(threadPrefix) <= baseCount); // Verify threads will be cleanup up by gc /*System.err.println("pre-gc: " + countThreadsWithName("ServoMonitorGetValueLimiter")); for (int i = 0; i < pollers.length; ++i) { pollers[i] = null; } System.gc(); Thread.sleep(1000); System.err.println("post-gc: " + countThreadsWithName("ServoMonitorGetValueLimiter"));*/ } private int countThreadsWithName(String prefix) { final ThreadMXBean bean = ManagementFactory.getThreadMXBean(); final long[] ids = bean.getAllThreadIds(); final ThreadInfo[] infos = bean.getThreadInfo(ids); int count = 0; for (ThreadInfo info : infos) { if (info != null && info.getThreadName().startsWith(prefix)) { ++count; } } return count; } private static class SlowCounter extends AbstractMonitor<Number> implements Counter { private final AtomicLong count = new AtomicLong(); public SlowCounter(String name) { super(MonitorConfig.builder(name).withTag(DataSourceType.COUNTER).build()); } @Override public void increment() { count.incrementAndGet(); } @Override public void increment(long amount) { count.getAndAdd(amount); } @Override public Number getValue(int pollerIndex) { try { Thread.sleep(ONE_HOUR); } catch (Exception e) { System.err.println("Ignoring exception " + e.getMessage()); } return count.get(); } } }
2,868
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/BasicMetricFilterTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.assertEquals; public class BasicMetricFilterTest { private List<Metric> mkList() { return UnmodifiableList.of( new Metric("m1", SortedTagList.EMPTY, 0L, 0), new Metric("m2", SortedTagList.builder().withTag("c", "a.b.c.d.M1").build(), 0L, 0), new Metric("m3", SortedTagList.builder().withTag("c", "a.b.c.c.M3").build(), 0L, 0), new Metric("m4", SortedTagList.builder().withTag("c", "a.b.c.d.M4").build(), 0L, 0), new Metric("m5", SortedTagList.builder().withTag("c", "a.a.a.a.M5").build(), 0L, 0) ); } private MetricPoller newPoller() { MockMetricPoller poller = new MockMetricPoller(); poller.setMetrics(mkList()); return poller; } @Test public void testFilterFalse() throws Exception { MetricPoller poller = newPoller(); assertEquals(poller.poll(new BasicMetricFilter(false)).size(), 0); } @Test public void testFilterTrue() throws Exception { MetricPoller poller = newPoller(); assertEquals(poller.poll(new BasicMetricFilter(true)), mkList()); } }
2,869
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/CounterToRateMetricTransformTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class CounterToRateMetricTransformTest { private static final TagList GAUGE = SortedTagList.builder() .withTag(DataSourceType.GAUGE) .build(); private static final TagList COUNTER = SortedTagList.builder() .withTag(DataSourceType.COUNTER) .build(); private List<Metric> mkList(long ts, int value) { return UnmodifiableList.of( new Metric("m1", SortedTagList.EMPTY, ts, value), new Metric("m2", GAUGE, ts, value), new Metric("m3", COUNTER, ts, value) ); } private Map<String, Double> mkMap(List<List<Metric>> updates) { Map<String, Double> map = new HashMap<>(); for (Metric m : updates.get(0)) { map.put(m.getConfig().getName(), m.getNumberValue().doubleValue()); } return map; } private Map<String, String> mkTypeMap(List<List<Metric>> updates) { Map<String, String> map = new HashMap<>(); for (Metric m : updates.get(0)) { map.put(m.getConfig().getName(), m.getConfig().getTags().getValue(DataSourceType.KEY)); } return map; } @Test public void testResultingType() throws Exception { MemoryMetricObserver mmo = new MemoryMetricObserver("m", 1); MetricObserver transform = new CounterToRateMetricTransform(mmo, 120, TimeUnit.SECONDS); Map<String, String> metrics; // Make time look like the future to avoid expirations long baseTime = System.currentTimeMillis() + 100000L; // First sample transform.update(mkList(baseTime + 0, 0)); metrics = mkTypeMap(mmo.getObservations()); assertEquals(metrics.size(), 2); assertEquals(metrics.get("m3"), null); assertEquals(metrics.get("m2"), "GAUGE"); assertEquals(metrics.get("m1"), null); transform.update(mkList(baseTime + 5000, 5)); metrics = mkTypeMap(mmo.getObservations()); assertEquals(metrics.size(), 3); assertEquals(metrics.get("m3"), "RATE"); assertEquals(metrics.get("m2"), "GAUGE"); assertEquals(metrics.get("m1"), null); } @Test public void testSimpleRate() throws Exception { MemoryMetricObserver mmo = new MemoryMetricObserver("m", 1); MetricObserver transform = new CounterToRateMetricTransform(mmo, 120, TimeUnit.SECONDS); Map<String, Double> metrics; // Make time look like the future to avoid expirations long baseTime = System.currentTimeMillis() + 100000L; // First sample transform.update(mkList(baseTime + 0, 0)); metrics = mkMap(mmo.getObservations()); assertEquals(metrics.size(), 2); assertTrue(metrics.get("m3") == null); // Delta of 5 in 5 seconds transform.update(mkList(baseTime + 5000, 5)); metrics = mkMap(mmo.getObservations()); assertEquals(metrics.size(), 3); assertEquals(metrics.get("m3"), 1.0, 0.00001); // Delta of 15 in 5 seconds transform.update(mkList(baseTime + 10000, 20)); metrics = mkMap(mmo.getObservations()); assertEquals(metrics.size(), 3); assertEquals(metrics.get("m3"), 3.0, 0.00001); // No change from previous sample transform.update(mkList(baseTime + 15000, 20)); metrics = mkMap(mmo.getObservations()); assertEquals(metrics.size(), 3); assertEquals(metrics.get("m3"), 0.0, 0.00001); // Decrease from previous sample transform.update(mkList(baseTime + 20000, 19)); metrics = mkMap(mmo.getObservations()); assertEquals(metrics.size(), 3); assertEquals(metrics.get("m3"), 0.0, 0.00001); } @Test public void testFirstSample() throws Exception { MemoryMetricObserver mmo = new MemoryMetricObserver("m", 1); MetricObserver transform = new CounterToRateMetricTransform(mmo, 120, 5, TimeUnit.SECONDS); Map<String, Double> metrics; // Make time look like the future to avoid expirations long baseTime = System.currentTimeMillis() + 100000L; // First sample transform.update(mkList(baseTime + 0, 10)); metrics = mkMap(mmo.getObservations()); assertEquals(metrics.size(), 3); assertEquals(metrics.get("m3"), 2.0, 0.00001); // Delta of 5 in 5 seconds transform.update(mkList(baseTime + 5000, 15)); metrics = mkMap(mmo.getObservations()); assertEquals(metrics.size(), 3); assertEquals(metrics.get("m3"), 1.0, 0.00001); } }
2,870
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/JmxMetricPollerTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.tag.Tags; import org.testng.annotations.Test; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.netflix.servo.publish.BasicMetricFilter.MATCH_ALL; import static com.netflix.servo.publish.BasicMetricFilter.MATCH_NONE; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class JmxMetricPollerTest { @Test public void testBasic() throws Exception { MetricPoller poller = new JmxMetricPoller( new LocalJmxConnector(), new ObjectName("java.lang:type=OperatingSystem"), MATCH_NONE); boolean found = false; List<Metric> metrics = poller.poll(MATCH_ALL); for (Metric m : metrics) { if ("AvailableProcessors".equals(m.getConfig().getName())) { found = true; Map<String, String> tags = m.getConfig().getTags().asMap(); assertEquals(tags.get("JmxDomain"), "java.lang"); assertEquals(tags.get("Jmx.type"), "OperatingSystem"); assertEquals(tags.get("ClassName"), "com.netflix.servo.publish.JmxMetricPoller"); assertEquals(tags.get(DataSourceType.KEY), "GAUGE"); } } assertTrue(found); } @Test public void testCounterFilter() throws Exception { MetricPoller poller = new JmxMetricPoller( new LocalJmxConnector(), new ObjectName("java.lang:type=OperatingSystem"), MATCH_ALL); boolean found = false; List<Metric> metrics = poller.poll(MATCH_ALL); for (Metric m : metrics) { if ("AvailableProcessors".equals(m.getConfig().getName())) { found = true; Map<String, String> tags = m.getConfig().getTags().asMap(); assertEquals(tags.get("JmxDomain"), "java.lang"); assertEquals(tags.get("Jmx.type"), "OperatingSystem"); assertEquals(tags.get("ClassName"), "com.netflix.servo.publish.JmxMetricPoller"); assertEquals(tags.get(DataSourceType.KEY), "COUNTER"); } } assertTrue(found); } /** * Tabular JMX values are very useful for cases where we want the same behavior as CompositePath but we * don't know up front what the values are going to be. */ @Test public void testTabularData() throws Exception { MapMXBean mapMXBean = new MapMXBean(); try { MetricPoller poller = new JmxMetricPoller( new LocalJmxConnector(), new ObjectName("com.netflix.servo.test:*"), MATCH_ALL); List<Metric> metrics = poller.poll(config -> config.getName().equals("Count")); assertEquals(metrics.size(), 2); Map<String, Integer> values = new HashMap<>(); for (Metric m : metrics) { values.put(m.getConfig().getTags().getTag("JmxCompositePath").getValue(), (Integer) m.getValue()); } assertEquals(values.get("Entry1"), (Integer) 111); assertEquals(values.get("Entry2"), (Integer) 222); } finally { mapMXBean.destroy(); } } public interface TestMapMXBean { Map<String, Integer> getCount(); String getStringValue(); } public static class MapMXBean implements TestMapMXBean { private final ObjectName objectName; MapMXBean() throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); objectName = new ObjectName("com.netflix.servo.test", "Test", "Obj"); destroy(); mbs.registerMBean(this, objectName); } public void destroy() throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); if (mbs.isRegistered(objectName)) { mbs.unregisterMBean(objectName); } } @Override public Map<String, Integer> getCount() { Map<String, Integer> map = new HashMap<>(); map.put("Entry1", 111); map.put("Entry2", 222); return map; } @Override public String getStringValue() { return "AStringResult"; } } @Test public void testDefaultTags() throws Exception { MetricPoller poller = new JmxMetricPoller( new LocalJmxConnector(), Collections.singletonList(new ObjectName("java.lang:type=OperatingSystem")), MATCH_ALL, true, Collections.singletonList(Tags.newTag("HostName", "localhost"))); List<Metric> metrics = poller.poll(MATCH_ALL); for (Metric m : metrics) { Map<String, String> tags = m.getConfig().getTags().asMap(); assertEquals(tags.get("HostName"), "localhost"); } } @Test public void testNonNumericMetrics() throws Exception { MapMXBean mapMXBean = new MapMXBean(); try { MetricPoller poller = new JmxMetricPoller( new LocalJmxConnector(), Collections.singletonList(new ObjectName("com.netflix.servo.test:*")), MATCH_ALL, false, null); List<Metric> metrics = poller.poll(config -> config.getName().equals("StringValue")); assertEquals(metrics.size(), 1); assertEquals(metrics.get(0).getValue(), "AStringResult"); } finally { mapMXBean.destroy(); } } }
2,871
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/MockMetricPoller.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.util.UnmodifiableList; import java.util.List; public class MockMetricPoller extends BaseMetricPoller { private List<Metric> metrics; private long delay; private boolean die; public MockMetricPoller() { metrics = UnmodifiableList.of(); delay = 0L; } public void setMetrics(List<Metric> metrics) { this.metrics = UnmodifiableList.copyOf(metrics); } public void setDelay(long delay) { this.delay = delay; } public void setDie(boolean die) { this.die = die; } public List<Metric> pollImpl(boolean reset) { if (die) { throw new IllegalStateException("die"); } try { Thread.sleep(delay); } catch (InterruptedException e) { System.err.println("Ignoring " + e.getMessage()); } return metrics; } }
2,872
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/CompositeMetricPollerTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.util.Iterables; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.netflix.servo.publish.BasicMetricFilter.MATCH_ALL; import static org.testng.Assert.assertEquals; public class CompositeMetricPollerTest { private List<Metric> mkList() { return UnmodifiableList.of( new Metric("m1", SortedTagList.EMPTY, 0L, 0), new Metric("m2", SortedTagList.builder().withTag("c", "a.b.c.d.M1").build(), 0L, 0), new Metric("m3", SortedTagList.builder().withTag("c", "a.b.c.c.M3").build(), 0L, 0), new Metric("m4", SortedTagList.builder().withTag("c", "a.b.c.d.M4").build(), 0L, 0), new Metric("m5", SortedTagList.builder().withTag("c", "a.a.a.a.M5").build(), 0L, 0) ); } private MetricPoller newPoller(long delay) { MockMetricPoller poller = new MockMetricPoller(); poller.setMetrics(mkList()); poller.setDelay(delay); return poller; } @Test public void testBasic() throws Exception { Map<String, MetricPoller> pollers = new HashMap<>(); pollers.put("p1", newPoller(0)); ExecutorService exec = Executors.newFixedThreadPool(1); MetricPoller poller = new CompositeMetricPoller(pollers, exec, 10000); assertEquals(poller.poll(MATCH_ALL), mkList()); } @Test public void testMultiple() throws Exception { Map<String, MetricPoller> pollers = new HashMap<>(); pollers.put("p1", newPoller(0)); pollers.put("p2", newPoller(0)); ExecutorService exec = Executors.newFixedThreadPool(1); MetricPoller poller = new CompositeMetricPoller(pollers, exec, 10000); assertEquals(poller.poll(MATCH_ALL), UnmodifiableList.copyOf(Iterables.concat(mkList(), mkList()))); } @Test public void testTimeout() throws Exception { // Note: java8 changes the hashing/traversal order so you can see slightly different // behavior if there is a bug. In particular before we were cancelling the future on // timeout, then if the p2 key times out it will fail on java7 and pass on java8. // If the p1 key times out the opposite. Map<String, MetricPoller> pollers = new HashMap<>(); pollers.put("p1", newPoller(120000)); pollers.put("p2", newPoller(0)); // To make it fail regardless of jdk version if there is an issue pollers.put("p3", newPoller(120000)); pollers.put("p4", newPoller(120000)); pollers.put("p5", newPoller(120000)); ExecutorService exec = Executors.newFixedThreadPool(1); MetricPoller poller = new CompositeMetricPoller(pollers, exec, 500); assertEquals(poller.poll(MATCH_ALL), mkList()); } @Test public void testException() throws Exception { MockMetricPoller mock = new MockMetricPoller(); mock.setDie(true); Map<String, MetricPoller> pollers = new HashMap<>(); pollers.put("p1", mock); pollers.put("p2", newPoller(0)); ExecutorService exec = Executors.newFixedThreadPool(1); MetricPoller poller = new CompositeMetricPoller(pollers, exec, 10000); assertEquals(poller.poll(MATCH_ALL), mkList()); } }
2,873
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/AsyncMetricObserverTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class AsyncMetricObserverTest { private List<Metric> mkList(int v) { return UnmodifiableList.of(new Metric("m", SortedTagList.EMPTY, 0L, v)); } @Test public void testUpdate() throws Exception { MemoryMetricObserver mmo = new MemoryMetricObserver("mem", 50); AsyncMetricObserver amo = new AsyncMetricObserver("async", mmo, 50); amo.update(mkList(1)); amo.update(mkList(2)); amo.update(mkList(3)); amo.update(mkList(4)); Thread.sleep(1000); assertEquals(mmo.getObservations(), UnmodifiableList.of(mkList(1), mkList(2), mkList(3), mkList(4))); amo.stop(); } @Test public void testExceedQueueSize() throws Exception { MemoryMetricObserver mmo = new MemoryMetricObserver("mem", 50); MetricObserver smo = new SlowMetricObserver(mmo, 500L); AsyncMetricObserver amo = new AsyncMetricObserver("async", smo, 2); amo.update(mkList(1)); amo.update(mkList(2)); amo.update(mkList(3)); amo.update(mkList(4)); Thread.sleep(4000); // We should always get at least queueSize updates List<List<Metric>> observations = mmo.getObservations(); assertTrue(observations.size() >= 2); // Older entries are overwritten, the last queueSize updates should // be in the output int last = observations.size() - 1; assertEquals(observations.get(last - 1), mkList(3)); assertEquals(observations.get(last), mkList(4)); amo.stop(); } @Test public void testExpiration() throws Exception { MemoryMetricObserver mmo = new MemoryMetricObserver("mem", 50); MetricObserver smo = new SlowMetricObserver(mmo, 500L); AsyncMetricObserver amo = new AsyncMetricObserver("async", smo, 50, 250); amo.update(mkList(1)); amo.update(mkList(2)); amo.update(mkList(3)); amo.update(mkList(4)); Thread.sleep(4000); // Only the first update should have made it on time List<List<Metric>> observations = mmo.getObservations(); assertEquals(observations.size(), 1); assertEquals(observations.get(0), mkList(1)); amo.stop(); } @Test public void testFailedUpdate() throws Exception { // Just making sure exception does not propagate MetricObserver fmo = new FailingMetricObserver(); AsyncMetricObserver amo = new AsyncMetricObserver("async", fmo, 50, 250); amo.update(mkList(1)); amo.update(mkList(1)); amo.update(mkList(1)); amo.update(mkList(1)); amo.update(mkList(1)); amo.update(mkList(1)); Thread.sleep(1000); amo.stop(); } }
2,874
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/PrefixMetricFilterTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.List; import java.util.NavigableMap; import java.util.TreeMap; import static com.netflix.servo.publish.BasicMetricFilter.MATCH_ALL; import static com.netflix.servo.publish.BasicMetricFilter.MATCH_NONE; import static org.testng.Assert.assertEquals; public class PrefixMetricFilterTest { private List<Metric> mkList() { return UnmodifiableList.of( new Metric("m1", SortedTagList.EMPTY, 0L, 0), new Metric("m2", SortedTagList.builder().withTag("c", "a.b.c.d.M1").build(), 0L, 0), new Metric("m3", SortedTagList.builder().withTag("c", "a.b.c.c.M3").build(), 0L, 0), new Metric("m4", SortedTagList.builder().withTag("c", "a.b.c.d.M4").build(), 0L, 0), new Metric("m5", SortedTagList.builder().withTag("c", "a.a.a.a.M5").build(), 0L, 0) ); } private MetricPoller newPoller() { MockMetricPoller poller = new MockMetricPoller(); poller.setMetrics(mkList()); return poller; } @Test public void testPrefixFilter() throws Exception { NavigableMap<String, MetricFilter> filters = new TreeMap<>(); filters.put("a.b.c", MATCH_ALL); MetricFilter filter = new PrefixMetricFilter("c", MATCH_NONE, filters); MetricPoller poller = newPoller(); List<Metric> metrics = poller.poll(filter); assertEquals(metrics.size(), 3); } @Test public void testLongestPrefixFilter() throws Exception { NavigableMap<String, MetricFilter> filters = new TreeMap<>(); filters.put("a.b.c", MATCH_ALL); filters.put("a.b.c.c", MATCH_NONE); MetricFilter filter = new PrefixMetricFilter("c", MATCH_NONE, filters); MetricPoller poller = newPoller(); List<Metric> metrics = poller.poll(filter); assertEquals(metrics.size(), 2); } @Test public void testPrefixFilterOnName() throws Exception { NavigableMap<String, MetricFilter> filters = new TreeMap<>(); filters.put("m", MATCH_ALL); MetricFilter filter = new PrefixMetricFilter(null, MATCH_NONE, filters); MetricPoller poller = newPoller(); List<Metric> metrics = poller.poll(filter); assertEquals(metrics.size(), 5); } }
2,875
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/FileMetricObserverTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import org.testng.annotations.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class FileMetricObserverTest { private static final TagList TAGS = SortedTagList.builder() .withTag("cluster", "foo") .withTag("zone", "a") .withTag("node", "i-123") .build(); private List<Metric> mkList(int v) { List<Metric> metrics = new ArrayList<>(v); for (int i = 0; i < v; ++i) { metrics.add(new Metric("m", TAGS, 0L, i)); } return metrics; } private void delete(File f) throws IOException { if (f.exists() && !f.delete()) { throw new IOException("could not delete " + f); } } private void deleteRecursively(File f) throws IOException { if (f.isDirectory()) { for (File file : f.listFiles()) { deleteRecursively(file); } delete(f); } else { delete(f); } } private void checkLine(int i, String line) { String[] parts = line.split("\t"); assertEquals(parts.length, 3); assertEquals(parts[0], "m"); for (Tag tag : TAGS) { String tagStr = tag.getKey() + "=" + tag.getValue(); assertTrue(parts[1].contains(tagStr), "missing " + tagStr); } assertEquals(Integer.parseInt(parts[2]), i); } private void checkFile(File f, boolean compressed) throws IOException { InputStream is = new FileInputStream(f); if (compressed) { is = new GZIPInputStream(is); } try (BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { int i = 0; String line; while ((line = in.readLine()) != null) { checkLine(i, line); ++i; } } } private static File createTempDir() { File baseDir = new File(System.getProperty("java.io.tmpdir")); String baseName = System.currentTimeMillis() + "-"; for (int counter = 0; counter < 3; counter++) { File tempDir = new File(baseDir, baseName + counter); if (tempDir.mkdir()) { return tempDir; } } throw new IllegalStateException("Failed to create directory within 3 attempts (tried " + baseName + "0 to " + baseName + "2)"); } @Test public void testUpdate() throws Exception { File dir = createTempDir(); try { MetricObserver fmo = new FileMetricObserver("test", dir); fmo.update(mkList(1)); Thread.sleep(250); fmo.update(mkList(2)); Thread.sleep(250); fmo.update(mkList(3)); File[] files = dir.listFiles(); assert files != null; assertEquals(files.length, 3); for (File f : files) { checkFile(f, false); } } finally { deleteRecursively(dir); } } @Test public void testUpdateCompressed() throws Exception { File dir = createTempDir(); try { MetricObserver fmo = new FileMetricObserver("test", dir, true); fmo.update(mkList(1)); Thread.sleep(250); fmo.update(mkList(2)); Thread.sleep(250); fmo.update(mkList(3)); File[] files = dir.listFiles(); assert files != null; assertEquals(files.length, 3); for (File f : files) { checkFile(f, true); } } finally { deleteRecursively(dir); } } }
2,876
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/SlowMetricObserver.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class SlowMetricObserver extends BaseMetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(SlowMetricObserver.class); private final MetricObserver wrappedObserver; private final long delay; public SlowMetricObserver(MetricObserver observer, long delay) { super("slow"); this.wrappedObserver = observer; this.delay = delay; } public void updateImpl(List<Metric> metrics) { try { Thread.sleep(delay); } catch (InterruptedException e) { LOGGER.warn("sleep interrupted", e); } wrappedObserver.update(metrics); } }
2,877
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/PollSchedulerTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import org.testng.annotations.Test; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; public class PollSchedulerTest { @Test public void testGetInstance() throws Exception { PollScheduler p = PollScheduler.getInstance(); assertNotNull(p); } @Test public void testStartNoArg() throws Exception { PollScheduler.getInstance().start(); assertTrue(PollScheduler.getInstance().isStarted()); PollScheduler.getInstance().stop(); } @Test public void testStart() throws Exception { ScheduledExecutorService s = Executors.newScheduledThreadPool(2); PollScheduler.getInstance().start(s); assertTrue(PollScheduler.getInstance().isStarted()); //PollScheduler.getInstance().addPoller( ,60, TimeUnit.SECONDS); PollScheduler.getInstance().stop(); } @Test public void testStop() throws Exception { ScheduledExecutorService s = Executors.newScheduledThreadPool(2); PollScheduler.getInstance().start(s); assertTrue(PollScheduler.getInstance().isStarted()); PollScheduler.getInstance().stop(); assertTrue(!PollScheduler.getInstance().isStarted()); assertTrue(s.isShutdown()); } }
2,878
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/NormalizationTransformTest.java
/** * Copyright 2014 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.monitor.AbstractMonitor; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.LongGauge; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.StepCounter; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ManualClock; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; public class NormalizationTransformTest { Metric newMetric(long t, double v) { return new Metric(MonitorConfig.builder("test").build(), t, v); } static class TimeVal { final long t; final double v; static TimeVal from(long t, double v) { return new TimeVal(t, v); } static TimeVal from(Metric m) { return new TimeVal(m.getTimestamp(), m.getNumberValue().doubleValue()); } TimeVal(long t, double v) { this.t = t; this.v = v; } @Override public String toString() { return "TimeVal{t=" + t + ", v=" + v + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeVal timeVal = (TimeVal) o; return t == timeVal.t && Double.compare(timeVal.v, v) == 0; } @Override public int hashCode() { int result; long temp; result = (int) (t ^ (t >>> 32)); temp = Double.doubleToLongBits(v); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } } void assertMetrics(long step, long heartbeat, List<Metric> input, List<TimeVal> expected) { ManualClock clock = new ManualClock(0); MemoryMetricObserver mmo = new MemoryMetricObserver("m", 1); MetricObserver transform = new NormalizationTransform(mmo, step, heartbeat, TimeUnit.MILLISECONDS, clock); int i = 0; for (Metric m : input) { transform.update(UnmodifiableList.of(m)); Metric result = mmo.getObservations().get(0).get(0); assertEquals(TimeVal.from(result), expected.get(i)); i++; } } @Test public void testBasic() throws Exception { List<Metric> inputList = UnmodifiableList.of( newMetric(5, 1.0), newMetric(15, 2.0), newMetric(25, 2.0), newMetric(35, 1.0), newMetric(85, 1.0), newMetric(95, 2.0), newMetric(105, 2.0)); List<TimeVal> expected = UnmodifiableList.of( TimeVal.from(0, 0.5), TimeVal.from(10, 1.5), TimeVal.from(20, 2.0), TimeVal.from(30, 1.5), TimeVal.from(80, 0.5), TimeVal.from(90, 1.5), TimeVal.from(100, 2.0) ); assertMetrics(10, 20, inputList, expected); } @Test public void testAlreadyNormalized() throws Exception { List<Metric> inputList = UnmodifiableList.of( newMetric(0, 10.0), newMetric(10, 20.0), newMetric(20, 30.0), newMetric(30, 10.0)); List<TimeVal> expected = UnmodifiableList.of( TimeVal.from(0, 10.0), TimeVal.from(10, 20.0), TimeVal.from(20, 30.0), TimeVal.from(30, 10.0)); assertMetrics(10, 20, inputList, expected); } @Test public void testNormalizedMissedHeartbeat() throws Exception { List<Metric> inputList = UnmodifiableList.of( newMetric(0, 10.0), newMetric(10, 10.0), newMetric(30, 10.0)); List<TimeVal> expected = UnmodifiableList.of( TimeVal.from(0, 10.0), TimeVal.from(10, 10.0), TimeVal.from(30, 10.0)); assertMetrics(10, 20, inputList, expected); } long t(int m, int s) { return (m * 60 + s) * 1000L; } @Test public void testRandomOffset() throws Exception { List<Metric> inputList = UnmodifiableList.of( newMetric(t(1, 13), 1.0), newMetric(t(2, 13), 1.0), newMetric(t(3, 13), 1.0)); List<TimeVal> expected = UnmodifiableList.of( TimeVal.from(t(1, 0), 47.0 / 60.0), TimeVal.from(t(2, 0), 1.0), TimeVal.from(t(3, 0), 1.0)); assertMetrics(60000, 120000, inputList, expected); } private List<Metric> getValue(List<? extends AbstractMonitor<? extends Number>> monitors, Clock clock) { List<Metric> result = new ArrayList<>(); for (AbstractMonitor<? extends Number> m : monitors) { Number n = m.getValue(0); Metric metric = new Metric(m.getConfig(), clock.now(), n); result.add(metric); } return result; } private static final double DELTA = 1e-6; @Test public void testUpdate() throws Exception { BasicCounter basicCounter = new BasicCounter(MonitorConfig.builder("basicCounter").build()); ManualClock manualClock = new ManualClock(0); StepCounter stepCounter = new StepCounter(MonitorConfig.builder("stepCounter").build(), manualClock); LongGauge gauge = new LongGauge(MonitorConfig.builder("longGauge").build()); List<? extends AbstractMonitor<? extends Number>> monitors = UnmodifiableList.of(basicCounter, stepCounter, gauge); MemoryMetricObserver observer = new MemoryMetricObserver("normalization-test", 1); NormalizationTransform normalizationTransform = new NormalizationTransform(observer, 60, 120, TimeUnit.SECONDS, manualClock); CounterToRateMetricTransform toRateMetricTransform = new CounterToRateMetricTransform(normalizationTransform, 60, 120, TimeUnit.SECONDS, manualClock); double[] rates = {0.5 / 60.0, 2 / 60.0, 3 / 60.0, 4 / 60.0}; double[] expectedNormalized = { rates[0] * (2.0 / 3.0), // 20000L over stepBoundary rates[0] * (1.0 / 3.0) + rates[1] * (2.0 / 3.0), rates[1] * (1.0 / 3.0) + rates[2] * (2.0 / 3.0), rates[2] * (1.0 / 3.0) + rates[3] * (2.0 / 3.0)}; for (int i = 1; i < 5; ++i) { long now = 20000L + i * 60000L; long stepBoundary = i * 60000L; manualClock.set(now); basicCounter.increment(i); stepCounter.increment(i); gauge.set((long) i); List<Metric> metrics = getValue(monitors, manualClock); toRateMetricTransform.update(metrics); List<Metric> o = observer.getObservations().get(0); assertEquals(o.size(), 3); double basicCounterVal = o.get(0).getNumberValue().doubleValue(); double stepCounterVal = o.get(1).getNumberValue().doubleValue(); double gaugeVal = o.get(2).getNumberValue().doubleValue(); assertEquals(gaugeVal, (double) i, DELTA); // rate per second for the prev interval assertEquals(stepCounterVal, (i - 1) / 60.0, DELTA); assertEquals(basicCounterVal, expectedNormalized[i - 1], DELTA); for (Metric m : o) { assertEquals(m.getTimestamp(), stepBoundary); } } // no updates to anything, just clock forward int i = 5; manualClock.set(i * 60000L + 20000L); List<Metric> metrics = getValue(monitors, manualClock); toRateMetricTransform.update(metrics); List<Metric> o = observer.getObservations().get(0); assertEquals(o.size(), 3); double basicCounterVal = o.get(0).getNumberValue().doubleValue(); double stepCounterVal = o.get(1).getNumberValue().doubleValue(); double gaugeVal = o.get(2).getNumberValue().doubleValue(); assertEquals(gaugeVal, (double) 4, DELTA); // last set value assertEquals(stepCounterVal, 4 / 60.0, DELTA); assertEquals(basicCounterVal, (1 / 3.0) * rates[3]); } @Test public void testExpiration() { BasicCounter c1 = new BasicCounter(MonitorConfig.builder("c1").build()); BasicCounter c2 = new BasicCounter(MonitorConfig.builder("c2").build()); BasicCounter c3 = new BasicCounter(MonitorConfig.builder("c3").build()); ManualClock manualClock = new ManualClock(0); MemoryMetricObserver observer = new MemoryMetricObserver("normalization-test", 1); NormalizationTransform normalizationTransform = new NormalizationTransform(observer, 60, 120, TimeUnit.SECONDS, manualClock); CounterToRateMetricTransform toRateMetricTransform = new CounterToRateMetricTransform(normalizationTransform, 60, 120, TimeUnit.SECONDS, manualClock); manualClock.set(30000L); c1.increment(); Metric m1 = new Metric(c1.getConfig(), manualClock.now(), c1.getValue(0)); toRateMetricTransform.update(UnmodifiableList.of(m1)); assertEquals(NormalizationTransform.HEARTBEAT_EXCEEDED.getValue(0).longValue(), 0); List<Metric> o = observer.getObservations().get(0); assertEquals(o.size(), 1); manualClock.set(100000L); Metric m2 = new Metric(c2.getConfig(), manualClock.now(), c2.getValue()); toRateMetricTransform.update(UnmodifiableList.of(m2)); assertEquals(NormalizationTransform.HEARTBEAT_EXCEEDED.getValue(0).longValue(), 0); manualClock.set(160000L); Metric m3 = new Metric(c3.getConfig(), manualClock.now(), c3.getValue()); toRateMetricTransform.update(UnmodifiableList.of(m3)); assertEquals(NormalizationTransform.HEARTBEAT_EXCEEDED.getValue(0).longValue(), 1); } }
2,879
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/FailingMetricObserver.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import java.util.List; public class FailingMetricObserver implements MetricObserver { public FailingMetricObserver() { } public String getName() { return "die"; } public void update(List<Metric> metrics) { throw new IllegalArgumentException("die"); } }
2,880
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/publish/RegexMetricFilterTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.publish; import com.netflix.servo.Metric; import com.netflix.servo.tag.SortedTagList; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.List; import java.util.regex.Pattern; import static org.testng.Assert.assertEquals; public class RegexMetricFilterTest { private List<Metric> mkList() { return UnmodifiableList.of( new Metric("m1", SortedTagList.EMPTY, 0L, 0), new Metric("m2", SortedTagList.builder().withTag("c", "a.b.c.d.M1").build(), 0L, 0), new Metric("m3", SortedTagList.builder().withTag("c", "a.b.c.c.M3").build(), 0L, 0), new Metric("m4", SortedTagList.builder().withTag("c", "a.b.c.d.M4").build(), 0L, 0), new Metric("m5", SortedTagList.builder().withTag("c", "a.a.a.a.M5").build(), 0L, 0) ); } private MetricPoller newPoller() { MockMetricPoller poller = new MockMetricPoller(); poller.setMetrics(mkList()); return poller; } @Test public void testPrefixFilter() throws Exception { Pattern pattern = Pattern.compile("^a\\.b\\.c.*"); MetricFilter filter = new RegexMetricFilter("c", pattern, false, false); MetricPoller poller = newPoller(); List<Metric> metrics = poller.poll(filter); assertEquals(metrics.size(), 3); assertEquals(metrics.get(0), mkList().get(1)); } @Test public void testPrefixFilterMatchIfTagMissing() throws Exception { Pattern pattern = Pattern.compile("^a\\.b\\.c.*"); MetricFilter filter = new RegexMetricFilter("c", pattern, true, false); MetricPoller poller = newPoller(); List<Metric> metrics = poller.poll(filter); assertEquals(metrics.size(), 4); assertEquals(metrics.get(0), mkList().get(0)); } @Test public void testPrefixFilterInvert() throws Exception { Pattern pattern = Pattern.compile("^a\\.b\\.c.*"); MetricFilter filter = new RegexMetricFilter("c", pattern, true, true); MetricPoller poller = newPoller(); List<Metric> metrics = poller.poll(filter); assertEquals(metrics.size(), 1); assertEquals(metrics.get(0), mkList().get(4)); } @Test public void testPrefixFilterName() throws Exception { Pattern pattern = Pattern.compile("m[13]"); MetricFilter filter = new RegexMetricFilter(null, pattern, false, false); MetricPoller poller = newPoller(); List<Metric> metrics = poller.poll(filter); assertEquals(metrics.size(), 2); assertEquals(metrics.get(0), mkList().get(0)); assertEquals(metrics.get(1), mkList().get(2)); } }
2,881
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/tag/BasicTagListTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.tag; import com.netflix.servo.util.Preconditions; import com.netflix.servo.util.UnmodifiableList; import org.testng.annotations.Test; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; public class BasicTagListTest { static Map<String, String> mapOf(String... elts) { Preconditions.checkArgument(elts.length > 0, "elts must not be empty"); Preconditions.checkArgument(elts.length % 2 == 0, "elts must be even: key,value pairs"); Map<String, String> res = new HashMap<>(elts.length / 2); for (int i = 0; i < elts.length; i += 2) { final String key = elts[i]; final String value = elts[i + 1]; res.put(key, value); } return res; } @Test public void testCopyOfMap() throws Exception { Map<String, String> input = mapOf("foo", "bar", "dee", "dum"); TagList tags = BasicTagList.copyOf(input); assertEquals(tags.asMap(), input); } @Test public void testCopyOfIterableString() throws Exception { Map<String, String> map = mapOf("foo", "bar", "dee", "dum"); List<String> input = UnmodifiableList.of("foo=bar", "dee=dum"); TagList tags = BasicTagList.copyOf(input); assertEquals(tags.asMap(), map); } @Test public void testOfVarargTag() throws Exception { Map<String, String> map = mapOf("foo", "bar", "dee", "dum"); TagList tags = BasicTagList.of( new BasicTag("foo", "bar"), new BasicTag("dee", "dum")); assertEquals(tags.asMap(), map); } @Test public void testConcatVararg() throws Exception { Map<String, String> map = mapOf("foo", "bar", "dee", "dum"); TagList t1 = BasicTagList.of("foo", "bar"); TagList tags = BasicTagList.concat(t1, new BasicTag("dee", "dum")); assertEquals(tags.asMap(), map); } @Test public void testConcatTagList() throws Exception { Map<String, String> map = mapOf("foo", "bar", "dee", "dum"); TagList t1 = BasicTagList.of("foo", "bar"); TagList t2 = BasicTagList.of("dee", "dum"); TagList tags = BasicTagList.concat(t1, t2); assertEquals(tags.asMap(), map); } @Test public void testConcatOverride() throws Exception { Map<String, String> map = mapOf("foo", "bar2"); TagList t1 = BasicTagList.of("foo", "bar"); TagList t2 = BasicTagList.of("foo", "bar2"); TagList tags = BasicTagList.concat(t1, t2); assertEquals(tags.asMap(), map); } @Test public void testEmpty() throws Exception { TagList t1 = BasicTagList.EMPTY; assertTrue(t1.isEmpty()); assertEquals(t1.size(), 0); } @Test public void testAccessors() throws Exception { TagList t1 = BasicTagList.of("foo", "bar"); assertTrue(!t1.isEmpty()); assertEquals(t1.size(), 1); assertEquals(t1.getTag("foo"), new BasicTag("foo", "bar")); assertTrue(t1.getTag("dee") == null, "dee is not a tag"); assertTrue(t1.containsKey("foo")); assertTrue(!t1.containsKey("dee")); } @Test public void testIterator() throws Exception { TagList t1 = BasicTagList.of("foo", "bar"); for (Tag t : t1) { assertEquals(t, new BasicTag("foo", "bar")); } } @Test public void testCopyTagList() throws Exception { Map<String, String> map = mapOf("foo", "bar", "dee", "dum"); BasicTagList t1 = BasicTagList.of("foo", "bar"); BasicTagList t2 = BasicTagList.of("foo", "bar2"); BasicTagList t3 = BasicTagList.of("dee", "dum"); assertEquals(t1.copy(t2), t2); assertEquals(t1.copy(t3).asMap(), map); } @Test public void testCopy() throws Exception { Map<String, String> map = mapOf("foo", "bar", "dee", "dum"); BasicTagList t1 = BasicTagList.of("foo", "bar"); BasicTagList t2 = BasicTagList.of("foo", "bar2"); assertEquals(t1.copy("foo", "bar2"), t2); assertEquals(t1.copy("dee", "dum").asMap(), map); } @Test public void testEquals() throws Exception { BasicTagList t1 = BasicTagList.of("foo", "bar"); BasicTagList t2 = BasicTagList.of("foo", "bar2"); BasicTagList t3 = BasicTagList.of("foo", "bar"); assertNotNull(t1); assertFalse(t1.toString().equals(t2.toString())); assertTrue(t1.equals(t1)); assertFalse(t1.equals(t2)); assertTrue(t1.equals(t3)); } @Test public void testHashCode() throws Exception { BasicTagList t1 = BasicTagList.of("foo", "bar"); BasicTagList t2 = BasicTagList.of("foo", "bar2"); BasicTagList t3 = BasicTagList.of("foo", "bar"); assertTrue(t1.hashCode() == t1.hashCode()); assertTrue(t1.hashCode() != t2.hashCode()); assertTrue(t1.hashCode() == t3.hashCode()); } @Test public void testOf() throws Exception { BasicTagList expected = BasicTagList.copyOf(mapOf("foo", "bar", "id", "1")); BasicTagList of = BasicTagList.of("foo", "bar", "id", "1"); assertEquals(of, expected); } @Test(expectedExceptions = IllegalArgumentException.class) public void testOfOddNumber() { BasicTagList.of("foo"); } @Test public void testConcurrentTagList() throws Exception { final int count = 10; final CountDownLatch latch = new CountDownLatch(count); final Set<BasicTagList> tagLists = Collections .newSetFromMap(new ConcurrentHashMap<>()); final CyclicBarrier barrier = new CyclicBarrier(count); for (int i = 0; i < count; i++) { new Thread(() -> { try { barrier.await(); tagLists.add(BasicTagList.of("id", "1", "color", "green")); } catch (Exception e) { e.printStackTrace(System.out); } finally { latch.countDown(); } }).start(); } latch.await(); assertEquals(tagLists.size(), 1); } }
2,882
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/tag/SmallTagMapTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo.tag; import com.netflix.servo.util.UnmodifiableList; import com.netflix.servo.util.UnmodifiableSet; import org.testng.annotations.Test; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; public class SmallTagMapTest { @Test public void testEmpty() { SmallTagMap smallTagMap = SmallTagMap.builder().result(); assertTrue(smallTagMap.isEmpty()); SmallTagMap notEmpty = SmallTagMap.builder().add(Tags.newTag("k", "v")).result(); assertFalse(notEmpty.isEmpty()); assertEquals(notEmpty.size(), 1); } @Test public void testGet() { Tag tag = Tags.newTag("k1", "v1"); SmallTagMap map = SmallTagMap.builder().add(tag).result(); assertEquals(map.get("k1"), tag); assertNull(map.get("k2")); } @Test public void testBuilderUpdatesExisting() { Tag t1 = Tags.newTag("k1", "v1"); Tag t2 = Tags.newTag("k1", "v2"); SmallTagMap map = SmallTagMap.builder().add(t1).add(t2).result(); assertEquals(map.get("k1"), t2); } @Test public void testBuilderAddAll() { Tag t1 = Tags.newTag("k1", "v1"); Tag t2 = Tags.newTag("k1", "v2"); Tag t3 = Tags.newTag("k2", "v2"); List<Tag> tags = UnmodifiableList.of(t1, t2, t3); SmallTagMap map = SmallTagMap.builder().addAll(tags).result(); assertEquals(map.get("k1"), t2); assertEquals(map.size(), 2); } @Test public void testIteratorEmpty() { SmallTagMap empty = SmallTagMap.builder().result(); assertFalse(empty.iterator().hasNext()); } @Test(expectedExceptions = NoSuchElementException.class) public void testIteratorNextThrows() { SmallTagMap empty = SmallTagMap.builder().result(); empty.iterator().next(); } @Test public void testIterator() { final Tag t1 = Tags.newTag("k1", "v"); final Tag t2 = Tags.newTag("k2", "v2"); SmallTagMap map = SmallTagMap.builder().add(t1).add(t2).result(); Set<Tag> tags = UnmodifiableSet.copyOf(map.iterator()); assertEquals(tags, UnmodifiableSet.of(t1, t2)); } @Test public void testResize() { SmallTagMap.Builder builder = SmallTagMap.builder(); for (int i = 0; i < SmallTagMap.MAX_TAGS; ++i) { Tag t = Tags.newTag("k" + i, "0"); builder.add(t); assertEquals(builder.size(), i + 1); } SmallTagMap map = builder.result(); assertEquals(map.size(), SmallTagMap.MAX_TAGS); } @Test public void testTooManyTags() { SmallTagMap.Builder builder = SmallTagMap.builder(); for (int i = 0; i < SmallTagMap.MAX_TAGS + 2; ++i) { builder.add(Tags.newTag("k" + i, "0")); } assertEquals(builder.size(), SmallTagMap.MAX_TAGS); assertEquals(builder.result().size(), SmallTagMap.MAX_TAGS); } @Test public void testContains() { SmallTagMap map = SmallTagMap.builder().add(Tags.newTag("k1", "v")).add( Tags.newTag("k2", "v2")).result(); assertTrue(map.containsKey("k1")); assertTrue(map.containsKey("k2")); assertFalse(map.containsKey("k3")); } @Test public void testHashcode() { SmallTagMap map1 = SmallTagMap.builder().add(Tags.newTag("k1", "v1")).result(); SmallTagMap map2 = SmallTagMap.builder().add(Tags.newTag("k1", "v2")).result(); SmallTagMap map3 = SmallTagMap.builder().add(Tags.newTag("k1", "v1")).result(); assertEquals(map1.hashCode(), map1.hashCode()); assertEquals(map1.hashCode(), map3.hashCode()); assertNotEquals(map1.hashCode(), map2.hashCode()); } @SuppressWarnings({"EqualsWithItself", "ObjectEqualsNull"}) @Test public void testEquals() { SmallTagMap map1 = SmallTagMap.builder().add(Tags.newTag("k1", "v1")).result(); SmallTagMap map2 = SmallTagMap.builder().add(Tags.newTag("k1", "v2")).result(); SmallTagMap map3 = SmallTagMap.builder().add(Tags.newTag("k1", "v1")).result(); SmallTagMap map4 = SmallTagMap.builder().add(Tags.newTag("k1", "v1")) .add(Tags.newTag("k2", "v2")).result(); assertTrue(map1.equals(map1)); assertTrue(map1.equals(map3)); assertFalse(map1.equals(map2)); assertFalse(map1.equals(null)); assertFalse(map1.equals(map4)); } @Test public void testToString() { SmallTagMap empty = SmallTagMap.builder().result(); assertEquals(empty.toString(), "SmallTagMap{}"); } @Test(expectedExceptions = UnsupportedOperationException.class) public void testIteratorImmutable() { SmallTagMap map1 = SmallTagMap.builder().add(Tags.newTag("k1", "v1")).result(); Iterator<Tag> it = map1.iterator(); assertTrue(it.hasNext()); it.remove(); } @Test public void testEqualsRandomOrder() { SmallTagMap.Builder builder1 = SmallTagMap.builder(); SmallTagMap.Builder builder2 = SmallTagMap.builder(); final int n = 16; for (int i = 0; i < n; i++) { builder1.add(Tags.newTag("k" + i, "0")); builder2.add(Tags.newTag("k" + (n - i - 1), "0")); } assertEquals(builder1.result(), builder2.result()); } @Test public void testHashcodeRandomOrder() { SmallTagMap.Builder builder1 = SmallTagMap.builder(); SmallTagMap.Builder builder2 = SmallTagMap.builder(); final int n = 16; for (int i = 0; i < n; i++) { builder1.add(Tags.newTag("k" + i, "0")); builder2.add(Tags.newTag("k" + (n - i - 1), "0")); } assertEquals(builder1.result().hashCode(), builder2.result().hashCode()); } }
2,883
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/tag/BasicTagTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.tag; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class BasicTagTest { private static final String TEST_KEY = "foo"; private static final String TEST_VALUE = "bar"; private final BasicTag testTag = new BasicTag(TEST_KEY, TEST_VALUE); @Test public void testEquals() throws Exception { BasicTag localTag = new BasicTag(TEST_KEY, TEST_VALUE); BasicTag notEqualTag = new BasicTag(TEST_KEY, "goo"); assertTrue(testTag != localTag); assertTrue(testTag.equals(localTag)); assertTrue(testTag.getKey().equals(TEST_KEY)); assertTrue(testTag.getValue().equals(TEST_VALUE)); assertTrue(!testTag.equals(notEqualTag)); } @Test public void testGetKey() throws Exception { assertEquals(testTag.getKey(), TEST_KEY); } @Test public void testGetValue() throws Exception { assertEquals(testTag.getValue(), TEST_VALUE); } @Test public void testParseTagValid() throws Exception { String goodString = "foo=bar"; Tag t = Tags.parseTag(goodString); assertTrue(t.equals(testTag)); } @Test(expectedExceptions = IllegalArgumentException.class) public void testParseTagNoEqSign() throws Exception { String badString = "foobar"; Tags.parseTag(badString); } @Test(expectedExceptions = IllegalArgumentException.class) public void testParseTagEmptyValue() throws Exception { String badString = "foo="; Tags.parseTag(badString); } @Test(expectedExceptions = IllegalArgumentException.class) public void testParseTagEmptyKey() throws Exception { String badString = "=bar"; Tags.parseTag(badString); } }
2,884
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/tag/SortedTagListTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.tag; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class SortedTagListTest { static final Tag A = new BasicTag("a", "a"); static final Tag B = new BasicTag("b", "b"); static final Tag C = new BasicTag("c", "c"); static final Tag[] TAG_ARRAY = new Tag[3]; private TagList testListFromStrings; private TagList testListFromCollection; private TagList testListFromTags; private Collection<Tag> collection; @BeforeClass public void setup() throws Exception { TAG_ARRAY[0] = A; TAG_ARRAY[1] = B; TAG_ARRAY[2] = C; testListFromStrings = new SortedTagList.Builder() .withTag("a", "a") .withTag("b", "b") .withTag("c", "c") .build(); collection = new ArrayList<>(); collection.add(A); collection.add(C); collection.add(B); testListFromCollection = new SortedTagList.Builder().withTags(collection).build(); testListFromTags = new SortedTagList.Builder().withTag(C).withTag(A).withTag(B).build(); } @Test public void testGetTag() throws Exception { assertTrue(testListFromCollection.getTag("a").equals(A)); assertTrue(testListFromStrings.getTag("b").equals(B)); assertTrue(testListFromTags.getTag("c").equals(C)); } @Test public void testContainsKey() throws Exception { assertTrue(testListFromCollection.containsKey("b")); assertTrue(testListFromStrings.containsKey("c")); assertTrue(testListFromTags.containsKey("a")); } @Test public void testIsEmpty() throws Exception { assertTrue(SortedTagList.EMPTY.isEmpty()); assertTrue(!testListFromCollection.isEmpty()); assertTrue(!testListFromStrings.isEmpty()); assertTrue(!testListFromTags.isEmpty()); } @Test public void testSize() throws Exception { assertTrue(SortedTagList.EMPTY.isEmpty()); assertTrue(!testListFromCollection.isEmpty()); assertTrue(!testListFromStrings.isEmpty()); assertTrue(!testListFromTags.isEmpty()); } @Test public void testOrder() throws Exception { int i = 0; for (Tag testListFromString : testListFromStrings) { assertEquals(testListFromString, TAG_ARRAY[i]); i++; } i = 0; for (Tag testListFromTag : testListFromTags) { assertEquals(testListFromTag, TAG_ARRAY[i]); i++; } i = 0; for (Tag aTestListFromCollection : testListFromCollection) { assertEquals(aTestListFromCollection, TAG_ARRAY[i]); i++; } } @Test public void testAsMap() throws Exception { Map<String, String> stringMap = testListFromCollection.asMap(); int i = 0; for (String s : stringMap.keySet()) { assertEquals(s, TAG_ARRAY[i].getKey()); i++; } i = 0; for (String s : stringMap.values()) { assertEquals(s, TAG_ARRAY[i].getValue()); i++; } } }
2,885
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/tag/TagComparatorTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.tag; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.testng.Assert.assertTrue; public class TagComparatorTest { private Tag a; private Tag b; private Tag aa; private Tag ab; private TagComparator comparator; @BeforeTest public void setupTest() throws Exception { comparator = new TagComparator(); a = new BasicTag("a", "a"); b = new BasicTag("b", "b"); aa = new BasicTag("a", "a"); ab = new BasicTag("a", "b"); } @Test public void testCompareFirstLevel() throws Exception { assertTrue(comparator.compare(a, b) < 0); assertTrue(comparator.compare(b, a) > 0); } @Test public void testCompareSecondLevel() throws Exception { assertTrue(comparator.compare(aa, ab) < 0); assertTrue(comparator.compare(ab, aa) > 0); } @Test public void testCompareEqual() throws Exception { assertTrue(comparator.compare(a, aa) == 0); } }
2,886
0
Create_ds/servo/servo-core/src/test/java/com/netflix/servo
Create_ds/servo/servo-core/src/test/java/com/netflix/servo/stats/StatsBufferTest.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.stats; import org.testng.annotations.Test; import java.lang.reflect.Field; import static org.testng.Assert.assertEquals; public class StatsBufferTest { static final double[] PERCENTILES = {50.0, 95.0, 99.0, 99.5}; private static final int SIZE = 1000; StatsBuffer getNoWrap() { StatsBuffer buffer = new StatsBuffer(SIZE, PERCENTILES); int max = SIZE / 2; for (int i = 0; i <= max; ++i) { buffer.record(i); } buffer.computeStats(); return buffer; } @Test public void testMaxNoWrap() { StatsBuffer buffer = getNoWrap(); assertEquals(buffer.getMax(), SIZE / 2); } @Test public void testMinNoWrap() { StatsBuffer buffer = getNoWrap(); assertEquals(buffer.getMin(), 0); } @Test public void testMeanNoWrap() { StatsBuffer buffer = getNoWrap(); assertEquals(buffer.getMean(), SIZE / 4.0); } @Test public void testCountNoWrap() { StatsBuffer buffer = getNoWrap(); assertEquals(buffer.getCount(), SIZE / 2 + 1); } @Test public void testTotalNoWrap() { StatsBuffer buffer = getNoWrap(); assertEquals(buffer.getTotalTime(), SIZE / 2 * (SIZE / 2 + 1) / 2); } @Test public void testVarianceNoWrap() { StatsBuffer buffer = getNoWrap(); assertEquals(buffer.getVariance(), 20958.5, 1e-4); } @Test public void testStdDevNoWrap() { StatsBuffer buffer = getNoWrap(); assertEquals(buffer.getStdDev(), 144.77051, 1e-4); } @Test public void testPercentiles50NoWrap() { StatsBuffer buffer = getNoWrap(); double[] percentiles = buffer.getPercentileValues(); // testNG does not give good errors if we do assertEquals on the two arrays assertEquals(percentiles[0], 250.5); } @Test public void testPercentiles95NoWrap() { StatsBuffer buffer = getNoWrap(); double[] percentiles = buffer.getPercentileValues(); assertEquals(percentiles[1], 475.95); } @Test public void testPercentiles99NoWrap() { StatsBuffer buffer = getNoWrap(); double[] percentiles = buffer.getPercentileValues(); assertEquals(percentiles[2], 495.99); } @Test public void testPercentiles995NoWrap() { StatsBuffer buffer = getNoWrap(); double[] percentiles = buffer.getPercentileValues(); assertEquals(percentiles[3], 498.495); } void assertEmpty(StatsBuffer buffer) { assertEquals(buffer.getCount(), 0); assertEquals(buffer.getTotalTime(), 0); assertEquals(buffer.getMax(), 0); assertEquals(buffer.getMin(), 0); // the following values could be NaN assertEquals(buffer.getMean(), 0.0); assertEquals(buffer.getVariance(), 0.0); assertEquals(buffer.getStdDev(), 0.0); assertEquals(buffer.getPercentileValues()[0], 0.0); } @Test public void testEmptyBuffer() { StatsBuffer buffer = new StatsBuffer(SIZE, PERCENTILES); assertEmpty(buffer); buffer.computeStats(); assertEmpty(buffer); } StatsBuffer getWithWrap() { StatsBuffer buffer = new StatsBuffer(SIZE, PERCENTILES); for (int i = SIZE * 2; i > 0; --i) { buffer.record(i); } buffer.computeStats(); return buffer; } @Test public void testMaxWrap() { StatsBuffer buffer = getWithWrap(); assertEquals(buffer.getMax(), SIZE); } @Test public void testMinWrap() { StatsBuffer buffer = getWithWrap(); assertEquals(buffer.getMin(), 1); } @Test public void testCountWrap() { StatsBuffer buffer = getWithWrap(); assertEquals(buffer.getCount(), SIZE); } static final long EXPECTED_TOTAL_WRAP = SIZE * (SIZE + 1) / 2; @Test public void testTotalWrap() { StatsBuffer buffer = getWithWrap(); assertEquals(buffer.getTotalTime(), EXPECTED_TOTAL_WRAP); } @Test public void testMeanWrap() { StatsBuffer buffer = getWithWrap(); assertEquals(buffer.getMean(), (double) EXPECTED_TOTAL_WRAP / SIZE); } static final double EXPECTED_VARIANCE_WRAP = 83416.66667; @Test public void testVarianceWrap() { StatsBuffer buffer = getWithWrap(); assertEquals(buffer.getVariance(), EXPECTED_VARIANCE_WRAP, 1e-4); } @Test public void testStdDevWrap() { StatsBuffer buffer = getWithWrap(); assertEquals(buffer.getStdDev(), Math.sqrt(EXPECTED_VARIANCE_WRAP), 1e-4); } @Test public void testPercentiles50Wrap() { StatsBuffer buffer = getWithWrap(); double[] percentiles = buffer.getPercentileValues(); // testNG does not give good errors if we do assertEquals on the two arrays assertEquals(percentiles[0], 501.0); } @Test public void testPercentiles95Wrap() { StatsBuffer buffer = getWithWrap(); double[] percentiles = buffer.getPercentileValues(); assertEquals(percentiles[1], 951.0); } @Test public void testPercentiles99Wrap() { StatsBuffer buffer = getWithWrap(); double[] percentiles = buffer.getPercentileValues(); assertEquals(percentiles[2], 991.0); } @Test public void testPercentiles995Wrap() { StatsBuffer buffer = getWithWrap(); double[] percentiles = buffer.getPercentileValues(); assertEquals(percentiles[3], 996.0); } // Used to access private count field via reflection so we can quickly simulate // a count that will cause an integer overflow. private void setCount(StatsBuffer buffer, int v) throws Exception { Class<?> cls = buffer.getClass(); Field field = cls.getDeclaredField("pos"); field.setAccessible(true); field.set(buffer, v); } // Before fix this would throw an ArrayIndexOutOfBoundException @Test public void testCountOverflow() throws Exception { StatsBuffer buffer = new StatsBuffer(SIZE, PERCENTILES); setCount(buffer, Integer.MAX_VALUE); buffer.record(1); buffer.record(2); } // java.lang.IllegalArgumentException: fromIndex(0) > toIndex(-2147483647) @Test public void testComputeStatsWithOverflow() throws Exception { StatsBuffer buffer = new StatsBuffer(SIZE, PERCENTILES); setCount(buffer, Integer.MAX_VALUE); buffer.record(1); buffer.record(2); buffer.computeStats(); } }
2,887
0
Create_ds/servo/servo-core/src/main/java/com/netflix
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/NoopMonitorRegistry.java
/* * Copyright 2020 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo; import com.netflix.servo.monitor.Monitor; import java.util.Collection; import java.util.Collections; /** * Monitor registry implementation that does as little as possible. */ public class NoopMonitorRegistry implements MonitorRegistry { /** Create a new instance. */ public NoopMonitorRegistry() { } @Override public Collection<Monitor<?>> getRegisteredMonitors() { return Collections.emptyList(); } @Override public void register(Monitor<?> monitor) { } @Override public void unregister(Monitor<?> monitor) { } @Override public boolean isRegistered(Monitor<?> monitor) { return false; } }
2,888
0
Create_ds/servo/servo-core/src/main/java/com/netflix
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/Metric.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.TagList; import com.netflix.servo.util.Preconditions; /** * Represents a metric value at a given point in time. */ public final class Metric { private final MonitorConfig config; private final long timestamp; private final Object value; /** * Creates a new instance. * * @param name name of the metric * @param tags tags associated with the metric * @param timestamp point in time when the metric value was sampled * @param value value of the metric */ public Metric(String name, TagList tags, long timestamp, Object value) { this(new MonitorConfig.Builder(name).withTags(tags).build(), timestamp, value); } /** * Creates a new instance. * * @param config config settings associated with the metric * @param timestamp point in time when the metric value was sampled * @param value value of the metric */ public Metric(MonitorConfig config, long timestamp, Object value) { this.config = Preconditions.checkNotNull(config, "config"); this.timestamp = timestamp; this.value = Preconditions.checkNotNull(value, "value"); } /** * Returns the config settings associated with the metric. */ public MonitorConfig getConfig() { return config; } /** * Returns the point in time when the metric was sampled. */ public long getTimestamp() { return timestamp; } /** * Returns the value of the metric. */ public Object getValue() { return value; } /** * Returns the value of the metric as a number. */ public Number getNumberValue() { return (Number) value; } /** * Returns true if the value for this metric is numeric. */ public boolean hasNumberValue() { return (value instanceof Number); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Metric)) { return false; } Metric m = (Metric) obj; return config.equals(m.getConfig()) && timestamp == m.getTimestamp() && value.equals(m.getValue()); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); result = 31 * result + value.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "Metric{config=" + config + ", timestamp=" + timestamp + ", value=" + value + '}'; } }
2,889
0
Create_ds/servo/servo-core/src/main/java/com/netflix
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/BasicMonitorRegistry.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.util.Preconditions; import com.netflix.servo.util.UnmodifiableList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * Simple monitor registry backed by a {@link java.util.Set}. */ public final class BasicMonitorRegistry implements MonitorRegistry { private final Set<Monitor<?>> monitors; /** * Creates a new instance. */ public BasicMonitorRegistry() { monitors = Collections.synchronizedSet(new HashSet<>()); } /** * The set of registered Monitor objects. */ @Override public Collection<Monitor<?>> getRegisteredMonitors() { return UnmodifiableList.copyOf(monitors); } /** * Register a new monitor in the registry. */ @Override public void register(Monitor<?> monitor) { Preconditions.checkNotNull(monitor, "monitor"); try { monitors.add(monitor); } catch (Exception e) { throw new IllegalArgumentException("invalid object", e); } } /** * Unregister a Monitor from the registry. */ @Override public void unregister(Monitor<?> monitor) { Preconditions.checkNotNull(monitor, "monitor"); try { monitors.remove(monitor); } catch (Exception e) { throw new IllegalArgumentException("invalid object", e); } } @Override public boolean isRegistered(Monitor<?> monitor) { return monitors.contains(monitor); } }
2,890
0
Create_ds/servo/servo-core/src/main/java/com/netflix
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/SpectatorContext.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo; import com.netflix.servo.monitor.BasicCompositeMonitor; import com.netflix.servo.monitor.CompositeMonitor; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Pollers; import com.netflix.servo.monitor.SpectatorMonitor; import com.netflix.servo.tag.BasicTagList; import com.netflix.spectator.api.AbstractTimer; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DistributionSummary; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Measurement; import com.netflix.spectator.api.Meter; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Spectator; import com.netflix.spectator.api.Timer; import com.netflix.spectator.api.patterns.PolledMeter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; /** * Helper that can be used to delegate to spectator. Other than calling * {@link #setRegistry(Registry)} to set the registry to use, it is only intended for use * within servo. */ public final class SpectatorContext { private SpectatorContext() { } private static final ScheduledExecutorService GAUGE_POOL = Executors.newScheduledThreadPool( 2, task -> { Thread t = new Thread(task, "servo-gauge-poller"); t.setDaemon(true); return t; } ); private static final Logger LOGGER = LoggerFactory.getLogger(SpectatorContext.class); private static volatile Registry registry = new NoopRegistry(); // Used to keep track of where the registry was being set. This can be useful to help // debug issues if missing metrics due to it being set from multiple places. private static volatile Exception initStacktrace = null; /** * Set the registry to use. By default it will use the NoopRegistry. */ public static void setRegistry(Registry registry) { SpectatorContext.registry = registry; // Ignore if overwriting with the global registry. In some cases it is necessary to set // the context for Servo early before a proper registry can be created via injection. In // that case the global registry is the best option. If it is later overwritten with the // registry created by the injector, then that should not trigger a warning to the user. if (registry instanceof NoopRegistry || isGlobal(registry)) { initStacktrace = null; } else { Exception cause = initStacktrace; Exception e = new IllegalStateException( "called SpectatorContext.setRegistry(" + registry.getClass().getName() + ")", cause); e.fillInStackTrace(); initStacktrace = e; if (cause != null) { LOGGER.warn("Registry used with Servo's SpectatorContext has been overwritten. This could result in missing metrics.", e); } } } private static boolean isGlobal(Registry registry) { // Use identity check to see it is the global instance return registry == Spectator.globalRegistry(); } /** * Get the registry that was configured. */ public static Registry getRegistry() { return registry; } /** Create a gauge based on the config. */ public static LazyGauge gauge(MonitorConfig config) { return new LazyGauge(Registry::gauge, registry, createId(config)); } /** Create a max gauge based on the config. */ public static LazyGauge maxGauge(MonitorConfig config) { return new LazyGauge(Registry::maxGauge, registry, createId(config)); } /** Create a counter based on the config. */ public static LazyCounter counter(MonitorConfig config) { return new LazyCounter(registry, createId(config)); } /** Create a timer based on the config. */ public static LazyTimer timer(MonitorConfig config) { return new LazyTimer(registry, createId(config)); } /** Create a distribution summary based on the config. */ public static LazyDistributionSummary distributionSummary(MonitorConfig config) { return new LazyDistributionSummary(registry, createId(config)); } /** Convert servo config to spectator id. */ public static Id createId(MonitorConfig config) { // Need to ensure that Servo type tag is removed to avoid incorrectly reprocessing the // data in later transforms Map<String, String> tags = new HashMap<>(config.getTags().asMap()); tags.remove("type"); return registry .createId(config.getName()) .withTags(tags); } /** Dedicated thread pool for polling user defined functions registered as gauges. */ public static ScheduledExecutorService gaugePool() { return GAUGE_POOL; } /** Create builder for a polled gauge based on the config. */ public static PolledMeter.Builder polledGauge(MonitorConfig config) { long delayMillis = Math.max(Pollers.getPollingIntervals().get(0) - 1000, 5000); Id id = createId(config); PolledMeter.remove(registry, id); return PolledMeter.using(registry) .withId(id) .withDelay(Duration.ofMillis(delayMillis)) .scheduleOn(gaugePool()); } /** Register a custom monitor. */ public static void register(Monitor<?> monitor) { if (monitor instanceof SpectatorMonitor) { ((SpectatorMonitor) monitor).initializeSpectator(BasicTagList.EMPTY); } else if (!isEmptyComposite(monitor)) { ServoMeter m = new ServoMeter(monitor); PolledMeter.remove(registry, m.id()); PolledMeter.monitorMeter(registry, m); monitorMonitonicValues(monitor); } } /** * A basic composite has an immutable list, if it is empty then will never provide any * useful monitors. This can happen if a monitor type is used with Monitors.registerObject. */ private static boolean isEmptyComposite(Monitor<?> monitor) { return (monitor instanceof BasicCompositeMonitor) && ((BasicCompositeMonitor) monitor).getMonitors().isEmpty(); } private static boolean isCounter(MonitorConfig config) { return "COUNTER".equals(config.getTags().getValue("type")); } private static void monitorMonitonicValues(Monitor<?> monitor) { if (!(monitor instanceof SpectatorMonitor)) { if (monitor instanceof CompositeMonitor<?>) { CompositeMonitor<?> cm = (CompositeMonitor<?>) monitor; for (Monitor<?> m : cm.getMonitors()) { monitorMonitonicValues(m); } } else if (isCounter(monitor.getConfig())) { polledGauge(monitor.getConfig()) .monitorMonotonicCounter(monitor, m -> ((Number) m.getValue()).longValue()); } } } /** Unregister a custom monitor. */ public static void unregister(Monitor<?> monitor) { PolledMeter.remove(registry, createId(monitor.getConfig())); } private static class ServoMeter implements Meter { private final Id id; private final Monitor<?> monitor; ServoMeter(Monitor<?> monitor) { this.id = createId(monitor.getConfig()); this.monitor = monitor; } @Override public Id id() { return id; } private void addMeasurements(Monitor<?> m, List<Measurement> measurements) { // Skip any that will report directly if (!(m instanceof SpectatorMonitor)) { if (m instanceof CompositeMonitor<?>) { CompositeMonitor<?> cm = (CompositeMonitor<?>) m; for (Monitor<?> v : cm.getMonitors()) { addMeasurements(v, measurements); } } else if (!isCounter(m.getConfig())) { try { Object obj = m.getValue(); if (obj instanceof Number) { double value = ((Number) obj).doubleValue(); // timestamp will get ignored as the value will get forwarded to a gauge Measurement v = new Measurement(createId(m.getConfig()), 0L, value); measurements.add(v); } } catch (Throwable t) { LOGGER.warn("Exception while querying user defined gauge ({}), " + "the value will be ignored. The owner of the user defined " + "function should fix it to not propagate an exception.", m.getConfig(), t); } } } } @Override public Iterable<Measurement> measure() { List<Measurement> measurements = new ArrayList<>(); addMeasurements(monitor, measurements); return measurements; } @Override public boolean hasExpired() { return false; } } /** Create a counter when it is first updated. */ public static class LazyCounter implements Counter { private final Registry registry; private volatile Id id; private volatile Counter counter; LazyCounter(Registry registry, Id id) { this.registry = registry; this.id = id; } /** Set a new id to use. */ public void setId(Id id) { this.id = id; this.counter = null; } private Counter get() { Counter c = counter; if (c == null) { c = registry.counter(id); counter = c; } return c; } @Override public void add(double amount) { get().add(amount); } @Override public double actualCount() { return get().actualCount(); } @Override public Id id() { return get().id(); } @Override public Iterable<Measurement> measure() { return get().measure(); } @Override public boolean hasExpired() { return get().hasExpired(); } } /** Create a timer when it is first updated. */ public static class LazyTimer extends AbstractTimer implements Timer { private final Registry registry; private volatile Id id; private volatile Timer timer; LazyTimer(Registry registry, Id id) { super(registry.clock()); this.registry = registry; this.id = id; } /** Set a new id to use. */ public void setId(Id id) { this.id = id; this.timer = null; } private Timer get() { Timer t = timer; if (t == null) { t = registry.timer(id); timer = t; } return t; } @Override public Id id() { return get().id(); } @Override public Iterable<Measurement> measure() { return get().measure(); } @Override public boolean hasExpired() { return get().hasExpired(); } @Override public void record(long amount, TimeUnit unit) { get().record(amount, unit); } @Override public long count() { return get().count(); } @Override public long totalTime() { return get().totalTime(); } } /** Create a distribution summary when it is first updated. */ public static class LazyDistributionSummary implements DistributionSummary { private final Registry registry; private volatile Id id; private volatile DistributionSummary summary; LazyDistributionSummary(Registry registry, Id id) { this.registry = registry; this.id = id; } /** Set a new id to use. */ public void setId(Id id) { this.id = id; this.summary = null; } private DistributionSummary get() { DistributionSummary s = summary; if (s == null) { s = registry.distributionSummary(id); summary = s; } return s; } @Override public Id id() { return get().id(); } @Override public Iterable<Measurement> measure() { return get().measure(); } @Override public boolean hasExpired() { return get().hasExpired(); } @Override public void record(long amount) { get().record(amount); } @Override public long count() { return get().count(); } @Override public long totalAmount() { return get().totalAmount(); } } /** Create a gauge when it is first updated. */ public static class LazyGauge implements Gauge { private final Registry registry; private final BiFunction<Registry, Id, Gauge> factory; private volatile Id id; private volatile Gauge gauge; LazyGauge(BiFunction<Registry, Id, Gauge> factory, Registry registry, Id id) { this.registry = registry; this.factory = factory; this.id = id; } /** Set a new id to use. */ public void setId(Id id) { this.id = id; this.gauge = null; } private Gauge get() { Gauge g = gauge; if (g == null) { g = factory.apply(registry, id); gauge = g; } return g; } @Override public Id id() { return get().id(); } @Override public Iterable<Measurement> measure() { return get().measure(); } @Override public boolean hasExpired() { return get().hasExpired(); } @Override public void set(double v) { get().set(v); } @Override public double value() { return get().value(); } } }
2,891
0
Create_ds/servo/servo-core/src/main/java/com/netflix
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/MonitorRegistry.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo; import com.netflix.servo.monitor.Monitor; import java.util.Collection; /** * Registry to keep track of objects with * {@link com.netflix.servo.annotations.Monitor} annotations. */ public interface MonitorRegistry { /** * The set of registered Monitor objects. */ Collection<Monitor<?>> getRegisteredMonitors(); /** * Register a new monitor in the registry. */ void register(Monitor<?> monitor); /** * Unregister a Monitor from the registry. */ void unregister(Monitor<?> monitor); /** * Check whether a monitor has been registerd. */ boolean isRegistered(Monitor<?> monitor); }
2,892
0
Create_ds/servo/servo-core/src/main/java/com/netflix
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/DefaultMonitorRegistry.java
/* * Copyright 2011-2018 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo; import com.netflix.servo.jmx.JmxMonitorRegistry; import com.netflix.servo.jmx.ObjectNameMapper; import com.netflix.servo.monitor.Monitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Properties; /** * Default registry that delegates all actions to a class specified by the * {@code com.netflix.servo.DefaultMonitorRegistry.registryClass} property. The * specified registry class must have a constructor with no arguments. If the * property is not specified or the class cannot be loaded an instance of * {@link com.netflix.servo.NoopMonitorRegistry} will be used. * <p/> * If using {@link com.netflix.servo.jmx.JmxMonitorRegistry}, the property * {@code com.netflix.servo.DefaultMonitorRegistry.jmxMapperClass} can optionally be * specified to control how monitors are mapped to JMX {@link javax.management.ObjectName}. * This property specifies the {@link com.netflix.servo.jmx.ObjectNameMapper} * implementation class to use. The implementation must have a constructor with * no arguments. */ public final class DefaultMonitorRegistry implements MonitorRegistry { private static final Logger LOG = LoggerFactory.getLogger(DefaultMonitorRegistry.class); private static final String CLASS_NAME = DefaultMonitorRegistry.class.getCanonicalName(); private static final String REGISTRY_CLASS_PROP = CLASS_NAME + ".registryClass"; private static final String REGISTRY_NAME_PROP = CLASS_NAME + ".registryName"; private static final String REGISTRY_JMX_NAME_PROP = CLASS_NAME + ".jmxMapperClass"; private static final MonitorRegistry INSTANCE = new DefaultMonitorRegistry(); private static final String DEFAULT_REGISTRY_NAME = "com.netflix.servo"; private final MonitorRegistry registry; /** * Returns the instance of this registry. */ public static MonitorRegistry getInstance() { return INSTANCE; } /** * Creates a new instance based on system properties. */ DefaultMonitorRegistry() { this(loadProps()); } /** * Creates a new instance based on the provide properties object. Only * intended for use in unit tests. */ DefaultMonitorRegistry(Properties props) { final String className = props.getProperty(REGISTRY_CLASS_PROP); if (className != null) { MonitorRegistry r; if (className.equals(JmxMonitorRegistry.class.getName())) { final String registryName = props.getProperty(REGISTRY_NAME_PROP, DEFAULT_REGISTRY_NAME); r = new JmxMonitorRegistry(registryName, getObjectNameMapper(props)); } else { try { Class<?> c = Class.forName(className); r = (MonitorRegistry) c.newInstance(); } catch (Throwable t) { LOG.error("failed to create instance of class {}, using default class {}", className, NoopMonitorRegistry.class.getName(), t); r = new NoopMonitorRegistry(); } } registry = r; } else { registry = new NoopMonitorRegistry(); } } /** * Gets the {@link ObjectNameMapper} to use by looking at the * {@code com.netflix.servo.DefaultMonitorRegistry.jmxMapperClass} * property. If not specified, then {@link ObjectNameMapper#DEFAULT} * is used. * * @param props the properties * @return the mapper to use */ private static ObjectNameMapper getObjectNameMapper(Properties props) { ObjectNameMapper mapper = ObjectNameMapper.DEFAULT; final String jmxNameMapperClass = props.getProperty(REGISTRY_JMX_NAME_PROP); if (jmxNameMapperClass != null) { try { Class<?> mapperClazz = Class.forName(jmxNameMapperClass); mapper = (ObjectNameMapper) mapperClazz.newInstance(); } catch (Throwable t) { LOG.error("failed to create the JMX ObjectNameMapper instance of class {}, using the default naming scheme", jmxNameMapperClass, t); } } return mapper; } private static Properties loadProps() { String registryClassProp = System.getProperty(REGISTRY_CLASS_PROP); String registryNameProp = System.getProperty(REGISTRY_NAME_PROP); String registryJmxNameProp = System.getProperty(REGISTRY_JMX_NAME_PROP); Properties props = new Properties(); if (registryClassProp != null) { props.setProperty(REGISTRY_CLASS_PROP, registryClassProp); } if (registryNameProp != null) { props.setProperty(REGISTRY_NAME_PROP, registryNameProp); } if (registryJmxNameProp != null) { props.setProperty(REGISTRY_JMX_NAME_PROP, registryJmxNameProp); } return props; } /** * The set of registered Monitor objects. */ @Override public Collection<Monitor<?>> getRegisteredMonitors() { return registry.getRegisteredMonitors(); } /** * Register a new monitor in the registry. */ @Override public void register(Monitor<?> monitor) { SpectatorContext.register(monitor); registry.register(monitor); } /** * Unregister a Monitor from the registry. */ @Override public void unregister(Monitor<?> monitor) { SpectatorContext.unregister(monitor); registry.unregister(monitor); } /** * Returns the inner registry that was created to service the requests. */ MonitorRegistry getInnerRegistry() { return registry; } @Override public boolean isRegistered(Monitor<?> monitor) { return registry.isRegistered(monitor); } }
2,893
0
Create_ds/servo/servo-core/src/main/java/com/netflix
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/package-info.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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. * <p/> * Primary interfaces for metrics. * <p/> * Primary interfaces for metrics. * <p/> * Primary interfaces for metrics. */ /** * Primary interfaces for metrics. */ package com.netflix.servo;
2,894
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/BucketTimer.java
/* * Copyright 2011-2018 Netflix, Inc. * * Licensed 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.netflix.servo.monitor; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import com.netflix.servo.tag.Tags; import com.netflix.servo.util.Clock; import com.netflix.servo.util.ClockWithOffset; import com.netflix.servo.util.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; /** * A timer implementation using a bucketing approach * that provides a way to get the distribution of samples if the primary * range of values is known. * <p/> * For example the following code: * <p/> * <pre> * BucketTimer t = new BucketTimer( * MonitorConfig.builder(name).build(), * new BucketConfig.Builder().withBuckets(new long[]{10L, 20L}).build()); * </pre> * <p/> * will create a <code>BucketTimer</code> that in addition to the statistics: * <code>totalTime</code>, <code>min</code>, <code>max </code> will report: * <ul> * <li>statistic=count bucket=10ms</li> * <li>statistic=count bucket=20ms</li> * <li>statistic=count bucket=overflow</li> * </ul> * <p/> * <ul> * <li>bucket=10ms will contain the number of samples that were recorded that were * lower or equal to 10.</li> * <p/> * <li>bucket=20ms will contain the number of samples where the value was lower or equal to 20ms * and higher than 10.</li> * <p/> * <li>bucket=overflow will contain the remaining entries.</li> * </ul> * Please note that there are no default pre-configured buckets since it is highly dependant * on the use-case. If you fail to specify buckets in {@link BucketConfig} you will get a NPE. */ public class BucketTimer extends AbstractMonitor<Long> implements Timer, CompositeMonitor<Long>, SpectatorMonitor { private static final String STATISTIC = "statistic"; private static final String BUCKET = "servo.bucket"; private static final String UNIT = "unit"; private static final Tag STAT_TOTAL = Tags.newTag(STATISTIC, "totalTime"); private static final Tag STAT_COUNT = Tags.newTag(STATISTIC, "count"); private static final Tag STAT_MIN = Tags.newTag(STATISTIC, "min"); private static final Tag STAT_MAX = Tags.newTag(STATISTIC, "max"); private final TimeUnit timeUnit; private final Counter totalTime; private final Counter[] bucketCount; private final Counter overflowCount; private final MinGauge min; private final MaxGauge max; private final List<Monitor<?>> monitors; private final BucketConfig bucketConfig; /** * Creates a new instance of the timer with a unit of milliseconds. */ public BucketTimer(MonitorConfig config, BucketConfig bucketConfig) { this(config, bucketConfig, TimeUnit.MILLISECONDS); } /** * Creates a new instance of the timer. */ public BucketTimer(MonitorConfig config, BucketConfig bucketConfig, TimeUnit unit) { this(config, bucketConfig, unit, ClockWithOffset.INSTANCE); } BucketTimer(MonitorConfig config, BucketConfig bucketConfig, TimeUnit unit, Clock clock) { super(config); this.bucketConfig = Preconditions.checkNotNull(bucketConfig, "bucketConfig"); final Tag unitTag = Tags.newTag(UNIT, unit.name()); final MonitorConfig unitConfig = config.withAdditionalTag(unitTag); this.timeUnit = unit; this.totalTime = new BasicCounter(unitConfig.withAdditionalTag(STAT_TOTAL)); this.overflowCount = new BasicCounter(unitConfig .withAdditionalTag(STAT_COUNT) .withAdditionalTag(Tags.newTag(BUCKET, "bucket=overflow"))); this.min = new MinGauge(unitConfig.withAdditionalTag(STAT_MIN), clock); this.max = new MaxGauge(unitConfig.withAdditionalTag(STAT_MAX), clock); final long[] buckets = bucketConfig.getBuckets(); final int numBuckets = buckets.length; final int numDigits = Long.toString(buckets[numBuckets - 1]).length(); final String label = bucketConfig.getTimeUnitAbbreviation(); this.bucketCount = new Counter[numBuckets]; for (int i = 0; i < numBuckets; i++) { bucketCount[i] = new BasicCounter(unitConfig .withAdditionalTag(STAT_COUNT) .withAdditionalTag(Tags.newTag(BUCKET, String.format("bucket=%0" + numDigits + "d%s", buckets[i], label))) ); } List<Monitor<?>> monitorList = new ArrayList<>(); monitorList.add(totalTime); monitorList.add(min); monitorList.add(max); monitorList.addAll(Arrays.asList(bucketCount)); monitorList.add(overflowCount); this.monitors = Collections.unmodifiableList(monitorList); } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { monitors.forEach(m -> { if (m instanceof SpectatorMonitor) { ((SpectatorMonitor) m).initializeSpectator(tags); } }); } /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { return monitors; } /** * {@inheritDoc} */ @Override public Stopwatch start() { Stopwatch s = new TimedStopwatch(this); s.start(); return s; } /** * {@inheritDoc} */ @Override public TimeUnit getTimeUnit() { return timeUnit; } /** * {@inheritDoc} */ @Override public void record(long duration) { totalTime.increment(duration); min.update(duration); max.update(duration); final long[] buckets = bucketConfig.getBuckets(); final long bucketDuration = bucketConfig.getTimeUnit().convert(duration, timeUnit); for (int i = 0; i < buckets.length; i++) { if (bucketDuration <= buckets[i]) { bucketCount[i].increment(); return; } } overflowCount.increment(); } /** * {@inheritDoc} */ @Override public void record(long duration, TimeUnit unit) { record(this.timeUnit.convert(duration, unit)); } /** * {@inheritDoc} */ @Override public Long getValue(int pollerIndex) { final long cnt = getCount(pollerIndex); return (cnt == 0) ? 0L : totalTime.getValue().longValue() / cnt; } /** * Get the total time for all updates. */ public Long getTotalTime() { return totalTime.getValue().longValue(); } /** * Get the total number of updates. */ public Long getCount(int pollerIndex) { long updates = 0; for (Counter c : bucketCount) { updates += c.getValue(pollerIndex).longValue(); } updates += overflowCount.getValue(pollerIndex).longValue(); return updates; } /** * Get the min value since the last reset. */ public Long getMin(int pollerIndex) { return min.getValue(pollerIndex); } /** * Get the max value since the last reset. */ public Long getMax(int pollerIndex) { return max.getValue(pollerIndex); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof BucketTimer)) { return false; } BucketTimer m = (BucketTimer) obj; return config.equals(m.getConfig()) && bucketConfig.equals(m.bucketConfig) && timeUnit.equals(m.timeUnit) && totalTime.equals(m.totalTime) && min.equals(m.min) && max.equals(m.max) && overflowCount.equals(m.overflowCount) && Arrays.equals(bucketCount, m.bucketCount); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + timeUnit.hashCode(); result = 31 * result + totalTime.hashCode(); result = 31 * result + Arrays.hashCode(bucketCount); result = 31 * result + overflowCount.hashCode(); result = 31 * result + min.hashCode(); result = 31 * result + max.hashCode(); result = 31 * result + bucketConfig.hashCode(); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "BucketTimer{config=" + config + ", bucketConfig=" + bucketConfig + ", timeUnit=" + timeUnit + ", totalTime=" + totalTime + ", min=" + min + ", max=" + max + ", bucketCount=" + Arrays.toString(bucketCount) + ", overflowCount=" + overflowCount + '}'; } }
2,895
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/TimedStopwatch.java
/* * Copyright 2014 Netflix, Inc. * * Licensed 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.netflix.servo.monitor; import com.netflix.servo.util.Preconditions; import java.util.concurrent.TimeUnit; /** * Stopwatch that will also record to a timer. */ public class TimedStopwatch extends BasicStopwatch { private final Timer timer; /** * Create a new instance with the specified timer. */ public TimedStopwatch(Timer timer) { Preconditions.checkNotNull(timer, "timer"); this.timer = timer; } /** * {@inheritDoc} */ @Override public void stop() { super.stop(); timer.record(getDuration(), TimeUnit.NANOSECONDS); } }
2,896
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/TimedInterface.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.TagList; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * This class creates a {@link java.lang.reflect.Proxy} monitor that tracks all calls to methods * of an interface. * <p/> * <pre> * IDummy dummy = TimedInterface.newProxy(IDummy.class, new DummyImpl(), "id"); * DefaultMonitorRegistry.getInstance().register((CompositeMonitor)dummy); * </pre> * <p/> * <p> * All calls to methods implemented by IDummy would have an associated BasicTimer with them. The * name for the {@link CompositeMonitor} is the name of the method. Additional tags are added: * <ul> * <li><code>interface</code> interface being implemented. * <li><code>class</code> simple name of the concrete class implementing the interface. * <li><code>id</code> (Optional) An identifier for this particular instance. * </ul> * </p> */ public final class TimedInterface { static final String TIMED_INTERFACE = "TimedInterface"; static final String INTERFACE_TAG = "interface"; static final String CLASS_TAG = "class"; static final String ID_TAG = "id"; private static class TimedHandler<T> implements InvocationHandler, CompositeMonitor<Long> { private final T concrete; private final Map<String, Timer> timers; private final MonitorConfig baseConfig; private final TagList baseTagList; /** * {@inheritDoc} */ @Override public List<Monitor<?>> getMonitors() { return timers.values().stream().collect(Collectors.toList()); } @Override public Long getValue(int pollerIdx) { return (long) timers.size(); } @Override public Long getValue() { return getValue(0); } /** * {@inheritDoc} */ @Override public MonitorConfig getConfig() { return baseConfig; } TimedHandler(Class<T> ctype, T concrete, String id) { this.concrete = concrete; BasicTagList tagList = BasicTagList.of( INTERFACE_TAG, ctype.getSimpleName(), CLASS_TAG, concrete.getClass().getSimpleName()); if (id != null) { tagList = tagList.copy(ID_TAG, id); } baseTagList = tagList; baseConfig = MonitorConfig.builder(TIMED_INTERFACE).withTags(baseTagList).build(); timers = new HashMap<>(); for (Method method : ctype.getMethods()) { final MonitorConfig config = MonitorConfig.builder(method.getName()) .withTags(baseTagList) .build(); timers.put(method.getName(), new BasicTimer(config)); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // if the method is one of the CompositeMonitor interface final Class<?> declaringClass = method.getDeclaringClass(); if (declaringClass.isAssignableFrom(CompositeMonitor.class)) { return method.invoke(this, args); } final String methodName = method.getName(); final Timer timer = timers.get(methodName); final Stopwatch stopwatch = timer.start(); try { return method.invoke(concrete, args); } finally { stopwatch.stop(); } } } private TimedInterface() { } /** * Creates a new TimedInterface for a given interface <code>ctype</code> with a concrete class * <code>concrete</code> and a specific id. The id can be used to distinguish among multiple * objects with the same concrete class. */ @SuppressWarnings("unchecked") public static <T> T newProxy(Class<T> ctype, T concrete, String id) { final InvocationHandler handler = new TimedHandler<>(ctype, concrete, id); final Class<?>[] types = new Class[]{ctype, CompositeMonitor.class}; return (T) Proxy.newProxyInstance(ctype.getClassLoader(), types, handler); } /** * Creates a new TimedInterface for a given interface <code>ctype</code> with a concrete class * <code>concrete</code>. */ public static <T> T newProxy(Class<T> ctype, T concrete) { return newProxy(ctype, concrete, null); } }
2,897
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/SpectatorMonitorWrapper.java
package com.netflix.servo.monitor; import com.netflix.servo.tag.TagList; class SpectatorMonitorWrapper<T extends Number> extends NumericMonitorWrapper<T> implements SpectatorMonitor { SpectatorMonitorWrapper(TagList tags, NumericMonitor<T> monitor) { super(tags, monitor); if (monitor instanceof SpectatorMonitor) { ((SpectatorMonitor) monitor).initializeSpectator(tags); } } /** * {@inheritDoc} */ @Override public void initializeSpectator(TagList tags) { } }
2,898
0
Create_ds/servo/servo-core/src/main/java/com/netflix/servo
Create_ds/servo/servo-core/src/main/java/com/netflix/servo/monitor/AnnotatedStringMonitor.java
/** * Copyright 2013 Netflix, Inc. * <p/> * Licensed 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.netflix.servo.monitor; import com.netflix.servo.util.Throwables; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Wraps an annotated field and exposes it as a monitor object. */ class AnnotatedStringMonitor extends AbstractMonitor<String> { private final Object object; private final AccessibleObject field; AnnotatedStringMonitor(MonitorConfig config, Object object, AccessibleObject field) { super(config); this.object = object; this.field = field; } /** * {@inheritDoc} */ @Override public String getValue(int pollerIndex) { Object v; try { field.setAccessible(true); if (field instanceof Field) { v = ((Field) field).get(object); } else { v = ((Method) field).invoke(object); } } catch (Exception e) { throw Throwables.propagate(e); } return (v == null) ? null : v.toString(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof AnnotatedStringMonitor)) { return false; } AnnotatedStringMonitor m = (AnnotatedStringMonitor) obj; return config.equals(m.getConfig()) && field.equals(m.field); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = config.hashCode(); result = 31 * result + field.hashCode(); return result; } @Override public String toString() { return "AnnotatedStringMonitor{config=" + config + ", field=" + field + '}'; } }
2,899