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/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart/model/LineStyle.java
/* * Copyright 2014-2023 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.atlas.chart.model; /** * Line styles for how to render an time series. */ public enum LineStyle { LINE, AREA, STACK, VSPAN, HEATMAP }
5,600
0
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart/model/Scale.java
/* * Copyright 2014-2023 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.atlas.chart.model; /** * Type of scale to use for mapping raw input values into y-coordinates on the chart. */ public enum Scale { LINEAR, LOGARITHMIC, LOG_LINEAR, POWER_2, SQRT; /** Returns the scale constant associated with a given name. */ public static Scale fromName(String s) { return switch (s) { case "linear" -> LINEAR; case "log" -> LOGARITHMIC; case "log-linear" -> LOG_LINEAR; case "pow2" -> POWER_2; case "sqrt" -> SQRT; default -> throw new IllegalArgumentException("unknown scale type '" + s + "', should be linear, log, log-linear, pow2, or sqrt"); }; } }
5,601
0
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart/model/LegendType.java
/* * Copyright 2014-2023 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.atlas.chart.model; /** * Mode for the legend. */ public enum LegendType { OFF, LABELS_ONLY, LABELS_WITH_STATS }
5,602
0
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart/graphics/TextAlignment.java
/* * Copyright 2014-2023 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.atlas.chart.graphics; /** * How to align text when wrapping to fit a display width. */ public enum TextAlignment { LEFT, RIGHT, CENTER }
5,603
0
Create_ds/atlas/atlas-json/src/test/scala/com/netflix/atlas
Create_ds/atlas/atlas-json/src/test/scala/com/netflix/atlas/json/ObjWithLambda.java
/* * Copyright 2014-2023 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.atlas.json; import java.util.function.Function; /** * Simple test object to verify lambda issue with paranamer is fixed: * * https://github.com/FasterXML/jackson-module-paranamer/issues/13 * https://github.com/paul-hammant/paranamer/issues/17 * * <pre> * java.lang.ArrayIndexOutOfBoundsException: 55596 * at com.fasterxml.jackson.module.paranamer.shaded.BytecodeReadingParanamer$ClassReader.readUnsignedShort(BytecodeReadingParanamer.java:722) * at com.fasterxml.jackson.module.paranamer.shaded.BytecodeReadingParanamer$ClassReader.accept(BytecodeReadingParanamer.java:571) * at com.fasterxml.jackson.module.paranamer.shaded.BytecodeReadingParanamer$ClassReader.access$200(BytecodeReadingParanamer.java:338) * at com.fasterxml.jackson.module.paranamer.shaded.BytecodeReadingParanamer.lookupParameterNames(BytecodeReadingParanamer.java:103) * at com.fasterxml.jackson.module.paranamer.shaded.CachingParanamer.lookupParameterNames(CachingParanamer.java:79) * </pre> */ public class ObjWithLambda { private String foo; public void setFoo(String value) { final Function<String, String> check = v -> { if (v == null) throw new NullPointerException("value cannot be null"); return v; }; foo = check.apply(value); } public String getFoo() { return foo; } }
5,604
0
Create_ds/openh264/test/build/android/src/com/cisco/codec
Create_ds/openh264/test/build/android/src/com/cisco/codec/unittest/MainActivity.java
package com.cisco.codec.unittest; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.util.Log; import android.widget.TextView; import android.os.Build; import android.os.Process; public class MainActivity extends Activity { private TextView mStatusView; @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); mStatusView = (TextView)findViewById (R.id.status_view); runUnitTest(); } @Override public void onDestroy() { super.onDestroy(); Log.i ("codec_unittest", "OnDestroy"); Process.killProcess (Process.myPid()); } public void runUnitTest() { Thread thread = new Thread() { public void run() { Log.i ("codec_unittest", "codec unittest begin"); CharSequence text = "Running..."; if (mStatusView != null) { mStatusView.setText (text); } // String path = getIntent().getStringExtra("path"); // if (path.length() <=0) // { // path = "/sdcard/codec_unittest.xml"; // } String path = "/sdcard/codec_unittest.xml"; Log.i ("codec_unittest", "codec unittest runing @" + path); DoUnittest ("/sdcard", path); Log.i ("codec_unittest", "codec unittest end"); finish(); } }; thread.start(); } static { try { System.loadLibrary ("stlport_shared"); //System.loadLibrary("openh264"); System.loadLibrary ("ut"); System.loadLibrary ("utDemo"); } catch (Exception e) { Log.v ("codec_unittest", "Load library failed"); } } public native void DoUnittest (String directory, String path); }
5,605
0
Create_ds/openh264/codec/build/android/enc/src/com/wels
Create_ds/openh264/codec/build/android/enc/src/com/wels/enc/WelsEncTest.java
package com.wels.enc; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.Process; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import java.io.*; import java.util.Vector; public class WelsEncTest extends Activity { /** Called when the activity is first created. */ private OnClickListener OnClickEvent; private Button mBtnLoad, mBtnStartSW; final String mStreamPath = "/sdcard/welsenc/"; Vector<String> mCfgFiles = new Vector<String>(); @Override public void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); final TextView tv = new TextView (this); System.out.println ("Here we go ..."); Log.i (TAG, "sdcard path:" + Environment.getExternalStorageDirectory().getAbsolutePath()); setContentView (R.layout.main); mBtnLoad = (Button)findViewById (R.id.cfg); mBtnStartSW = (Button)findViewById (R.id.buttonSW); OnClickEvent = new OnClickListener() { public void onClick (View v) { switch (v.getId()) { case R.id.cfg: { String cfgFile = mStreamPath + "cfgs.txt"; try { BufferedReader bufferedReader = new BufferedReader (new FileReader (cfgFile)); String text; while ((text = bufferedReader.readLine()) != null) { mCfgFiles.add (mStreamPath + text); Log.i (TAG, mStreamPath + text); } bufferedReader.close(); } catch (IOException e) { Log.e (TAG, e.getMessage()); } } break; case R.id.buttonSW: { System.out.println ("encode sequence number = " + mCfgFiles.size()); Log.i (TAG, "after click"); try { for (int k = 0; k < mCfgFiles.size(); k++) { String cfgFile = mCfgFiles.get (k); DoEncoderTest (cfgFile); } } catch (Exception e) { Log.e (TAG, e.getMessage()); } mCfgFiles.clear(); tv.setText ("Encoder is completed!"); } break; } } }; mBtnLoad.setOnClickListener (OnClickEvent); mBtnStartSW.setOnClickListener (OnClickEvent); System.out.println ("Done!"); //run the test automatically,if you not want to autotest, just comment this line runAutoEnc(); } public void runAutoEnc() { Thread thread = new Thread() { public void run() { Log.i (TAG, "encoder performance test begin"); String inYuvfile = null, outBitfile = null, inOrgfile = null, inLayerfile = null; File encCase = new File (mStreamPath); String[] caseNum = encCase.list(); if (caseNum == null || caseNum.length == 0) { Log.i (TAG, "have not find any encoder resourse"); finish(); } for (int i = 0; i < caseNum.length; i++) { String[] yuvName = null; File yuvPath = null; File encCaseNo = new File (mStreamPath + caseNum[i]); String[] encFile = encCaseNo.list(); for (int k = 0; k < encFile.length; k++) { if (encFile[k].compareToIgnoreCase ("welsenc.cfg") == 0) inOrgfile = encCaseNo + File.separator + encFile[k]; else if (encFile[k].compareToIgnoreCase ("layer2.cfg") == 0) inLayerfile = encCaseNo + File.separator + encFile[k]; else if (encFile[k].compareToIgnoreCase ("yuv") == 0) { yuvPath = new File (encCaseNo + File.separator + encFile[k]); yuvName = yuvPath.list(); } } for (int m = 0; m < yuvName.length; m++) { inYuvfile = yuvPath + File.separator + yuvName[m]; outBitfile = inYuvfile + ".264"; Log.i (TAG, "enc yuv file:" + yuvName[m]); DoEncoderAutoTest (inOrgfile, inLayerfile, inYuvfile, outBitfile); } } Log.i (TAG, "encoder performance test finish"); finish(); } }; thread.start(); } @Override public void onStart() { Log.i (TAG, "welsencdemo onStart"); super.onStart(); } @Override public void onDestroy() { super.onDestroy(); Log.i (TAG, "OnDestroy"); Process.killProcess (Process.myPid()); } @Override public boolean onKeyDown (int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: return true; default: return super.onKeyDown (keyCode, event); } } public native void DoEncoderTest (String cfgFileName); public native void DoEncoderAutoTest (String cfgFileName, String layerFileName, String yuvFileName, String outBitsName); private static final String TAG = "welsenc"; static { try { System.loadLibrary ("openh264"); System.loadLibrary ("c++_shared"); System.loadLibrary ("welsencdemo"); Log.v (TAG, "Load libwelsencdemo.so successful"); } catch (Exception e) { Log.e (TAG, "Failed to load welsenc" + e.getMessage()); } } }
5,606
0
Create_ds/openh264/codec/build/android/dec/src/com/wels
Create_ds/openh264/codec/build/android/dec/src/com/wels/dec/WelsDecTest.java
package com.wels.dec; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.Process; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import java.io.*; import java.util.Vector; public class WelsDecTest extends Activity { /** Called when the activity is first created. */ private OnClickListener OnClickEvent; private Button mBtnLoad, mBtnStartSW; final String mStreamPath = "/sdcard/welsdec/"; Vector<String> mStreamFiles = new Vector<String>(); @Override public void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); final TextView tv = new TextView (this); System.out.println ("Here we go ..."); Log.i (TAG, "sdcard path:" + Environment.getExternalStorageDirectory().getAbsolutePath()); setContentView (R.layout.main); mBtnLoad = (Button)findViewById (R.id.cfg); mBtnStartSW = (Button)findViewById (R.id.buttonSW); OnClickEvent = new OnClickListener() { public void onClick (View v) { switch (v.getId()) { case R.id.cfg: { String cfgFile = mStreamPath + "BitStreams.txt"; try { BufferedReader bufferedReader = new BufferedReader (new FileReader (cfgFile)); String text; while ((text = bufferedReader.readLine()) != null) { mStreamFiles.add (mStreamPath + text); Log.i (TAG, mStreamPath + text); } bufferedReader.close(); } catch (IOException e) { Log.e ("WELS_DEC", e.getMessage()); } } break; case R.id.buttonSW: { System.out.println ("decode sequence number = " + mStreamFiles.size()); Log.i ("WSE_DEC", "after click"); try { for (int k = 0; k < mStreamFiles.size(); k++) { String inFile = mStreamFiles.get (k); String outFile = mStreamFiles.get (k) + ".yuv"; Log.i (TAG, "input file:" + inFile + " output file:" + outFile); DoDecoderTest (inFile, outFile); } } catch (Exception e) { Log.e (TAG, e.getMessage()); } mStreamFiles.clear(); tv.setText ("Decoder is completed!"); } break; } } }; mBtnLoad.setOnClickListener (OnClickEvent); mBtnStartSW.setOnClickListener (OnClickEvent); System.out.println ("Done!"); //if you want to run the demo manually, just comment following 2 lines runAutoDec(); } public void runAutoDec() { Thread thread = new Thread() { public void run() { Log.i (TAG, "decoder performance test begin"); File bitstreams = new File (mStreamPath); String[] list = bitstreams.list(); if (list == null || list.length == 0) { Log.i (TAG, "have not find any coder resourse"); finish(); } for (int i = 0; i < list.length; i++) { String inFile = list[i]; inFile = mStreamPath + inFile; String outFile = inFile + ".yuv"; DoDecoderTest (inFile, outFile); } Log.i (TAG, "decoder performance test finish"); finish(); } }; thread.start(); } @Override public void onStart() { Log.i ("WSE_DEC", "welsdecdemo onStart"); super.onStart(); } @Override public void onDestroy() { super.onDestroy(); Log.i (TAG, "OnDestroy"); Process.killProcess (Process.myPid()); } @Override public boolean onKeyDown (int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: return true; default: return super.onKeyDown (keyCode, event); } } public native void DoDecoderTest (String infilename, String outfilename); private static final String TAG = "welsdec"; static { try { System.loadLibrary ("openh264"); System.loadLibrary ("c++_shared"); System.loadLibrary ("welsdecdemo"); Log.v (TAG, "Load libwelsdec successful"); } catch (Exception e) { Log.e (TAG, "Failed to load welsdec" + e.getMessage()); } } }
5,607
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/IpcStatusTest.java
/* * Copyright 2014-2019 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.spectator.ipc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import javax.net.ssl.SSLException; import java.io.IOException; import java.net.ConnectException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.concurrent.TimeoutException; public class IpcStatusTest { @Test public void forHttpStatusNegative() { Assertions.assertEquals(IpcStatus.unexpected_error, IpcStatus.forHttpStatus(-1)); } @Test public void forHttpStatus1xx() { Assertions.assertEquals(IpcStatus.success, IpcStatus.forHttpStatus(100)); } @Test public void forHttpStatus2xx() { Assertions.assertEquals(IpcStatus.success, IpcStatus.forHttpStatus(200)); } @Test public void forHttpStatus3xx() { Assertions.assertEquals(IpcStatus.success, IpcStatus.forHttpStatus(304)); } @Test public void forHttpStatus404() { Assertions.assertEquals(IpcStatus.success, IpcStatus.forHttpStatus(404)); } @Test public void forHttpStatus403() { Assertions.assertEquals(IpcStatus.access_denied, IpcStatus.forHttpStatus(403)); } @Test public void forHttpStatus429() { Assertions.assertEquals(IpcStatus.throttled, IpcStatus.forHttpStatus(429)); } @Test public void forHttpStatus4xx() { Assertions.assertEquals(IpcStatus.bad_request, IpcStatus.forHttpStatus(487)); } @Test public void forHttpStatus503() { Assertions.assertEquals(IpcStatus.throttled, IpcStatus.forHttpStatus(503)); } @Test public void forHttpStatusStandard503() { Assertions.assertEquals(IpcStatus.unavailable, IpcStatus.forHttpStatusStandard(503)); } @Test public void forHttpStatus5xx() { Assertions.assertEquals(IpcStatus.unexpected_error, IpcStatus.forHttpStatus(587)); } @Test public void forHttpStatusTooBig() { Assertions.assertEquals(IpcStatus.unexpected_error, IpcStatus.forHttpStatus(123456)); } @Test public void forExceptionIO() { Throwable t = new IOException(); Assertions.assertEquals(IpcStatus.connection_error, IpcStatus.forException(t)); } @Test public void forExceptionSocket() { Throwable t = new SocketException(); Assertions.assertEquals(IpcStatus.connection_error, IpcStatus.forException(t)); } @Test public void forExceptionUnknownHost() { Throwable t = new UnknownHostException(); Assertions.assertEquals(IpcStatus.connection_error, IpcStatus.forException(t)); } @Test public void forExceptionConnect() { Throwable t = new ConnectException(); Assertions.assertEquals(IpcStatus.connection_error, IpcStatus.forException(t)); } @Test public void forExceptionTimeout() { Throwable t = new TimeoutException(); Assertions.assertEquals(IpcStatus.timeout, IpcStatus.forException(t)); } @Test public void forExceptionSocketTimeout() { Throwable t = new SocketTimeoutException(); Assertions.assertEquals(IpcStatus.timeout, IpcStatus.forException(t)); } @Test public void forExceptionIllegalArgument() { Throwable t = new IllegalArgumentException(); Assertions.assertEquals(IpcStatus.bad_request, IpcStatus.forException(t)); } @Test public void forExceptionIllegalState() { Throwable t = new IllegalStateException(); Assertions.assertEquals(IpcStatus.bad_request, IpcStatus.forException(t)); } @Test public void forExceptionRuntime() { Throwable t = new RuntimeException(); Assertions.assertEquals(IpcStatus.unexpected_error, IpcStatus.forException(t)); } @Test public void forExceptionSSL() { Throwable t = new SSLException("test"); Assertions.assertEquals(IpcStatus.access_denied, IpcStatus.forException(t)); } }
5,608
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/IpcLogEntryTest.java
/* * Copyright 2014-2023 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.spectator.ipc; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.DistributionSummary; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class IpcLogEntryTest { private final ManualClock clock = new ManualClock(); private final ObjectMapper mapper = new ObjectMapper(); private final IpcLogEntry entry = new IpcLogEntry(clock); @BeforeEach public void before() { clock.setWallTime(0L); clock.setMonotonicTime(0L); entry.reset(); } @SuppressWarnings("unchecked") private Map<String, Object> toMap(IpcLogEntry entry) { try { return (Map<String, Object>) mapper.readValue(entry.toString(), Map.class); } catch (IOException e) { throw new RuntimeException(e); } } @Test public void startTime() { long expected = 1234567890L; clock.setWallTime(expected); long actual = (int) entry .markStart() .convert(this::toMap) .get("start"); Assertions.assertEquals(expected, actual); } @Test public void startTimeOnlyComputedLatency() { long expected = 157; long t = 1234567890L; clock.setMonotonicTime(TimeUnit.MILLISECONDS.toNanos(t)); entry.markStart(); clock.setMonotonicTime(TimeUnit.MILLISECONDS.toNanos(t + expected)); double actual = (double) entry .convert(this::toMap) .get("latency"); Assertions.assertEquals(expected / 1000.0, actual, 1e-12); } @Test public void latency() { long expected = 157L; double actual = (double) entry .withLatency(expected, TimeUnit.MILLISECONDS) .convert(this::toMap) .get("latency"); Assertions.assertEquals(expected / 1000.0, actual, 1e-12); } @Test public void latencyAndStart() { long expected = 157L; long t = 1234567890L; clock.setWallTime(t); entry.markStart(); clock.setWallTime(t + expected + 42); double actual = (double) entry .withLatency(expected, TimeUnit.MILLISECONDS) .convert(this::toMap) .get("latency"); Assertions.assertEquals(expected / 1000.0, actual, 1e-12); } @Test public void owner() { String expected = "runtime"; String actual = (String) entry .withOwner(expected) .convert(this::toMap) .get("owner"); Assertions.assertEquals(expected, actual); } @Test public void standardProtocol() { String expected = IpcProtocol.http_2.value(); String actual = (String) entry .withProtocol(IpcProtocol.http_2) .convert(this::toMap) .get("protocol"); Assertions.assertEquals(expected, actual); } @Test public void customProtocol() { String expected = "nflx-proto"; String actual = (String) entry .withProtocol(expected) .convert(this::toMap) .get("protocol"); Assertions.assertEquals(expected, actual); } @Test public void status() { String expected = IpcStatus.cancelled.value(); String actual = (String) entry .withStatus(IpcStatus.cancelled) .convert(this::toMap) .get("status"); Assertions.assertEquals(expected, actual); } @Test public void statusDetail() { String expected = "connection_failed"; String actual = (String) entry .withStatusDetail(expected) .convert(this::toMap) .get("statusDetail"); Assertions.assertEquals(expected, actual); } @Test public void exceptionClass() { IOException io = new IOException("host not found exception"); String expected = "java.io.IOException"; String actual = (String) entry .withException(io) .convert(this::toMap) .get("exceptionClass"); Assertions.assertEquals(expected, actual); } @Test public void exceptionMessage() { String expected = "host not found exception"; IOException io = new IOException(expected); String actual = (String) entry .withException(io) .convert(this::toMap) .get("exceptionMessage"); Assertions.assertEquals(expected, actual); } @Test public void attempt() { String expected = IpcAttempt.third_up.value(); String actual = (String) entry .withAttempt(7) .convert(this::toMap) .get("attempt"); Assertions.assertEquals(expected, actual); } @Test public void attemptFinal() { String expected = IpcAttemptFinal.is_true.value(); String actual = (String) entry .withAttemptFinal(true) .convert(this::toMap) .get("attemptFinal"); Assertions.assertEquals(expected, actual); } @Test public void vip() { String expected = "www:7001"; String actual = (String) entry .withVip(expected) .convert(this::toMap) .get("vip"); Assertions.assertEquals(expected, actual); } @Test public void endpoint() { String expected = "/api/v1/test"; String actual = (String) entry .withEndpoint(expected) .convert(this::toMap) .get("endpoint"); Assertions.assertEquals(expected, actual); } @Test public void endpointViaUri() { String path = "/api/v1/1234567890"; String actual = (String) entry .withUri(URI.create(path)) .convert(this::toMap) .get("endpoint"); Assertions.assertEquals("_api_v1_-", actual); } @Test public void endpointViaUri404() { String path = "/api/v1/1234567890"; String actual = (String) entry .withUri(URI.create(path)) .withHttpStatus(404) .convert(this::toMap) .get("endpoint"); Assertions.assertEquals("unknown", actual); } @Test public void clientNode() { String expected = "i-12345"; String actual = (String) entry .withClientNode(expected) .convert(this::toMap) .get("clientNode"); Assertions.assertEquals(expected, actual); } @Test public void serverNode() { String expected = "i-12345"; String actual = (String) entry .withServerNode(expected) .convert(this::toMap) .get("serverNode"); Assertions.assertEquals(expected, actual); } @Test public void addRequestZoneHeader() { Map<String, Object> map = entry .addRequestHeader(NetflixHeader.Zone.headerName(), "us-east-1e") .convert(this::toMap); Assertions.assertEquals("us-east-1", map.get("clientRegion")); Assertions.assertEquals("us-east-1e", map.get("clientZone")); } @Test public void addRequestZoneHeaderExplicitRegion() { Map<String, Object> map = entry .withClientRegion("us-west-1") .addRequestHeader(NetflixHeader.Zone.headerName(), "us-east-1e") .convert(this::toMap); Assertions.assertEquals("us-west-1", map.get("clientRegion")); Assertions.assertEquals("us-east-1e", map.get("clientZone")); } @Test public void addRequestZoneHeaderExplicitZone() { Map<String, Object> map = entry .withClientZone("us-west-1b") .addRequestHeader(NetflixHeader.Zone.headerName(), "us-east-1e") .convert(this::toMap); Assertions.assertEquals("us-west-1", map.get("clientRegion")); Assertions.assertEquals("us-west-1b", map.get("clientZone")); } @Test public void addResponseZoneHeader() { Map<String, Object> map = entry .addResponseHeader(NetflixHeader.Zone.headerName(), "us-east-1e") .convert(this::toMap); Assertions.assertEquals("us-east-1", map.get("serverRegion")); Assertions.assertEquals("us-east-1e", map.get("serverZone")); } @Test public void addResponseZoneHeaderExplicitRegion() { Map<String, Object> map = entry .withServerRegion("us-west-1") .addResponseHeader(NetflixHeader.Zone.headerName(), "us-east-1e") .convert(this::toMap); Assertions.assertEquals("us-west-1", map.get("serverRegion")); Assertions.assertEquals("us-east-1e", map.get("serverZone")); } @Test public void addResponseZoneHeaderExplicitZone() { Map<String, Object> map = entry .withServerZone("us-west-1b") .addResponseHeader(NetflixHeader.Zone.headerName(), "us-east-1e") .convert(this::toMap); Assertions.assertEquals("us-west-1", map.get("serverRegion")); Assertions.assertEquals("us-west-1b", map.get("serverZone")); } @Test public void addRequestAsgHeader() { Map<String, Object> map = entry .addRequestHeader(NetflixHeader.ASG.headerName(), "www-test-v011") .convert(this::toMap); Assertions.assertEquals("www", map.get("clientApp")); Assertions.assertEquals("www-test", map.get("clientCluster")); Assertions.assertEquals("www-test-v011", map.get("clientAsg")); } @Test public void addRequestAsgHeaderCaseSensitivty() { Map<String, Object> map = entry .addRequestHeader("netflix-asg", "www-test-v011") .convert(this::toMap); Assertions.assertEquals("www", map.get("clientApp")); Assertions.assertEquals("www-test", map.get("clientCluster")); Assertions.assertEquals("www-test-v011", map.get("clientAsg")); } @Test public void addRequestAsgHeaderExplicitApp() { Map<String, Object> map = entry .withClientApp("foo") .addRequestHeader(NetflixHeader.ASG.headerName(), "www-test-v011") .convert(this::toMap); Assertions.assertEquals("foo", map.get("clientApp")); Assertions.assertEquals("www-test", map.get("clientCluster")); Assertions.assertEquals("www-test-v011", map.get("clientAsg")); } @Test public void addRequestAsgHeaderExplicitCluster() { Map<String, Object> map = entry .withClientCluster("foo") .addRequestHeader(NetflixHeader.ASG.headerName(), "www-test-v011") .convert(this::toMap); Assertions.assertEquals("www", map.get("clientApp")); Assertions.assertEquals("foo", map.get("clientCluster")); Assertions.assertEquals("www-test-v011", map.get("clientAsg")); } @Test public void addRequestAsgHeaderExplicitAsg() { Map<String, Object> map = entry .withClientAsg("foo") .addRequestHeader(NetflixHeader.ASG.headerName(), "www-test-v011") .convert(this::toMap); Assertions.assertEquals("foo", map.get("clientApp")); Assertions.assertEquals("foo", map.get("clientCluster")); Assertions.assertEquals("foo", map.get("clientAsg")); } @Test public void addResponseAsgHeader() { Map<String, Object> map = entry .addResponseHeader(NetflixHeader.ASG.headerName(), "www-test-v011") .convert(this::toMap); Assertions.assertEquals("www", map.get("serverApp")); Assertions.assertEquals("www-test", map.get("serverCluster")); Assertions.assertEquals("www-test-v011", map.get("serverAsg")); } @Test public void addResponseAsgHeaderCaseSensitivty() { Map<String, Object> map = entry .addResponseHeader("netflix-asg", "www-test-v011") .convert(this::toMap); Assertions.assertEquals("www", map.get("serverApp")); Assertions.assertEquals("www-test", map.get("serverCluster")); Assertions.assertEquals("www-test-v011", map.get("serverAsg")); } @Test public void addResponseAsgHeaderExplicitApp() { Map<String, Object> map = entry .withServerApp("foo") .addResponseHeader(NetflixHeader.ASG.headerName(), "www-test-v011") .convert(this::toMap); Assertions.assertEquals("foo", map.get("serverApp")); Assertions.assertEquals("www-test", map.get("serverCluster")); Assertions.assertEquals("www-test-v011", map.get("serverAsg")); } @Test public void addResponseAsgHeaderExplicitCluster() { Map<String, Object> map = entry .withServerCluster("foo") .addResponseHeader(NetflixHeader.ASG.headerName(), "www-test-v011") .convert(this::toMap); Assertions.assertEquals("www", map.get("serverApp")); Assertions.assertEquals("foo", map.get("serverCluster")); Assertions.assertEquals("www-test-v011", map.get("serverAsg")); } @Test public void addResponseAsgHeaderExplicitAsg() { Map<String, Object> map = entry .withServerAsg("foo") .addResponseHeader(NetflixHeader.ASG.headerName(), "www-test-v011") .convert(this::toMap); Assertions.assertEquals("foo", map.get("serverApp")); Assertions.assertEquals("foo", map.get("serverCluster")); Assertions.assertEquals("foo", map.get("serverAsg")); } @Test public void addRequestNodeHeader() { Map<String, Object> map = entry .addRequestHeader(NetflixHeader.Node.headerName(), "i-12345") .convert(this::toMap); Assertions.assertEquals("i-12345", map.get("clientNode")); } @Test public void addResponseNodeHeader() { Map<String, Object> map = entry .addResponseHeader(NetflixHeader.Node.headerName(), "i-12345") .convert(this::toMap); Assertions.assertEquals("i-12345", map.get("serverNode")); } @Test public void addRequestVipHeader() { Map<String, Object> map = entry .addRequestHeader(NetflixHeader.Vip.headerName(), "www:7001") .convert(this::toMap); Assertions.assertEquals("www:7001", map.get("vip")); } @Test public void addResponseEndpointHeader() { Map<String, Object> map = entry .addResponseHeader(NetflixHeader.Endpoint.headerName(), "/api/v1/test") .convert(this::toMap); Assertions.assertEquals("/api/v1/test", map.get("endpoint")); } @Test public void httpStatusOk() { String actual = (String) entry .withHttpStatus(200) .convert(this::toMap) .get("result"); Assertions.assertEquals(IpcResult.success.value(), actual); } @Test public void httpStatus400() { String actual = (String) entry .withHttpStatus(400) .convert(this::toMap) .get("result"); Assertions.assertEquals(IpcResult.failure.value(), actual); } @Test public void httpStatusWithExplicitResult() { String actual = (String) entry .withResult(IpcResult.failure) .withHttpStatus(200) .convert(this::toMap) .get("result"); Assertions.assertEquals(IpcResult.failure.value(), actual); } @Test public void httpStatus429() { String actual = (String) entry .withHttpStatus(429) .convert(this::toMap) .get("status"); Assertions.assertEquals(IpcStatus.throttled.value(), actual); } @Test public void httpStatus503() { String actual = (String) entry .withHttpStatus(503) .convert(this::toMap) .get("status"); Assertions.assertEquals(IpcStatus.throttled.value(), actual); } @Test public void httpMethod() { String expected = "GET"; String actual = (String) entry .withHttpMethod(expected) .convert(this::toMap) .get("httpMethod"); Assertions.assertEquals(expected, actual); } @Test public void uri() { String expected = "http://foo.com/api/v1/test"; String actual = (String) entry .withUri(URI.create(expected)) .convert(this::toMap) .get("uri"); Assertions.assertEquals(expected, actual); } @Test public void uriPath() { String expected = "http://foo.com/api/v1/test"; String actual = (String) entry .withUri(URI.create(expected)) .convert(this::toMap) .get("path"); Assertions.assertEquals("/api/v1/test", actual); } @Test public void remoteAddress() { String expected = "123.45.67.89"; String actual = (String) entry .withRemoteAddress(expected) .convert(this::toMap) .get("remoteAddress"); Assertions.assertEquals(expected, actual); } @Test public void remotePort() { int expected = 42; int actual = (int) entry .withRemotePort(expected) .convert(this::toMap) .get("remotePort"); Assertions.assertEquals(expected, actual); } @SuppressWarnings("unchecked") @Test public void addTags() { Map<String, String> actual = (Map<String, String>) entry .addTag(new BasicTag("k1", "v1")) .addTag("k2", "v2") .convert(this::toMap) .get("additionalTags"); Assertions.assertEquals(2, actual.size()); Assertions.assertEquals("v1", actual.get("k1")); Assertions.assertEquals("v2", actual.get("k2")); } @Test public void regionFromZoneAWS() { String expected = "us-east-1"; String actual = (String) entry .withClientZone(expected + "e") .convert(this::toMap) .get("clientRegion"); Assertions.assertEquals(expected, actual); } @Test public void regionFromZoneGCE() { String expected = "us-east1"; String actual = (String) entry .withClientZone(expected + "-e") .convert(this::toMap) .get("clientRegion"); Assertions.assertEquals(expected, actual); } @Test public void regionFromZoneUnknownShort() { String expected = "foo"; String actual = (String) entry .withClientZone(expected) .convert(this::toMap) .get("clientRegion"); Assertions.assertNull(actual); } @Test public void regionFromZoneUnknownLong() { String expected = "foobarbaz"; String actual = (String) entry .withClientZone(expected) .convert(this::toMap) .get("clientRegion"); Assertions.assertNull(actual); } @Test public void regionFromZoneAwsLocalZone() { String expected = "us-west-2-lax-1a"; String actual = (String) entry .withClientZone(expected) .convert(this::toMap) .get("clientRegion"); Assertions.assertEquals("us-west-2-lax-1", actual); } @SuppressWarnings("unchecked") @Test public void customHeaders() { List<Map<String, Object>> actual = (List<Map<String, Object>>) entry .addRequestHeader("foo", "bar") .addRequestHeader("foo", "bar2") .addRequestHeader("abc", "def") .convert(this::toMap) .get("requestHeaders"); Assertions.assertEquals(3, actual.size()); } @Test public void stringEscape() { for (char c = 0; c < 65535; ++c) { String actual = (String) entry .withStatusDetail("" + c) .convert(this::toMap) .get("statusDetail"); if (actual.length() == 0) { Assertions.assertTrue(Character.isISOControl(c)); Assertions.assertEquals("", actual); } else { Assertions.assertEquals("" + c, actual); } entry.reset(); } } @Test public void requestContentLength() { long expected = 42L; Number actual = (Number) entry .withRequestContentLength(expected) .convert(this::toMap) .get("requestContentLength"); Assertions.assertEquals(expected, actual.longValue()); } @Test public void responseContentLength() { long expected = 42L; Number actual = (Number) entry .withResponseContentLength(expected) .convert(this::toMap) .get("responseContentLength"); Assertions.assertEquals(expected, actual.longValue()); } @Test public void inflightRequests() { Registry registry = new DefaultRegistry(); DistributionSummary summary = registry.distributionSummary("ipc.client.inflight"); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); IpcLogEntry logEntry = logger.createClientEntry(); Assertions.assertEquals(0L, summary.totalAmount()); logEntry.markStart(); Assertions.assertEquals(1L, summary.totalAmount()); logEntry.markEnd(); Assertions.assertEquals(1L, summary.totalAmount()); } @Test public void inflightRequestsMany() { Registry registry = new DefaultRegistry(); DistributionSummary summary = registry.distributionSummary("ipc.client.inflight"); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); for (int i = 0; i < 10; ++i) { logger.createClientEntry().markStart().markEnd(); } Assertions.assertEquals((10 * 11) / 2, summary.totalAmount()); Assertions.assertEquals(10L, summary.count()); } @Test public void clientMetricsValidate() { Registry registry = new DefaultRegistry(); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); logger.createClientEntry() .withOwner("test") .markStart() .markEnd() .log(); IpcMetric.validate(registry, true); } @Test public void clientMetricsValidateHttpSuccess() { Registry registry = new DefaultRegistry(); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); logger.createClientEntry() .withOwner("test") .markStart() .markEnd() .withHttpStatus(200) .withRequestContentLength(123) .withResponseContentLength(456) .log(); IpcMetric.validate(registry, true); } @Test public void clientMetricsDisbled() { Registry registry = new DefaultRegistry(); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); logger.createClientEntry() .withOwner("test") .disableMetrics() // must be before markStart for inflight .markStart() .markEnd() .log(); Assertions.assertEquals(0, registry.stream().count()); } @Test public void serverMetricsValidate() { Registry registry = new DefaultRegistry(); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); logger.createServerEntry() .withOwner("test") .markStart() .markEnd() .log(); IpcMetric.validate(registry); } @Test public void serverMetricsDisabled() { Registry registry = new DefaultRegistry(); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); logger.createServerEntry() .withOwner("test") .disableMetrics() .markStart() .markEnd() .log(); Assertions.assertEquals(0, registry.stream().count()); } @Test public void serverMetricsDisabledViaHeader() { Registry registry = new DefaultRegistry(); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); logger.createServerEntry() .withOwner("test") .addRequestHeader("netflix-ingress-common-ipc-metrics", "true") .markStart() .markEnd() .log(); Assertions.assertEquals(0, registry.stream().count()); } @Test public void endpointUnknownIfNotSet() { Registry registry = new DefaultRegistry(); IpcLogger logger = new IpcLogger(registry, clock, LoggerFactory.getLogger(getClass())); logger.createServerEntry() .withOwner("test") .markStart() .markEnd() .log(); registry.counters().forEach(c -> { Assertions.assertEquals("unknown", Utils.getTagValue(c.id(), "ipc.endpoint")); }); } }
5,609
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/ServerGroupTest.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.frigga.Names; import com.netflix.frigga.conventions.sharding.Shard; import com.netflix.frigga.conventions.sharding.ShardingNamingConvention; import com.netflix.frigga.conventions.sharding.ShardingNamingResult; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Map; import java.util.Random; import java.util.function.BiFunction; public class ServerGroupTest { @Test public void parseApp() { String asg = "app"; ServerGroup expected = new ServerGroup(asg, -1, -1, asg.length()); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForApp() { String asg = "app"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForApp() { String asg = "app"; Assertions.assertEquals("app", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForApp() { String asg = "app"; Assertions.assertEquals("app", ServerGroup.parse(asg).asg()); } @Test public void getStackForApp() { String asg = "app"; Assertions.assertNull(ServerGroup.parse(asg).stack()); } @Test public void getDetailForApp() { String asg = "app"; Assertions.assertNull(ServerGroup.parse(asg).detail()); } @Test public void getShardsForApp() { String asg = "app"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForApp() { String asg = "app"; Assertions.assertNull(ServerGroup.parse(asg).sequence()); } @Test public void parseAppStack() { String asg = "app-stack"; ServerGroup expected = new ServerGroup(asg, 3, -1, asg.length()); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppStack() { String asg = "app-stack"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppStack() { String asg = "app-stack"; Assertions.assertEquals("app-stack", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppStack() { String asg = "app-stack"; Assertions.assertEquals("app-stack", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppStack() { String asg = "app-stack"; Assertions.assertEquals("stack", ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppStack() { String asg = "app-stack"; Assertions.assertNull(ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppStack() { String asg = "app-stack"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppStack() { String asg = "app-stack"; Assertions.assertNull(ServerGroup.parse(asg).sequence()); } @Test public void parseAppStackDetail() { String asg = "app-stack-detail"; ServerGroup expected = new ServerGroup(asg, 3, 9, asg.length()); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppStackDetail() { String asg = "app-stack-detail"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppStackDetail() { String asg = "app-stack-detail"; Assertions.assertEquals("app-stack-detail", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppStackDetail() { String asg = "app-stack-detail"; Assertions.assertEquals("app-stack-detail", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppStackDetail() { String asg = "app-stack-detail"; Assertions.assertEquals("stack", ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppStackDetail() { String asg = "app-stack-detail"; Assertions.assertEquals("detail", ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppStackDetail() { String asg = "app-stack-detail"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppStackDetail() { String asg = "app-stack-detail"; Assertions.assertNull(ServerGroup.parse(asg).sequence()); } @Test public void parseAppStackDetails() { String asg = "app-stack-detail_1-detail_2"; ServerGroup expected = new ServerGroup(asg, 3, 9, asg.length()); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppStackDetails() { String asg = "app-stack-detail_1-detail_2"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppStackDetails() { String asg = "app-stack-detail_1-detail_2"; Assertions.assertEquals("app-stack-detail_1-detail_2", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppStackDetails() { String asg = "app-stack-detail_1-detail_2"; Assertions.assertEquals("app-stack-detail_1-detail_2", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppStackDetails() { String asg = "app-stack-detail_1-detail_2"; Assertions.assertEquals("stack", ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppStackDetails() { String asg = "app-stack-detail_1-detail_2"; Assertions.assertEquals("detail_1-detail_2", ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppStackDetails() { String asg = "app-stack-detail_1-detail_2"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppStackDetails() { String asg = "app-stack-detail_1-detail_2"; Assertions.assertNull(ServerGroup.parse(asg).sequence()); } @Test public void parseAppDetail() { String asg = "app--detail"; ServerGroup expected = new ServerGroup(asg, 3, 4, asg.length()); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppDetail() { String asg = "app--detail"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppDetail() { String asg = "app--detail"; Assertions.assertEquals("app--detail", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppDetail() { String asg = "app--detail"; Assertions.assertEquals("app--detail", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppDetail() { String asg = "app--detail"; Assertions.assertNull(ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppDetail() { String asg = "app--detail"; Assertions.assertEquals("detail", ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppDetail() { String asg = "app--detail"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppDetail() { String asg = "app--detail"; Assertions.assertNull(ServerGroup.parse(asg).sequence()); } @Test public void parseAppSeq() { String asg = "app-v001"; ServerGroup expected = new ServerGroup(asg, 3, -1, asg.length() - 5); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppSeq() { String asg = "app-v001"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppSeq() { String asg = "app-v001"; Assertions.assertEquals("app", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppSeq() { String asg = "app-v001"; Assertions.assertEquals("app-v001", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppSeq() { String asg = "app-v001"; Assertions.assertNull(ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppSeq() { String asg = "app-v001"; Assertions.assertNull(ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppSeq() { String asg = "app-v001"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppSeq() { String asg = "app-v001"; Assertions.assertEquals("v001", ServerGroup.parse(asg).sequence()); } @Test public void parseAppStackSeq() { String asg = "app-stack-v001"; ServerGroup expected = new ServerGroup(asg, 3, 9, asg.length() - 5); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppStackSeq() { String asg = "app-stack-v001"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppStackSeq() { String asg = "app-stack-v001"; Assertions.assertEquals("app-stack", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppStackSeq() { String asg = "app-stack-v001"; Assertions.assertEquals("app-stack-v001", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppStackSeq() { String asg = "app-stack-v001"; Assertions.assertEquals("stack", ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppStackSeq() { String asg = "app-stack-v001"; Assertions.assertNull(ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppStackSeq() { String asg = "app-stack-v001"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppStackSeq() { String asg = "app-stack-v001"; Assertions.assertEquals("v001", ServerGroup.parse(asg).sequence()); } @Test public void parseAppStackDetailSeq() { String asg = "app-stack-detail-v001"; ServerGroup expected = new ServerGroup(asg, 3, 9, asg.length() - 5); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppStackDetailSeq() { String asg = "app-stack-detail-v001"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppStackDetailSeq() { String asg = "app-stack-detail-v001"; Assertions.assertEquals("app-stack-detail", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppStackDetailSeq() { String asg = "app-stack-detail-v001"; Assertions.assertEquals("app-stack-detail-v001", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppStackDetailSeq() { String asg = "app-stack-detail-v001"; Assertions.assertEquals("stack", ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppStackDetailSeq() { String asg = "app-stack-detail-v001"; Assertions.assertEquals("detail", ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppStackDetailSeq() { String asg = "app-stack-detail-v001"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppStackDetailSeq() { String asg = "app-stack-detail-v001"; Assertions.assertEquals("v001", ServerGroup.parse(asg).sequence()); } @Test public void parseAppStackDetailsSeq() { String asg = "app-stack-detail_1-detail_2-v001"; ServerGroup expected = new ServerGroup(asg, 3, 9, asg.length() - 5); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppStackDetailsSeq() { String asg = "app-stack-detail_1-detail_2-v001"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppStackDetailsSeq() { String asg = "app-stack-detail_1-detail_2-v001"; Assertions.assertEquals("app-stack-detail_1-detail_2", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppStackDetailsSeq() { String asg = "app-stack-detail_1-detail_2-v001"; Assertions.assertEquals("app-stack-detail_1-detail_2-v001", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppStackDetailsSeq() { String asg = "app-stack-detail_1-detail_2-v001"; Assertions.assertEquals("stack", ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppStackDetailsSeq() { String asg = "app-stack-detail_1-detail_2-v001"; Assertions.assertEquals("detail_1-detail_2", ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppStackDetailsSeq() { String asg = "app-stack-detail_1-detail_2-v001"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppStackDetailsSeq() { String asg = "app-stack-detail_1-detail_2-v001"; Assertions.assertEquals("v001", ServerGroup.parse(asg).sequence()); } @Test public void parseAppDetailSeq() { String asg = "app--detail-v001"; ServerGroup expected = new ServerGroup(asg, 3, 4, asg.length() - 5); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForAppDetailSeq() { String asg = "app--detail-v001"; Assertions.assertEquals("app", ServerGroup.parse(asg).app()); } @Test public void getClusterForAppDetailSeq() { String asg = "app--detail-v001"; Assertions.assertEquals("app--detail", ServerGroup.parse(asg).cluster()); } @Test public void getAsgForAppDetailSeq() { String asg = "app--detail-v001"; Assertions.assertEquals("app--detail-v001", ServerGroup.parse(asg).asg()); } @Test public void getStackForAppDetailSeq() { String asg = "app--detail-v001"; Assertions.assertNull(ServerGroup.parse(asg).stack()); } @Test public void getDetailForAppDetailSeq() { String asg = "app--detail-v001"; Assertions.assertEquals("detail", ServerGroup.parse(asg).detail()); } @Test public void getShardsForAppDetailSeq() { String asg = "app--detail-v001"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForAppDetailSeq() { String asg = "app--detail-v001"; Assertions.assertEquals("v001", ServerGroup.parse(asg).sequence()); } @Test public void parseEmptyApp() { String asg = "-v1698"; ServerGroup expected = new ServerGroup(asg, 0, -1, 0); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppEmptyApp() { String asg = "-v1698"; Assertions.assertNull(ServerGroup.parse(asg).app()); } @Test public void getClusterEmptyApp() { String asg = "-v1698"; Assertions.assertNull(ServerGroup.parse(asg).cluster()); } @Test public void parseEmptyString() { String asg = ""; ServerGroup expected = new ServerGroup(asg, -1, -1, 0); Assertions.assertEquals(expected, ServerGroup.parse(asg)); } @Test public void getAppForEmptyString() { String asg = ""; Assertions.assertNull(ServerGroup.parse(asg).app()); } @Test public void getClusterForEmptyString() { String asg = ""; Assertions.assertNull(ServerGroup.parse(asg).cluster()); } @Test public void getAsgForEmptyString() { String asg = ""; Assertions.assertNull(ServerGroup.parse(asg).asg()); } @Test public void getStackForEmptyString() { String asg = ""; Assertions.assertNull(ServerGroup.parse(asg).stack()); } @Test public void getDetailForEmptyString() { String asg = ""; Assertions.assertNull(ServerGroup.parse(asg).detail()); } @Test public void getShardsForEmptyString() { String asg = ""; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getSequenceForEmptyString() { String asg = ""; Assertions.assertNull(ServerGroup.parse(asg).sequence()); } @Test public void getShardsOnlyShard1() { String asg = "app-stack-x1shard1-detail-v000"; Assertions.assertEquals("shard1", ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getShardsOnlyShard2() { String asg = "app-stack-x2shard2-detail-v000"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertEquals("shard2", ServerGroup.parse(asg).shard2()); } @Test public void getShardsBoth() { String asg = "app-stack-x1shard1-x2shard2-detail-v000"; Assertions.assertEquals("shard1", ServerGroup.parse(asg).shard1()); Assertions.assertEquals("shard2", ServerGroup.parse(asg).shard2()); } @Test public void getShardsThree() { String asg = "app-stack-x1shard1-x2shard2-x3shard3-detail-v000"; Assertions.assertEquals("shard1", ServerGroup.parse(asg).shard1()); Assertions.assertEquals("shard2", ServerGroup.parse(asg).shard2()); } @Test public void getShardsOutOfOrder() { String asg = "app-stack-x2shard2-x1shard1-detail-v000"; Assertions.assertEquals("shard1", ServerGroup.parse(asg).shard1()); Assertions.assertEquals("shard2", ServerGroup.parse(asg).shard2()); } @Test public void getShardsLeadingDigits() { String asg = "app-stack-x10shard1-detail-v000"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getShardsGap() { String asg = "app-stack-x1shard1-foo-x2shard2-detail-v000"; Assertions.assertEquals("shard1", ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getShardsEndOfDetail() { String asg = "app-stack-detail-x1shard1-x2shard2-v000"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } @Test public void getShardsDuplicate() { String asg = "app-stack-x1a1-x2a2-x1b1-x2b2-v000"; Assertions.assertEquals("b1", ServerGroup.parse(asg).shard1()); Assertions.assertEquals("b2", ServerGroup.parse(asg).shard2()); } @Test public void getShardsEmpty() { String asg = "app-stack-x1-x2-v000"; Assertions.assertNull(ServerGroup.parse(asg).shard1()); Assertions.assertNull(ServerGroup.parse(asg).shard2()); } private void appendRandomString(Random r, StringBuilder builder) { int length = r.nextInt(20) + 1; for (int i = 0; i < length; ++i) { char c = (char) (r.nextInt(26) + 'a'); builder.append(c); } } private void appendRandomPart(Random r, StringBuilder builder) { // https://github.com/cfieber/frigga/blob/master/src/main/java/com/netflix/frigga/NameConstants.java#L29 String[] prefixes = {"x0", "x1", "x2", "x3", "c0", "d0", "h0", "p0", "r0", "u0", "w0", "z0"}; if (r.nextBoolean()) { builder.append(prefixes[r.nextInt(prefixes.length)]); } appendRandomString(r, builder); } private String randomServerGroup(Random r) { StringBuilder builder = new StringBuilder(); int parts = r.nextInt(6) + 1; for (int i = 0; i < parts; ++i) { if (r.nextBoolean()) { appendRandomPart(r, builder); } else { builder.append('v'); builder.append(r.nextInt(10_000_000)); } if (i != parts - 1) { builder.append('-'); } } return builder.toString(); } @Test public void compatibleWithFrigga() { // Seed the RNG so that each run is deterministic. In this case we are just using it to // generate a bunch of patterns to try ShardingNamingConvention convention = new ShardingNamingConvention(); BiFunction<Map<Integer, Shard>, Integer, String> getShard = (shards, i) -> { Shard s = shards.get(i); return s == null ? null : s.getShardValue(); }; Random r = new Random(42); for (int i = 0; i < 50_000; ++i) { String asg = randomServerGroup(r); ServerGroup sg = ServerGroup.parse(asg); Names frigga = Names.parseName(asg); Assertions.assertEquals(frigga.getApp(), sg.app(), "app: " + asg); Assertions.assertEquals(frigga.getCluster(), sg.cluster(), "cluster: " + asg); Assertions.assertEquals(frigga.getGroup(), sg.asg(), "asg: " + asg); Assertions.assertEquals(frigga.getStack(), sg.stack(), "stack: " + asg); Assertions.assertEquals(frigga.getDetail(), sg.detail(), "detail: " + asg); if (frigga.getDetail() == null) { continue; } try { ShardingNamingResult result = convention.extractNamingConvention(frigga.getDetail()); if (result.getResult().isPresent()) { Map<Integer, Shard> shards = result.getResult().get(); Assertions.assertEquals(getShard.apply(shards, 1), sg.shard1(), "shard1: " + asg); Assertions.assertEquals(getShard.apply(shards, 2), sg.shard2(), "shard2: " + asg); } else { Assertions.assertNull(sg.shard1(), "shard1: " + asg); Assertions.assertNull(sg.shard2(), "shard2: " + asg); } } catch (Exception e) { throw new RuntimeException("parsing shards failed: " + asg, e); } } } }
5,610
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/IpcAttemptTest.java
/* * Copyright 2014-2019 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.spectator.ipc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class IpcAttemptTest { @Test public void forAttemptNegative() { Assertions.assertEquals(IpcAttempt.unknown, IpcAttempt.forAttemptNumber(-1)); } @Test public void forAttemptZero() { Assertions.assertEquals(IpcAttempt.unknown, IpcAttempt.forAttemptNumber(0)); } @Test public void forAttemptOne() { Assertions.assertEquals(IpcAttempt.initial, IpcAttempt.forAttemptNumber(1)); } @Test public void forAttemptTwo() { Assertions.assertEquals(IpcAttempt.second, IpcAttempt.forAttemptNumber(2)); } @Test public void forAttemptThree() { Assertions.assertEquals(IpcAttempt.third_up, IpcAttempt.forAttemptNumber(3)); } @Test public void forAttemptGreaterThanThree() { for (int i = 4; i < 1000; ++i) { Assertions.assertEquals(IpcAttempt.third_up, IpcAttempt.forAttemptNumber(i)); } } }
5,611
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/IpcMetricTest.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.Duration; public class IpcMetricTest { private Registry registry = null; @BeforeEach public void init() { registry = new DefaultRegistry(); } @Test public void validateIdOk() { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); } @Test public void validateAttemptFinalTrue() { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.key(), "test") .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcAttemptFinal.is_true); IpcMetric.clientCall.validate(id, true); } @Test public void validateAttemptFinalFalse() { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.key(), "test") .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcAttemptFinal.is_false); IpcMetric.clientCall.validate(id, true); } @Test public void validateIdBadName() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId("ipc.client-call") .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); }); } @Test public void validateIdMissingResult() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); }); } @Test public void validateIdErrorStatusOnSuccess() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcStatus.bad_request) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); }); } @Test public void validateIdErrorGroupOnFailure() { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.failure) .withTag(IpcStatus.bad_request) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); } @Test public void validateIdSuccessStatusOnFailure() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.failure) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); }); } public void validateIdStatusDetailOnSuccess() { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcTagKey.statusDetail.tag("foo")) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); } @Test public void validateIdBadResultValue() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcTagKey.result.tag("foo")) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); }); } @Test public void validateIdBadStatusValue() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcTagKey.status.tag("foo")) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); }); } @Test public void validateIdBadAttemptFinalValue() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), "foo"); IpcMetric.clientCall.validate(id, true); }); } @Test public void validateIdUnspecifiedDimension() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), "foo") .withTag(IpcTagKey.clientApp.key(), "app"); IpcMetric.clientCall.validate(id, true); }); } @Test public void validateRegistryOk() { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); registry.timer(id).record(Duration.ofSeconds(42)); IpcMetric.validate(registry, true); } @Test public void validateRegistryTimerWrongType() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcTagKey.attemptFinal.key(), true); registry.counter(id).increment(); IpcMetric.validate(registry); }); } @Test public void validateRegistryDistSummaryWrongType() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientInflight.metricName()) .withTag(IpcTagKey.owner.tag("test")); registry.counter(id).increment(); IpcMetric.validate(registry); }); } @Test public void validateFailureInjectionOk() { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(IpcFailureInjection.none) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id, true); } @Test public void validateFailureInjectionInvalid() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Id id = registry.createId(IpcMetric.clientCall.metricName()) .withTag(IpcTagKey.owner.tag("test")) .withTag(IpcResult.success) .withTag(IpcStatus.success) .withTag(IpcAttempt.initial) .withTag(Tag.of(IpcTagKey.failureInjected.key(), "false")) .withTag(IpcTagKey.attemptFinal.key(), true); IpcMetric.clientCall.validate(id); }); } }
5,612
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/IpcAttemptFinalTest.java
/* * Copyright 2014-2019 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.spectator.ipc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class IpcAttemptFinalTest { @Test public void forValueTrue() { Assertions.assertEquals(IpcAttemptFinal.is_true, IpcAttemptFinal.forValue(true)); } @Test public void forValueFalse() { Assertions.assertEquals(IpcAttemptFinal.is_false, IpcAttemptFinal.forValue(false)); } }
5,613
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/http/HttpResponseTest.java
/* * Copyright 2014-2019 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.spectator.ipc.http; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class HttpResponseTest { @Test public void toStringEmpty() { HttpResponse res = new HttpResponse(200, Collections.emptyMap()); String expected = "HTTP/1.1 200\n\n... 0 bytes ...\n"; Assertions.assertEquals(expected, res.toString()); } @Test public void toStringContent() { byte[] entity = "content".getBytes(StandardCharsets.UTF_8); HttpResponse res = new HttpResponse(200, Collections.emptyMap(), entity); String expected = "HTTP/1.1 200\n\n... 7 bytes ...\n"; Assertions.assertEquals(expected, res.toString()); } @Test public void toStringHeaders() { Map<String, List<String>> headers = new HashMap<>(); headers.put("Date", Collections.singletonList("Mon, 27 Jul 2012 17:21:03 GMT")); headers.put("Content-Type", Collections.singletonList("application/json")); byte[] entity = "{}".getBytes(StandardCharsets.UTF_8); HttpResponse res = new HttpResponse(200, headers, entity); String expected = "HTTP/1.1 200\nContent-Type: application/json\nDate: Mon, 27 Jul 2012 17:21:03 GMT\n\n... 2 bytes ...\n"; Assertions.assertEquals(expected, res.toString()); } @Test public void header() { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); HttpResponse res = new HttpResponse(200, headers); Assertions.assertEquals("application/json", res.header("content-type")); Assertions.assertEquals("application/json", res.header("Content-Type")); } @Test public void dateHeaderNull() { Map<String, List<String>> headers = new HashMap<>(); HttpResponse res = new HttpResponse(200, headers); Assertions.assertNull(res.dateHeader("Date")); } @Test public void dateHeaderGMT() { Map<String, List<String>> headers = new HashMap<>(); headers.put("Date", Collections.singletonList("Fri, 27 Jul 2012 17:21:03 GMT")); HttpResponse res = new HttpResponse(200, headers); Instant expected = Instant.ofEpochMilli(1343409663000L); Assertions.assertEquals(expected, res.dateHeader("Date")); } @Test public void compressNoChange() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); headers.put("Content-Encoding", Collections.singletonList("gzip")); byte[] entity = HttpUtils.gzip("foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8)); HttpResponse res = new HttpResponse(200, headers, entity); Assertions.assertSame(res, res.compress()); } @Test public void compress() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); byte[] entity = "foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8); HttpResponse res = new HttpResponse(200, headers, entity); String entityString = new String( HttpUtils.gunzip(res.compress().entity()), StandardCharsets.UTF_8); Assertions.assertEquals("foo bar baz foo bar baz", entityString); Assertions.assertEquals("gzip", res.compress().header("Content-Encoding")); } @Test public void decompressNoChange() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); byte[] entity = HttpUtils.gzip("foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8)); HttpResponse res = new HttpResponse(200, headers, entity); Assertions.assertSame(res, res.decompress()); } @Test public void decompress() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); headers.put("Content-Encoding", Collections.singletonList("gzip")); byte[] entity = HttpUtils.gzip("foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8)); HttpResponse res = new HttpResponse(200, headers, entity); Assertions.assertEquals("foo bar baz foo bar baz", res.decompress().entityAsString()); Assertions.assertNull(res.decompress().header("content-encoding")); } @Test public void decompressEmpty() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); headers.put("Content-Encoding", Collections.singletonList("gzip")); HttpResponse res = new HttpResponse(200, headers); Assertions.assertEquals("", res.decompress().entityAsString()); Assertions.assertEquals(0, res.decompress().entity().length); } @Test public void entityInputStream() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); byte[] entity = "foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8); HttpResponse res = new HttpResponse(200, headers, entity); try (InputStream in = res.entityInputStream()) { Assertions.assertEquals("foo bar baz foo bar baz", toString(in)); } } @Test public void entityInputStreamCompressed() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); headers.put("Content-Encoding", Collections.singletonList("gzip")); byte[] entity = HttpUtils.gzip("foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8)); HttpResponse res = new HttpResponse(200, headers, entity); try (InputStream in = res.entityInputStream()) { Assertions.assertEquals("foo bar baz foo bar baz", toString(in)); } } private String toString(InputStream in) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer, 0, buffer.length)) > 0) { baos.write(buffer, 0, length); } return new String(baos.toByteArray(), StandardCharsets.UTF_8); } }
5,614
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/http/HttpUtilsTest.java
/* * Copyright 2014-2019 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.spectator.ipc.http; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.zip.Deflater; public class HttpUtilsTest { private String extract(String u) { return HttpUtils.clientNameForURI(URI.create(u)); } @Test public void relativeUri() { Assertions.assertEquals("default", extract("/foo")); } @Test public void dashFirst() { Assertions.assertEquals("ec2", extract("http://ec2-127-0-0-1.compute-1.amazonaws.com/foo")); } @Test public void dotFirst() { Assertions.assertEquals("foo", extract("http://foo.test.netflix.com/foo")); } @Test public void gzip() throws IOException { byte[] data = "foo bar baz".getBytes(StandardCharsets.UTF_8); String result = new String(HttpUtils.gunzip(HttpUtils.gzip(data)), StandardCharsets.UTF_8); Assertions.assertEquals("foo bar baz", result); } @Test public void gzipWithLevel() throws IOException { byte[] data = "foo bar baz".getBytes(StandardCharsets.UTF_8); String result = new String(HttpUtils.gunzip(HttpUtils.gzip(data, Deflater.BEST_SPEED)), StandardCharsets.UTF_8); Assertions.assertEquals("foo bar baz", result); } }
5,615
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/http/PathSanitizerTest.java
/* * Copyright 2014-2023 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.spectator.ipc.http; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.Set; import java.util.UUID; public class PathSanitizerTest { private final Random random = new Random(42); private String sanitize(String path) { return PathSanitizer.sanitize(path); } @Test public void emptyPath() { Assertions.assertEquals("none", sanitize("/")); Assertions.assertEquals("none", sanitize("")); Assertions.assertEquals("none", sanitize("/?a=1")); Assertions.assertEquals("none", sanitize("?a=1")); } @Test public void uuids() { String path = "/api/v1/foo/" + UUID.randomUUID(); Assertions.assertEquals("_api_v1_foo_-", sanitize(path)); } @Test public void matrixParameters() { String path = "/api/v1/foo;user=bob"; Assertions.assertEquals("_api_v1_foo", sanitize(path)); } @Test public void requestParameters() { String path = "/api/v1/foo?user=bob&version=1"; Assertions.assertEquals("_api_v1_foo", sanitize(path)); } @Test public void decimalNumbers() { String path = "/api/v1/foo/1234567890/123"; Assertions.assertEquals("_api_v1_foo_-_-", sanitize(path)); } @Test public void floatingPointNumbers() { String path = "/api/v1/foo/1234.567890/1e2"; Assertions.assertEquals("_api_v1_foo_-_-", sanitize(path)); } @Test public void hexNumbers() { String path = "/api/v1/foo/a1ed5bc27"; Assertions.assertEquals("_api_v1_foo_-", sanitize(path)); } @Test public void isoDate() { String path = "/api/v1/foo/2021-05-04T13:35:00.000Z"; Assertions.assertEquals("_api_v1_foo_-", sanitize(path)); } @Test public void versionNumber() { String path = "/api/4.2.3"; Assertions.assertEquals("_api_-", sanitize(path)); } @Test public void unixTimestamp() { String path = "/api/v1/foo/" + System.currentTimeMillis(); Assertions.assertEquals("_api_v1_foo_-", sanitize(path)); } @Test public void iso_3166_2() { String path = "/country/US"; Assertions.assertEquals("_country_-", sanitize(path)); } @Test public void iso_3166_lang() { String path = "/country/en-US"; Assertions.assertEquals("_country_-", sanitize(path)); } @Test public void graphql() { String path = "/graphql"; Assertions.assertEquals("_graphql", sanitize(path)); } @Test public void allowSet() { String path = "/foo-bar"; Assertions.assertEquals("_-", PathSanitizer.sanitize(path)); Set<String> allowed = Collections.singleton("foo-bar"); Assertions.assertEquals("_foo-bar", PathSanitizer.sanitize(path, allowed)); Assertions.assertEquals("_api_v1_foo-bar", PathSanitizer.sanitize("/api/v1" + path, allowed)); } @Test public void randomLookingString() { String path = "/random/AOTV16LMT2"; Assertions.assertEquals("_random_-", sanitize(path)); } @Test public void randomLookingString2() { String path = "/random/f3hnq9z8t"; Assertions.assertEquals("_random_-", sanitize(path)); } @Test public void hexStringsInt() { // Check that majority of hex strings are suppressed. int suppressed = 0; for (int i = 0; i < 1000; ++i) { String path = "/hex/" + String.format("%x", random.nextInt()); if ("_hex_-".equals(sanitize(path))) { ++suppressed; } } Assertions.assertTrue(suppressed > 950, "suppressed " + suppressed + " of 1000"); } @Test public void hexStringsLong() { // Check that majority of hex strings are suppressed. int suppressed = 0; for (int i = 0; i < 1000; ++i) { String path = "/hex/" + String.format("%x", random.nextLong()); if ("_hex_-".equals(sanitize(path))) { ++suppressed; } } Assertions.assertTrue(suppressed > 950, "suppressed " + suppressed + " of 1000"); } private String randomString(int n) { int bound = '~' - '!'; StringBuilder builder = new StringBuilder(); for (int i = 0; i < n; ++i) { char c = (char) ('!' + random.nextInt(bound)); builder.append(c == '/' || c == ';' ? 'a' : c); } return builder.toString(); } @Test public void random8() { // Check that majority of random strings are suppressed. int suppressed = 0; for (int i = 0; i < 1000; ++i) { String path = "/random/" + randomString(8); if ("_random_-".equals(sanitize(path))) { ++suppressed; } } Assertions.assertTrue(suppressed > 950, "suppressed " + suppressed + " of 1000"); } @Test public void random16() { // Check that majority of random strings are suppressed. int suppressed = 0; for (int i = 0; i < 1000; ++i) { String path = "/random/" + randomString(16); if ("_random_-".equals(sanitize(path))) { ++suppressed; } } Assertions.assertTrue(suppressed > 950, "suppressed " + suppressed + " of 1000"); } private String randomAlphaString(int n) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < n; ++i) { char c = (char) ('a' + random.nextInt(26)); builder.append(c); } return builder.toString(); } @Test public void randomAlpha8() { // Check that majority of random strings with only alpha characters are suppressed. This // is mostly based on runs of consonants, so shorter patterns are more likely to be missed. int suppressed = 0; for (int i = 0; i < 1000; ++i) { String path = "/random/" + randomAlphaString(8); if ("_random_-".equals(sanitize(path))) { ++suppressed; } } Assertions.assertTrue(suppressed > 500, "suppressed " + suppressed + " of 1000"); } @Test public void randomAlpha16() { // Check that majority of random strings with only alpha characters are suppressed. This // is mostly based on runs of consonants, so shorter patterns are more likely to be missed. int suppressed = 0; for (int i = 0; i < 1000; ++i) { String path = "/random/" + randomAlphaString(16); if ("_random_-".equals(sanitize(path))) { ++suppressed; } } Assertions.assertTrue(suppressed > 900, "suppressed " + suppressed + " of 1000"); } @Test public void randomAlphaUpper16() { // Check that majority of random strings with only alpha characters are suppressed. This // is mostly based on runs of consonants, so shorter patterns are more likely to be missed. int suppressed = 0; for (int i = 0; i < 1000; ++i) { String path = "/random/" + randomAlphaString(16).toUpperCase(Locale.US); if ("_random_-".equals(sanitize(path))) { ++suppressed; } } Assertions.assertTrue(suppressed > 900, "suppressed " + suppressed + " of 1000"); } @Test public void allowMostWords() throws Exception { // Check that majority (> 95%) of actual words are allowed. Results could potentially // vary if the words file is different on other machines. Path file = Paths.get("/usr/share/dict/words"); if (Files.isRegularFile(file)) { List<String> words = Files.readAllLines(file, StandardCharsets.UTF_8); int suppressed = 0; int total = words.size(); for (String word : words) { String path = "/" + word; if ("_-".equals(sanitize(path))) { ++suppressed; } } Assertions.assertTrue( suppressed < 0.05 * total, "suppressed " + suppressed + " of " + total); } } @Test public void restrictsLength() { // Alternate consonants and vowels to avoid consonant run check String pattern = "abecidofug"; StringBuilder path = new StringBuilder().append('/'); for (int i = 0; i < 100; ++i) { path.append(pattern); } Assertions.assertEquals("_-", PathSanitizer.sanitize(path.toString())); path.append("/foo/bar/baz"); Assertions.assertEquals("_-_foo_bar_baz", PathSanitizer.sanitize(path.toString())); } }
5,616
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/http/HttpRequestBuilderTest.java
/* * Copyright 2014-2020 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.spectator.ipc.http; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.URI; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; public class HttpRequestBuilderTest { private static final HttpResponse OK = new HttpResponse(200, Collections.emptyMap()); private static final HttpResponse REDIRECT = new HttpResponse(302, Collections.emptyMap()); private static final HttpResponse BAD_REQUEST = new HttpResponse(400, Collections.emptyMap()); private static final HttpResponse THROTTLED = new HttpResponse(429, Collections.emptyMap()); private static final HttpResponse SERVER_ERROR = new HttpResponse(500, Collections.emptyMap()); private static final HttpResponse UNAVAILABLE = new HttpResponse(503, Collections.emptyMap()); @Test public void ok() throws IOException { HttpResponse res = new TestRequestBuilder(() -> OK).send(); Assertions.assertEquals(200, res.status()); } @Test public void retry0() throws Exception { Assertions.assertThrows(IOException.class, () -> new TestRequestBuilder(() -> { throw new IOException("failed"); }).send()); } @Test public void retry2() { AtomicInteger attempts = new AtomicInteger(); boolean failed = false; try { HttpResponseSupplier supplier = () -> { attempts.incrementAndGet(); throw new IOException("failed"); }; new TestRequestBuilder(supplier).withRetries(2).send(); } catch (IOException e) { failed = true; } Assertions.assertEquals(3, attempts.get()); Assertions.assertTrue(failed); } private void retryException(String method, IOException ex, int expectedAttempts) { AtomicInteger attempts = new AtomicInteger(); boolean failed = false; try { HttpResponseSupplier supplier = () -> { attempts.incrementAndGet(); throw ex; }; new TestRequestBuilder(supplier).withMethod(method).withRetries(2).send(); } catch (IOException e) { failed = true; } Assertions.assertEquals(expectedAttempts, attempts.get()); Assertions.assertTrue(failed); } @Test public void retryConnectExceptionPost() { retryException("POST", new ConnectException("failed"), 3); } @Test public void retryConnectTimeoutPost() { retryException("POST", new SocketTimeoutException("connect timed out"), 3); } @Test public void retryReadTimeoutGet() { retryException("GET", new SocketTimeoutException("read timed out"), 3); } @Test public void retryReadTimeoutPost() { retryException("POST", new SocketTimeoutException("read timed out"), 1); } private void retryStatus( String method, HttpResponse expectedRes, int expectedAttempts) throws IOException { AtomicInteger attempts = new AtomicInteger(); HttpResponseSupplier supplier = () -> { attempts.incrementAndGet(); return expectedRes; }; HttpResponse res = new TestRequestBuilder(supplier) .withMethod(method) .withInitialRetryDelay(0L) .withRetries(2) .send(); Assertions.assertEquals(expectedAttempts, attempts.get()); Assertions.assertEquals(expectedRes.status(), res.status()); } @Test public void retry2xx() throws IOException { retryStatus("GET", OK, 1); } @Test public void retry3xx() throws IOException { retryStatus("GET", REDIRECT, 1); } @Test public void retry4xx() throws IOException { retryStatus("GET", BAD_REQUEST, 1); } @Test public void retry5xx() throws IOException { retryStatus("GET", SERVER_ERROR, 3); } @Test public void retry429() throws IOException { retryStatus("GET", THROTTLED, 3); } @Test public void retry503() throws IOException { retryStatus("GET", UNAVAILABLE, 3); } @Test public void retryPost2xx() throws IOException { retryStatus("POST", OK, 1); } @Test public void retryPost3xx() throws IOException { retryStatus("POST", REDIRECT, 1); } @Test public void retryPost4xx() throws IOException { retryStatus("POST", BAD_REQUEST, 1); } @Test public void retryPost5xx() throws IOException { retryStatus("POST", SERVER_ERROR, 1); } @Test public void retryPost429() throws IOException { retryStatus("POST", THROTTLED, 3); } @Test public void retryPost503() throws IOException { retryStatus("POST", UNAVAILABLE, 3); } @Test public void hostnameVerificationWithHTTP() throws IOException { Assertions.assertThrows(IllegalStateException.class, () -> new TestRequestBuilder(() -> OK).allowAllHosts()); } @Test public void hostnameVerificationWithHTTPS() throws IOException { HttpResponse res = new TestRequestBuilder(() -> OK, URI.create("https://foo.com/path")) .allowAllHosts() .send(); Assertions.assertEquals(200, res.status()); } private static class TestRequestBuilder extends HttpRequestBuilder { private HttpResponseSupplier supplier; TestRequestBuilder(HttpResponseSupplier supplier) { this(supplier, URI.create("/path")); } TestRequestBuilder(HttpResponseSupplier supplier, URI uri) { super(HttpClient.DEFAULT_LOGGER, uri); this.supplier = supplier; } @Override protected HttpResponse sendImpl() throws IOException { return supplier.get(); } } private interface HttpResponseSupplier { HttpResponse get() throws IOException; } }
5,617
0
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/test/java/com/netflix/spectator/ipc/http/RetryPolicyTest.java
/* * Copyright 2014-2020 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.spectator.ipc.http; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.net.SocketTimeoutException; public class RetryPolicyTest { @Test public void safeIsConnectNullMessage() { RetryPolicy policy = RetryPolicy.SAFE; Assertions.assertTrue(policy.shouldRetry("GET", new SocketTimeoutException(null))); } @Test public void safeConnectMessageCapitalization() { RetryPolicy policy = RetryPolicy.SAFE; Assertions.assertTrue(policy.shouldRetry("GET", new SocketTimeoutException("connect"))); Assertions.assertTrue(policy.shouldRetry("GET", new SocketTimeoutException("Connect"))); Assertions.assertTrue(policy.shouldRetry("GET", new SocketTimeoutException("failed to connect"))); Assertions.assertTrue(policy.shouldRetry("GET", new SocketTimeoutException("Connection timed out"))); } }
5,618
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcTagKey.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; /** * Standard dimensions used for IPC metrics. */ public enum IpcTagKey { /** The library that produced the metric. */ owner("owner"), /** * Indicates whether or not the request was successful. See {@link IpcResult} * for permitted values. */ result("ipc.result"), /** * Dimension indicating a high level status for the request. These values are the same * for all implementations to make it easier to query across services. See {@link IpcStatus} * for permitted values. */ status("ipc.status"), /** * Optional dimension indicating a more detailed status. The values for this are * implementation specific. For example with HTTP, the status code would be a likely * value used here. */ statusDetail("ipc.status.detail"), /** * Dimension indicating a high level cause for the request failure. These groups * are the same for all implementations to make it easier to query across all * services and client implementations. See {@link IpcErrorGroup} for permitted * values. * * @deprecated Use {@link #status} instead. This value is scheduled for removal * in a future release. */ @Deprecated errorGroup("ipc.error.group"), /** * Implementation specific error code. * * @deprecated Use {@link #statusDetail} instead. This value is scheduled for removal * in a future release. */ @Deprecated errorReason("ipc.error.reason"), /** * Indicates the attempt number for the request. */ attempt("ipc.attempt"), /** * Indicates if this is the final attempt for the request. For example, if the client * is configured to allow 1 retry, then the second attempt would be final. Acceptable * values are {@code true} and {@code false}. */ attemptFinal("ipc.attempt.final"), /** * Identifier for the client instance making the request. This is typically the name used * to see the associated configuration settings for the client. */ id("id"), /** * Eureka VIP used to select the server. If there are multiple vips in the list, then it * should be the first vip that caused the server to get selected. */ vip("ipc.vip"), /** * The server side endpoint that is being requested. This should be a bounded set that * will have a small cardinality. <b>Do not pass in the unsanitized path value for a * URI.</b> */ endpoint("ipc.endpoint"), /** * Protocol used for the request. For example {@code http_1} or {@code http_2}. */ protocol("ipc.protocol"), /** * Region where the client is located. * * @deprecated Not included in the spec. Common IPC tags should bias towards consistency * across integrations and only use tags that are part of the spec. This value is scheduled * for removal in a future release. */ @Deprecated clientRegion("ipc.client.region"), /** * Availability zone where the client is located. * * @deprecated Not included in the spec. Common IPC tags should bias towards consistency * across integrations and only use tags that are part of the spec. This value is scheduled * for removal in a future release. */ @Deprecated clientZone("ipc.client.zone"), /** * Application that is running the client. */ clientApp("ipc.client.app"), /** * Cluster that is running the client. */ clientCluster("ipc.client.cluster"), /** * Server group that is running the client. */ clientAsg("ipc.client.asg"), /** * Region where the server is located. * * @deprecated Not included in the spec. Common IPC tags should bias towards consistency * across integrations and only use tags that are part of the spec. This value is scheduled * for removal in a future release. */ @Deprecated serverRegion("ipc.server.region"), /** * Availability zone where the server is located. * * @deprecated Not included in the spec. Common IPC tags should bias towards consistency * across integrations and only use tags that are part of the spec. This value is scheduled * for removal in a future release. */ @Deprecated serverZone("ipc.server.zone"), /** * Application name for the server. */ serverApp("ipc.server.app"), /** * Cluster name for the server. */ serverCluster("ipc.server.cluster"), /** * Server group name for the server. */ serverAsg("ipc.server.asg"), /** * Instance id for the server. <b>Do not use this unless you know it will not * cause a metrics explosion. If there is any doubt, then do not enable it.</b> * * @deprecated Not included in the spec. Common IPC tags should bias towards consistency * across integrations and only use tags that are part of the spec. This value is scheduled * for removal in a future release. */ @Deprecated serverNode("ipc.server.node"), /** * The port number connected to on the server. * * @deprecated Not included in the spec. Common IPC tags should bias towards consistency * across integrations and only use tags that are part of the spec. This value is scheduled * for removal in a future release. */ @Deprecated serverPort("ipc.server.port"), /** * Indicates that an artificial failure was injected into the request processing for testing * purposes. The outcome of that failure will be reflected in the other error tags. * See {@link IpcFailureInjection} for permitted values. */ failureInjected("ipc.failure.injected"), /** * HTTP status code. In most cases it is preferred to use {@link #statusDetail} instead. * This tag key is optionally used to include the HTTP status code when the status detail * is overridden with application specific values. */ httpStatus("http.status"), /** * HTTP method such as GET, PUT, or POST. */ httpMethod("http.method"); private final String key; /** Create a new instance. */ IpcTagKey(String key) { this.key = key; } /** String to use as the tag key. */ public String key() { return key; } /** Create a new tag with the specified value and this key. */ public Tag tag(String value) { return new BasicTag(key, value); } }
5,619
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcAttemptFinal.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.Tag; /** * Dimension indicating if it is the final attempt for a given request. * * @see IpcTagKey#attempt * @see IpcTagKey#attemptFinal */ public enum IpcAttemptFinal implements Tag { /** It is the final attempt for the request. */ is_true("true"), /** Further attempts will be made if there is a retriable failure. */ is_false("false"); private final String value; /** Create a new instance. */ IpcAttemptFinal(String value) { this.value = value; } @Override public String key() { return IpcTagKey.attemptFinal.key(); } @Override public String value() { return value; } /** * Get the enum value associated with the boolean. */ public static IpcAttemptFinal forValue(boolean v) { return v ? is_true : is_false; } }
5,620
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcErrorGroup.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.Tag; /** * Dimension indicating a high level cause for the request failure. These groups * are the same for all implementations to make it easier to query across all * services and client implementations. An implementation specific failure can be * specified with {@link IpcTagKey#errorReason}. * * @deprecated Use {@link IpcStatus} instead. This class is scheduled for removal * in a future release. */ @Deprecated public enum IpcErrorGroup implements Tag { /** No error. */ none, /** Catch all category for errors that do not fit a more specific group. */ general, /** * Any failure to initialize the connection. Examples include connection timeout, * host not found exception, and SSL handshake errors. */ connection_init, /** * The request timed out while waiting for a response to arrive or be generated. */ read_timeout, /** * The client cancelled the request before the server generated a response. */ cancelled, /** * The client is being throttled due to an excessive number of requests. */ client_throttled, /** * The client is being throttled due to a problem on the server side. */ server_throttled, /** * There was an error due to problems with the client request, e.g., HTTP status 400. */ client_error, /** * There was an error due to problems on the server side, e.g., HTTP status 500. */ server_error; @Override public String key() { return IpcTagKey.errorGroup.key(); } @Override public String value() { return name(); } }
5,621
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcResult.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.Tag; /** * Dimension indicating the overall result of the request. * * @see IpcTagKey#result */ public enum IpcResult implements Tag { /** Indicates the request was successful. */ success, /** Indicates the request failed. */ failure; @Override public String key() { return IpcTagKey.result.key(); } @Override public String value() { return name(); } }
5,622
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcFailureInjection.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.Tag; /** * Dimension indicating whether failure was injected into a request. * * @see IpcTagKey#failureInjected */ public enum IpcFailureInjection implements Tag { /** Indicates there was no failure injected into the request. */ none, /** Indicates there was a fault injected into the request. */ failure, /** Indicates there was latency into the request. */ delay, /** Indicates there was both a latency and an fault injected into the request. */ delay_and_failure; @Override public String key() { return IpcTagKey.failureInjected.key(); } @Override public String value() { return name(); } }
5,623
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcProtocol.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.Tag; /** * Dimension indicating the protocol. This enum includes the standard values for well * established protocols that should agree across all implementations. */ public enum IpcProtocol implements Tag { /** HTTP 1.x. */ http_1, /** HTTP 2.x. */ http_2, /** gRPC protocol. */ grpc; @Override public String key() { return IpcTagKey.protocol.key(); } @Override public String value() { return name(); } }
5,624
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcAttempt.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.Tag; /** * Dimension indicating the retry attempt. * * @see IpcTagKey#attempt * @see IpcTagKey#attemptFinal */ public enum IpcAttempt implements Tag { /** Initial request. */ initial, /** Second attempt or the first retry. */ second, /** A third or later attempt. */ third_up, /** The attempt number cannot be determined. */ unknown; @Override public String key() { return IpcTagKey.attempt.key(); } @Override public String value() { return name(); } /** * Get the appropriate tag value based on the current attempt number. The attempt number * should start at 1 for the initial request and increment for each retry. * * @param attempt * Current attempt number. * @return * Tag value corresponding to the attempt number. */ public static IpcAttempt forAttemptNumber(int attempt) { IpcAttempt t; switch (attempt) { case 1: t = initial; break; case 2: t = second; break; default: t = (attempt >= 3) ? third_up : unknown; break; } return t; } }
5,625
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java
/* * Copyright 2014-2023 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.spectator.ipc; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import com.netflix.spectator.api.histogram.PercentileTimer; import com.netflix.spectator.ipc.http.PathSanitizer; import org.slf4j.MDC; import org.slf4j.Marker; import org.slf4j.event.Level; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; /** * Builder used to fill in and submit a log entry associated with an IPC request. */ @SuppressWarnings({"PMD.ExcessiveClassLength", "PMD.AvoidStringBufferField"}) public final class IpcLogEntry { private final Clock clock; private Registry registry; private IpcLogger logger; private Level level; private Marker marker; private long startNanos; private long startTime; private long latency; private String owner; private IpcResult result; private String protocol; private IpcStatus status; private String statusDetail; private Throwable exception; private IpcAttempt attempt; private IpcAttemptFinal attemptFinal; private String vip; private String endpoint; private String clientRegion; private String clientZone; private String clientApp; private String clientCluster; private String clientAsg; private String clientNode; private String serverRegion; private String serverZone; private String serverApp; private String serverCluster; private String serverAsg; private String serverNode; private String httpMethod; private int httpStatus; private String uri; private String path; private long requestContentLength = -1L; private long responseContentLength = -1L; private final List<Header> requestHeaders = new ArrayList<>(); private final List<Header> responseHeaders = new ArrayList<>(); private String remoteAddress; private int remotePort; private boolean disableMetrics; private final Map<String, String> additionalTags = new HashMap<>(); private final StringBuilder builder = new StringBuilder(); private Id inflightId; /** Create a new instance. */ IpcLogEntry(Clock clock) { this.clock = clock; reset(); } /** Set the registry to use for recording metrics. */ IpcLogEntry withRegistry(Registry registry) { this.registry = registry; return this; } /** * Set the logger instance to use for tracking state such as the number of inflight * requests. */ IpcLogEntry withLogger(IpcLogger logger) { this.logger = logger; return this; } /** * Set the marker indicating whether it is a client or server request. */ IpcLogEntry withMarker(Marker marker) { this.marker = marker; return this; } /** * Set the log level to use when sending to SLF4j. The default level is DEBUG. For * high volume use-cases it is recommended to set the level to TRACE to avoid excessive * logging. */ public IpcLogEntry withLogLevel(Level level) { this.level = level; return this; } /** * Set the latency for the request. This will typically be set automatically using * {@link #markStart()} and {@link #markEnd()}. Use this method if the latency value * is provided by the implementation rather than measured using this entry. */ public IpcLogEntry withLatency(long latency, TimeUnit unit) { this.latency = unit.toNanos(latency); return this; } /** * Record the starting time for the request and update the number of inflight requests. * This should be called just before starting the execution of the request. As soon as * the request completes it is recommended to call {@link #markEnd()}. */ public IpcLogEntry markStart() { if (registry != null && !disableMetrics) { inflightId = getInflightId(); int n = logger.inflightRequests(inflightId).incrementAndGet(); registry.distributionSummary(inflightId).record(n); } startTime = clock.wallTime(); startNanos = clock.monotonicTime(); return this; } /** * Record the latency for the request based on the completion time. This will be * implicitly called when the request is logged, but it is advisable to call as soon * as the response is received to minimize the amount of response processing that is * counted as part of the request latency. */ public IpcLogEntry markEnd() { return withLatency(clock.monotonicTime() - startNanos, TimeUnit.NANOSECONDS); } /** * Set the library that produced the metric. */ public IpcLogEntry withOwner(String owner) { this.owner = owner; return this; } /** * Set the protocol used for this request. See {@link IpcProtocol} for more information. */ public IpcLogEntry withProtocol(IpcProtocol protocol) { return withProtocol(protocol.value()); } /** * Set the protocol used for this request. See {@link IpcProtocol} for more information. */ public IpcLogEntry withProtocol(String protocol) { this.protocol = protocol; return this; } /** * Set the result for this request. See {@link IpcResult} for more information. */ public IpcLogEntry withResult(IpcResult result) { this.result = result; return this; } /** * Set the high level status for the request. See {@link IpcStatus} for more * information. */ public IpcLogEntry withStatus(IpcStatus status) { this.status = status; return this; } /** * Set the detailed implementation specific status for the request. In most cases it * is preferable to use {@link #withException(Throwable)} or {@link #withHttpStatus(int)} * instead of calling this directly. */ public IpcLogEntry withStatusDetail(String statusDetail) { this.statusDetail = statusDetail; return this; } /** * Set the high level cause for a request failure. See {@link IpcErrorGroup} for more * information. * * @deprecated Use {@link #withStatus(IpcStatus)} instead. This method is scheduled for * removal in a future release. */ @Deprecated public IpcLogEntry withErrorGroup(IpcErrorGroup errorGroup) { return this; } /** * Set the implementation specific reason for the request failure. In most cases it * is preferable to use {@link #withException(Throwable)} or {@link #withHttpStatus(int)} * instead of calling this directly. * * @deprecated Use {@link #withStatusDetail(String)} instead. This method is scheduled for * removal in a future release. */ @Deprecated public IpcLogEntry withErrorReason(String errorReason) { return this; } /** * Set the exception that was thrown while trying to execute the request. This will be * logged and can be used to fill in the error reason. */ public IpcLogEntry withException(Throwable exception) { this.exception = exception; if (statusDetail == null) { statusDetail = exception.getClass().getSimpleName(); } if (status == null) { status = IpcStatus.forException(exception); } return this; } /** * Set the attempt number for the request. */ public IpcLogEntry withAttempt(IpcAttempt attempt) { this.attempt = attempt; return this; } /** * Set the attempt number for the request. */ public IpcLogEntry withAttempt(int attempt) { return withAttempt(IpcAttempt.forAttemptNumber(attempt)); } /** * Set whether or not this is the final attempt for the request. */ public IpcLogEntry withAttemptFinal(boolean isFinal) { this.attemptFinal = IpcAttemptFinal.forValue(isFinal); return this; } /** * Set the vip that was used to determine which server to contact. This will only be * present if using client side load balancing via Eureka. */ public IpcLogEntry withVip(String vip) { this.vip = vip; return this; } /** * Set the endpoint for this request. */ public IpcLogEntry withEndpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Set the client region for the request. In the case of the server side this will be * automatically filled in if the {@link NetflixHeader#Zone} is specified on the client * request. */ public IpcLogEntry withClientRegion(String region) { this.clientRegion = region; return this; } /** * Set the client zone for the request. In the case of the server side this will be * automatically filled in if the {@link NetflixHeader#Zone} is specified on the client * request. */ public IpcLogEntry withClientZone(String zone) { this.clientZone = zone; if (clientRegion == null) { clientRegion = extractRegionFromZone(zone); } return this; } /** * Set the client app for the request. In the case of the server side this will be * automatically filled in if the {@link NetflixHeader#ASG} is specified on the client * request. The ASG value must follow the * <a href="https://github.com/Netflix/iep/tree/master/iep-nflxenv#server-group-settings"> * Frigga server group</a> naming conventions. */ public IpcLogEntry withClientApp(String app) { this.clientApp = app; return this; } /** * Set the client cluster for the request. In the case of the server side this will be * automatically filled in if the {@link NetflixHeader#ASG} is specified on the client * request. The ASG value must follow the * <a href="https://github.com/Netflix/iep/tree/master/iep-nflxenv#server-group-settings"> * Frigga server group</a> naming conventions. */ public IpcLogEntry withClientCluster(String cluster) { this.clientCluster = cluster; return this; } /** * Set the client ASG for the request. In the case of the server side this will be * automatically filled in if the {@link NetflixHeader#ASG} is specified on the client * request. The ASG value must follow the * <a href="https://github.com/Netflix/iep/tree/master/iep-nflxenv#server-group-settings"> * Frigga server group</a> naming conventions. */ public IpcLogEntry withClientAsg(String asg) { this.clientAsg = asg; if (clientApp == null || clientCluster == null) { ServerGroup group = ServerGroup.parse(asg); clientApp = (clientApp == null) ? group.app() : clientApp; clientCluster = (clientCluster == null) ? group.cluster() : clientCluster; } return this; } /** * Set the client node for the request. This will be used for access logging only and will * not be present on metrics. The server will log this value if the {@link NetflixHeader#Node} * header is present on the client request. */ public IpcLogEntry withClientNode(String node) { this.clientNode = node; return this; } /** * Set the server region for the request. In the case of the client side this will be * automatically filled in if the {@link NetflixHeader#Zone} is specified on the server * response. */ public IpcLogEntry withServerRegion(String region) { this.serverRegion = region; return this; } /** * Set the server zone for the request. In the case of the client side this will be * automatically filled in if the {@link NetflixHeader#Zone} is specified on the server * response. */ public IpcLogEntry withServerZone(String zone) { this.serverZone = zone; if (serverRegion == null) { serverRegion = extractRegionFromZone(zone); } return this; } /** * Set the server app for the request. In the case of the client side this will be * automatically filled in if the {@link NetflixHeader#ASG} is specified on the server * response. The ASG value must follow the * <a href="https://github.com/Netflix/iep/tree/master/iep-nflxenv#server-group-settings"> * Frigga server group</a> naming conventions. */ public IpcLogEntry withServerApp(String app) { this.serverApp = app; return this; } /** * Set the server cluster for the request. In the case of the client side this will be * automatically filled in if the {@link NetflixHeader#ASG} is specified on the server * response. The ASG value must follow the * <a href="https://github.com/Netflix/iep/tree/master/iep-nflxenv#server-group-settings"> * Frigga server group</a> naming conventions. */ public IpcLogEntry withServerCluster(String cluster) { this.serverCluster = cluster; return this; } /** * Set the server ASG for the request. In the case of the client side this will be * automatically filled in if the {@link NetflixHeader#ASG} is specified on the server * response. The ASG value must follow the * <a href="https://github.com/Netflix/iep/tree/master/iep-nflxenv#server-group-settings"> * Frigga server group</a> naming conventions. */ public IpcLogEntry withServerAsg(String asg) { this.serverAsg = asg; if (serverApp == null || serverCluster == null) { ServerGroup group = ServerGroup.parse(asg); serverApp = (serverApp == null) ? group.app() : serverApp; serverCluster = (serverCluster == null) ? group.cluster() : serverCluster; } return this; } /** * Set the server node for the request. This will be used for access logging only and will * not be present on metrics. The client will log this value if the {@link NetflixHeader#Node} * header is present on the server response. */ public IpcLogEntry withServerNode(String node) { this.serverNode = node; return this; } /** * Set the HTTP method used for this request. */ public IpcLogEntry withHttpMethod(String method) { this.httpMethod = method; return this; } /** * Set the HTTP status code for this request. If not already set, then this will set an * appropriate value for {@link #withStatus(IpcStatus)} and {@link #withResult(IpcResult)} * based on the status code. */ public IpcLogEntry withHttpStatus(int httpStatus) { if (httpStatus >= 100 && httpStatus < 600) { this.httpStatus = httpStatus; if (status == null) { status = IpcStatus.forHttpStatus(httpStatus); } if (result == null) { result = status.result(); } } else { // If an invalid HTTP status code is passed in this.httpStatus = -1; } return this; } /** * Set the URI and path for the request. */ public IpcLogEntry withUri(String uri, String path) { this.uri = uri; this.path = path; return this; } /** * Set the URI and path for the request. The path will get extracted from the URI. If the * URI is non-strict and cannot be parsed with the java URI class, then use * {@link #withUri(String, String)} instead. */ public IpcLogEntry withUri(URI uri) { return withUri(uri.toString(), uri.getPath()); } /** * Set the length for the request entity if it is known at the time of logging. If the size * is not known, e.g. a chunked HTTP entity, then a negative value can be used and the length * will be ignored. */ public IpcLogEntry withRequestContentLength(long length) { this.requestContentLength = length; return this; } /** * Set the length for the request entity if it is known at the time of logging. If the size * is not known, e.g. a chunked HTTP entity, then a negative value can be used and the length * will be ignored. */ public IpcLogEntry withResponseContentLength(long length) { this.responseContentLength = length; return this; } /** * Add a request header value. For special headers in {@link NetflixHeader} it will * automatically fill in the more specific fields based on the header values. */ public IpcLogEntry addRequestHeader(String name, String value) { if (clientAsg == null && name.equalsIgnoreCase(NetflixHeader.ASG.headerName())) { withClientAsg(value); } else if (clientZone == null && name.equalsIgnoreCase(NetflixHeader.Zone.headerName())) { withClientZone(value); } else if (clientNode == null && name.equalsIgnoreCase(NetflixHeader.Node.headerName())) { withClientNode(value); } else if (vip == null && name.equalsIgnoreCase(NetflixHeader.Vip.headerName())) { withVip(value); } else if (name.equalsIgnoreCase(NetflixHeader.IngressCommonIpcMetrics.headerName())) { disableMetrics(); } this.requestHeaders.add(new Header(name, value)); return this; } /** * Add a response header value. For special headers in {@link NetflixHeader} it will * automatically fill in the more specific fields based on the header values. */ public IpcLogEntry addResponseHeader(String name, String value) { if (serverAsg == null && name.equalsIgnoreCase(NetflixHeader.ASG.headerName())) { withServerAsg(value); } else if (serverZone == null && name.equalsIgnoreCase(NetflixHeader.Zone.headerName())) { withServerZone(value); } else if (serverNode == null && name.equalsIgnoreCase(NetflixHeader.Node.headerName())) { withServerNode(value); } else if (endpoint == null && name.equalsIgnoreCase(NetflixHeader.Endpoint.headerName())) { withEndpoint(value); } this.responseHeaders.add(new Header(name, value)); return this; } /** * Set the remote address for the request. */ public IpcLogEntry withRemoteAddress(String remoteAddress) { this.remoteAddress = remoteAddress; return this; } /** * Set the remote port for the request. */ public IpcLogEntry withRemotePort(int remotePort) { this.remotePort = remotePort; return this; } /** * Add custom tags to the request metrics. Note, IPC metrics already have many tags and it * is not recommended for users to tack on additional context. In particular, any additional * tags should have a <b>guaranteed</b> low cardinality. If additional tagging causes these * metrics to exceed limits, then you may lose all visibility into requests. */ public IpcLogEntry addTag(Tag tag) { this.additionalTags.put(tag.key(), tag.value()); return this; } /** * Add custom tags to the request metrics. Note, IPC metrics already have many tags and it * is not recommended for users to tack on additional context. In particular, any additional * tags should have a <b>guaranteed</b> low cardinality. If additional tagging causes these * metrics to exceed limits, then you may lose all visibility into requests. */ public IpcLogEntry addTag(String k, String v) { this.additionalTags.put(k, v); return this; } /** * Disable the metrics. The log will still get written, but none of the metrics will get * updated. */ public IpcLogEntry disableMetrics() { this.disableMetrics = true; return this; } private void putTag(Map<String, String> tags, Tag tag) { if (tag != null) { tags.put(tag.key(), tag.value()); } } private void putTag(Map<String, String> tags, String k, String v) { if (notNullOrEmpty(v)) { String value = logger.limiterForKey(k).apply(v); tags.put(k, value); } } private IpcResult getResult() { if (result == null) { result = status == null ? IpcResult.success : status.result(); } return result; } private IpcStatus getStatus() { if (status == null) { status = (result == IpcResult.success) ? IpcStatus.success : IpcStatus.unexpected_error; } return status; } private IpcAttempt getAttempt() { if (attempt == null) { attempt = IpcAttempt.forAttemptNumber(1); } return attempt; } private IpcAttemptFinal getAttemptFinal() { if (attemptFinal == null) { attemptFinal = IpcAttemptFinal.is_true; } return attemptFinal; } private String getEndpoint() { return (endpoint == null) ? (path == null || httpStatus == 404) ? "unknown" : PathSanitizer.sanitize(path) : endpoint; } private boolean isClient() { return marker != null && "ipc-client".equals(marker.getName()); } private Id createCallId(String name) { Map<String, String> tags = new HashMap<>(); // User specified custom tags, add individually to ensure that limiter is applied // to the values for (Map.Entry<String, String> entry : additionalTags.entrySet()) { putTag(tags, entry.getKey(), entry.getValue()); } // Required for both client and server putTag(tags, IpcTagKey.owner.key(), owner); putTag(tags, getResult()); putTag(tags, getStatus()); if (isClient()) { // Required for client, should be null on server putTag(tags, getAttempt()); putTag(tags, getAttemptFinal()); // Optional for client putTag(tags, IpcTagKey.serverApp.key(), serverApp); putTag(tags, IpcTagKey.serverCluster.key(), serverCluster); putTag(tags, IpcTagKey.serverAsg.key(), serverAsg); } else { // Optional for server putTag(tags, IpcTagKey.clientApp.key(), clientApp); putTag(tags, IpcTagKey.clientCluster.key(), clientCluster); putTag(tags, IpcTagKey.clientAsg.key(), clientAsg); } // Optional for both client and server putTag(tags, IpcTagKey.endpoint.key(), getEndpoint()); putTag(tags, IpcTagKey.vip.key(), vip); putTag(tags, IpcTagKey.protocol.key(), protocol); putTag(tags, IpcTagKey.statusDetail.key(), statusDetail); putTag(tags, IpcTagKey.httpStatus.key(), Integer.toString(httpStatus)); putTag(tags, IpcTagKey.httpMethod.key(), httpMethod); return registry.createId(name, tags); } private Id getInflightId() { if (inflightId == null) { Map<String, String> tags = new HashMap<>(); // Required for both client and server putTag(tags, IpcTagKey.owner.key(), owner); // Optional for both client and server putTag(tags, IpcTagKey.vip.key(), vip); String name = isClient() ? IpcMetric.clientInflight.metricName() : IpcMetric.serverInflight.metricName(); inflightId = registry.createId(name, tags); } return inflightId; } private void recordClientMetrics() { if (disableMetrics) { return; } Id clientCall = createCallId(IpcMetric.clientCall.metricName()); PercentileTimer.builder(registry) .withId(clientCall) .build() .record(getLatency(), TimeUnit.NANOSECONDS); if (responseContentLength >= 0L) { Id clientCallSizeInbound = registry.createId( IpcMetric.clientCallSizeInbound.metricName(), clientCall.tags()); registry.distributionSummary(clientCallSizeInbound).record(responseContentLength); } if (requestContentLength >= 0L) { Id clientCallSizeOutbound = registry.createId( IpcMetric.clientCallSizeOutbound.metricName(), clientCall.tags()); registry.distributionSummary(clientCallSizeOutbound).record(requestContentLength); } } private void recordServerMetrics() { if (disableMetrics) { return; } Id serverCall = createCallId(IpcMetric.serverCall.metricName()); PercentileTimer.builder(registry) .withId(serverCall) .build() .record(getLatency(), TimeUnit.NANOSECONDS); if (requestContentLength >= 0L) { Id serverCallSizeInbound = registry.createId( IpcMetric.serverCallSizeInbound.metricName(), serverCall.tags()); registry.distributionSummary(serverCallSizeInbound).record(requestContentLength); } if (responseContentLength >= 0L) { Id serverCallSizeOutbound = registry.createId( IpcMetric.serverCallSizeOutbound.metricName(), serverCall.tags()); registry.distributionSummary(serverCallSizeOutbound).record(responseContentLength); } } /** * Log the request. This entry will potentially be reused after this is called. The user * should not attempt any further modifications to the state of this entry. */ public void log() { if (logger != null) { if (registry != null) { if (isClient()) { recordClientMetrics(); } else { recordServerMetrics(); } } if (inflightId != null) { logger.inflightRequests(inflightId).decrementAndGet(); } logger.log(this); } else { reset(); } } /** Return the log level set for this log entry. */ Level getLevel() { return level; } /** Return the marker set for this log entry. */ Marker getMarker() { return marker; } /** Return true if the request is successful and the entry can be reused. */ boolean isSuccessful() { return result == IpcResult.success; } private String extractRegionFromZone(String zone) { int n = zone.length(); if (n < 4) { return null; } else { char c = zone.charAt(n - 2); if (Character.isDigit(c) && zone.charAt(n - 3) == '-') { // AWS zones have a pattern of `${region}[a-f]`, for example: `us-east-1a` return zone.substring(0, n - 1); } else if (c == '-') { // GCE zones have a pattern of `${region}-[a-f]`, for example: `us-east1-c` // https://cloud.google.com/compute/docs/regions-zones/ return zone.substring(0, n - 2); } else { // Pattern doesn't look familiar return null; } } } private long getLatency() { if (startNanos >= 0L && latency < 0L) { // If latency was not explicitly set but the start time was, then compute the // time since the start. The field is updated so subsequent calls will return // a consistent value for the latency. latency = clock.monotonicTime() - startNanos; } return latency; } private String getExceptionClass() { return (exception == null) ? null : exception.getClass().getName(); } private String getExceptionMessage() { return (exception == null) ? null : exception.getMessage(); } private void putInMDC(String key, String value) { if (value != null && !value.isEmpty()) { MDC.put(key, value); } } private void putInMDC(Tag tag) { if (tag != null) { putInMDC(tag.key(), tag.value()); } } void populateMDC() { putInMDC("marker", marker.getName()); putInMDC("uri", uri); putInMDC("path", path); putInMDC(IpcTagKey.endpoint.key(), endpoint); putInMDC(IpcTagKey.owner.key(), owner); putInMDC(IpcTagKey.protocol.key(), protocol); putInMDC(IpcTagKey.vip.key(), vip); putInMDC("ipc.client.region", clientRegion); putInMDC("ipc.client.zone", clientZone); putInMDC("ipc.client.node", clientNode); putInMDC(IpcTagKey.clientApp.key(), clientApp); putInMDC(IpcTagKey.clientCluster.key(), clientCluster); putInMDC(IpcTagKey.clientAsg.key(), clientAsg); putInMDC("ipc.server.region", serverRegion); putInMDC("ipc.server.zone", serverZone); putInMDC("ipc.server.node", serverNode); putInMDC(IpcTagKey.serverApp.key(), serverApp); putInMDC(IpcTagKey.serverCluster.key(), serverCluster); putInMDC(IpcTagKey.serverAsg.key(), serverAsg); putInMDC("ipc.remote.address", remoteAddress); putInMDC("ipc.remote.port", Integer.toString(remotePort)); putInMDC(attempt); putInMDC(attemptFinal); putInMDC(result); putInMDC(status); putInMDC(IpcTagKey.statusDetail.key(), statusDetail); putInMDC(IpcTagKey.httpMethod.key(), httpMethod); putInMDC(IpcTagKey.httpStatus.key(), Integer.toString(httpStatus)); } @Override public String toString() { return new JsonStringBuilder(builder) .startObject() .addField("owner", owner) .addField("start", startTime) .addField("latency", getLatency() / 1e9) .addField("protocol", protocol) .addField("uri", uri) .addField("path", path) .addField("endpoint", getEndpoint()) .addField("vip", vip) .addField("clientRegion", clientRegion) .addField("clientZone", clientZone) .addField("clientApp", clientApp) .addField("clientCluster", clientCluster) .addField("clientAsg", clientAsg) .addField("clientNode", clientNode) .addField("serverRegion", serverRegion) .addField("serverZone", serverZone) .addField("serverApp", serverApp) .addField("serverCluster", serverCluster) .addField("serverAsg", serverAsg) .addField("serverNode", serverNode) .addField("remoteAddress", remoteAddress) .addField("remotePort", remotePort) .addField("attempt", attempt) .addField("attemptFinal", attemptFinal) .addField("result", result) .addField("status", status) .addField("statusDetail", statusDetail) .addField("exceptionClass", getExceptionClass()) .addField("exceptionMessage", getExceptionMessage()) .addField("httpMethod", httpMethod) .addField("httpStatus", httpStatus) .addField("requestContentLength", requestContentLength) .addField("responseContentLength", responseContentLength) .addField("requestHeaders", requestHeaders) .addField("responseHeaders", responseHeaders) .addField("additionalTags", additionalTags) .endObject() .toString(); } /** * Resets this log entry so the instance can be reused. This helps to reduce allocations. */ void reset() { logger = null; level = Level.DEBUG; marker = null; startTime = -1L; startNanos = -1L; latency = -1L; owner = null; result = null; protocol = null; status = null; statusDetail = null; exception = null; attempt = null; attemptFinal = null; vip = null; endpoint = null; clientRegion = null; clientZone = null; clientApp = null; clientCluster = null; clientAsg = null; clientNode = null; serverRegion = null; serverZone = null; serverApp = null; serverCluster = null; serverAsg = null; serverNode = null; httpMethod = null; httpStatus = -1; uri = null; path = null; requestContentLength = -1L; responseContentLength = -1L; requestHeaders.clear(); responseHeaders.clear(); remoteAddress = null; remotePort = -1; additionalTags.clear(); builder.delete(0, builder.length()); inflightId = null; } /** * Partially reset this log entry so it can be used for another request attempt. Any * attributes that can change for a given request need to be cleared. */ void resetForRetry() { startTime = -1L; startNanos = -1L; latency = -1L; result = null; status = null; statusDetail = null; exception = null; attempt = null; attemptFinal = null; vip = null; serverRegion = null; serverZone = null; serverApp = null; serverCluster = null; serverAsg = null; serverNode = null; httpStatus = -1; requestContentLength = -1L; responseContentLength = -1L; requestHeaders.clear(); responseHeaders.clear(); remoteAddress = null; remotePort = -1; builder.delete(0, builder.length()); inflightId = null; } /** * Apply a mapping function to this log entry. This method is mostly used to allow the * final mapping to be applied to the entry without breaking the operator chaining. */ public <T> T convert(Function<IpcLogEntry, T> mapper) { return mapper.apply(this); } private static boolean notNullOrEmpty(String s) { return s != null && !s.isEmpty(); } private static class Header { private final String name; private final String value; Header(String name, String value) { this.name = name; this.value = value; } String name() { return name; } String value() { return value; } } private static class JsonStringBuilder { private final StringBuilder builder; private boolean firstEntry = true; JsonStringBuilder(StringBuilder builder) { this.builder = builder; } JsonStringBuilder startObject() { builder.append('{'); return this; } JsonStringBuilder endObject() { builder.append('}'); return this; } private void addSep() { if (firstEntry) { firstEntry = false; } else { builder.append(','); } } JsonStringBuilder addField(String k, String v) { if (notNullOrEmpty(v)) { addSep(); builder.append('"'); escapeAndAppend(builder, k); builder.append("\":\""); escapeAndAppend(builder, v); builder.append('"'); } return this; } JsonStringBuilder addField(String k, Tag tag) { if (tag != null) { addField(k, tag.value()); } return this; } JsonStringBuilder addField(String k, int v) { if (v >= 0) { addSep(); builder.append('"'); escapeAndAppend(builder, k); builder.append("\":").append(v); } return this; } JsonStringBuilder addField(String k, long v) { if (v >= 0L) { addSep(); builder.append('"'); escapeAndAppend(builder, k); builder.append("\":").append(v); } return this; } JsonStringBuilder addField(String k, double v) { if (v >= 0.0) { addSep(); builder.append('"'); escapeAndAppend(builder, k); builder.append("\":").append(v); } return this; } JsonStringBuilder addField(String k, List<Header> headers) { if (!headers.isEmpty()) { addSep(); builder.append('"'); escapeAndAppend(builder, k); builder.append("\":["); boolean first = true; for (Header h : headers) { if (first) { first = false; } else { builder.append(','); } builder.append("{\"name\":\""); escapeAndAppend(builder, h.name()); builder.append("\",\"value\":\""); escapeAndAppend(builder, h.value()); builder.append("\"}"); } builder.append(']'); } return this; } JsonStringBuilder addField(String k, Map<String, String> tags) { if (!tags.isEmpty()) { addSep(); builder.append('"'); escapeAndAppend(builder, k); builder.append("\":{"); boolean first = true; for (Map.Entry<String, String> entry : tags.entrySet()) { if (first) { first = false; } else { builder.append(','); } builder.append('"'); escapeAndAppend(builder, entry.getKey()); builder.append("\":\""); escapeAndAppend(builder, entry.getValue()); builder.append('"'); } builder.append('}'); } return this; } private void escapeAndAppend(StringBuilder builder, String str) { int length = str.length(); for (int i = 0; i < length; ++i) { char c = str.charAt(i); switch (c) { case '"': builder.append("\\\""); break; case '\\': builder.append("\\\\"); break; case '\b': builder.append("\\b"); break; case '\f': builder.append("\\f"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; case '\t': builder.append("\\t"); break; default: // Ignore control characters that are not matched explicitly above if (!Character.isISOControl(c)) { builder.append(c); } break; } } } @Override public String toString() { return builder.toString(); } } }
5,626
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/NetflixHeader.java
/* * Copyright 2014-2023 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.spectator.ipc; /** * Headers in use at Netflix to relay information between the client and the server. This * information provides additional context for logs and is used to tag the IPC metrics * consistently between the client and the server. */ public enum NetflixHeader { /** * Server group name for the client or the server. It should follow the naming conventions * expected by Frigga. See {@link ServerGroup} for more information. */ ASG("Netflix-ASG"), /** * Availability zone of the client or server instance. */ Zone("Netflix-Zone"), /** * Instance id of the client or server. */ Node("Netflix-Node"), /** * Route or route handler for a given path. It should have a fixed cardinality. For HTTP * this would need to come from the server so there is agreement and the client will report * the same value. */ Endpoint("Netflix-Endpoint"), /** * VIP that was used to lookup instances for a service when using a client side load balancer. * This should be set on the client request to the vip used for the lookup. In the case of NIWS, * that would be the VIP used for the DeploymentContextBasedVipAddresses. If multiple VIPs are * used, then the first VIP that caused a given server instance to be selected should be used. * * <p>For server side load balancers the VIP header should be omitted. */ Vip("Netflix-Vip"), /** * Used to indicate that common IPC metrics are provided by a proxy and do not need to be * reported locally. Reporting in multiple places can lead to confusing duplication. */ IngressCommonIpcMetrics("Netflix-Ingress-Common-IPC-Metrics"); private final String headerName; NetflixHeader(String headerName) { this.headerName = headerName; } /** Return the fully qualified header name. */ public String headerName() { return headerName; } }
5,627
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/ServerGroup.java
/* * Copyright 2014-2019 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.spectator.ipc; import java.util.Objects; /** * Helper for parsing Netflix server group names that follow the Frigga conventions. For * more information see the IEP documentation for * <a href="https://github.com/Netflix/iep/tree/master/iep-nflxenv#server-group-settings">server groups</a>. * * <p>Frigga is not used for the actual parsing as it is quite inefficient. See the * ServerGroupParsing benchmark for a comparison.</p> */ public class ServerGroup { /** * Create a new instance of a server group object by parsing the group name. */ public static ServerGroup parse(String asg) { int d1 = asg.indexOf('-'); int d2 = asg.indexOf('-', d1 + 1); int dN = asg.lastIndexOf('-'); if (dN < 0 || !isSequence(asg, dN)) { dN = asg.length(); } return new ServerGroup(asg, d1, d2, dN); } /** * Check if the last portion of the server group name is a version sequence (v\d+). */ private static boolean isSequence(String asg, int dN) { int length = asg.length(); if (length - dN < 5 || length - dN > 8 || asg.charAt(dN + 1) != 'v') { // Sequence must be 3 to 6 digits and start with v // https://github.com/Netflix/frigga/pull/32 return false; } for (int i = dN + 2; i < length; ++i) { if (!Character.isDigit(asg.charAt(i))) { return false; } } return true; } private static String substr(String str, int s, int e) { return (s >= e) ? null : str.substring(s, e); } private final String asg; private final int d1; private final int d2; private final int dN; /** * Create a new instance of the server group. * * @param asg * Raw group name received from the user. * @param d1 * Position of the first dash or -1 if there are no dashes in the input. * @param d2 * Position of the second dash or -1 if there is not a second dash in the input. * @param dN * Position indicating the end of the cluster name. For a server group with a * sequence this will be the final dash. If the sequence is not present, then * it will be the end of the string. */ ServerGroup(String asg, int d1, int d2, int dN) { this.asg = asg; this.d1 = d1; this.d2 = d2; this.dN = dN; } /** Return the application for the server group or null if invalid. */ public String app() { if (d1 < 0) { // No stack or detail is present return asg.length() > 0 ? asg : null; } else if (d1 == 0) { // Application portion is empty return null; } else { // Application is present along with stack, detail, or sequence return substr(asg, 0, d1); } } /** Return the cluster name for the server group or null if invalid. */ public String cluster() { if (d1 == 0) { // Application portion is empty return null; } else { return (dN > 0 && dN == asg.length()) ? asg() : substr(asg, 0, dN); } } /** Return the server group name or null if invalid. */ public String asg() { return (d1 != 0 && dN > 0) ? asg : null; } /** If the server group has a stack, then return the stack name. Otherwise return null. */ public String stack() { if (d1 <= 0) { // No stack, detail or sequence is present return null; } else if (d2 < 0) { // Stack, but no detail is present return substr(asg, d1 + 1, dN); } else { // Stack and at least one of detail or sequence is present return substr(asg, d1 + 1, d2); } } /** If the server group has a detail, then return the detail name. Otherwise return null. */ public String detail() { return (d1 != 0 && d2 > 0) ? substr(asg, d2 + 1, dN) : null; } private boolean isDigit(char c) { return c >= '0' && c <= '9'; } private boolean nonZeroDigit(char c) { return c >= '1' && c <= '9'; } private String shardN(char n) { if (d1 != 0 && d2 > 0) { int matchStart = -1; int matchEnd = -1; // Shards must be the first part of the detail, loop until we find a gap int s = d2; while (s != -1) { int nextDash = asg.indexOf('-', s + 2); int e = (nextDash == -1) ? dN : nextDash; if (e <= s + 3 || asg.charAt(s + 1) != 'x' || !nonZeroDigit(asg.charAt(s + 2))) { // Shard value must be at least 1 character // The number prefix must match break; } else if (asg.charAt(s + 2) == n && !isDigit(asg.charAt(s + 3))) { // If the first character of the value is numeric, means shard number is too high // skip and move to the next. Otherwise we have a match. Since the match could get // overwritten later, record positions for now and keep checking. matchStart = s + 3; matchEnd = e; } s = nextDash; } return (matchStart > 0) ? substr(asg, matchStart, matchEnd) : null; } else { // No detail means no shards return null; } } /** If the detail contains a shard with id 1, then return it. Otherwise return null. */ public String shard1() { return shardN('1'); } /** If the detail contains a shard with id 2, then return it. Otherwise return null. */ public String shard2() { return shardN('2'); } /** If the server group has a sequence number, then return it. Otherwise return null. */ public String sequence() { return dN == asg.length() ? null : substr(asg, dN + 1, asg.length()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ServerGroup that = (ServerGroup) o; return d1 == that.d1 && d2 == that.d2 && dN == that.dN && Objects.equals(asg, that.asg); } @Override public int hashCode() { return Objects.hash(asg, d1, d2, dN); } @Override public String toString() { return "ServerGroup(" + asg + ", " + d1 + ", " + d2 + ", " + dN + ")"; } }
5,628
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/NetflixHeaders.java
/* * Copyright 2014-2019 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.spectator.ipc; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; /** * Helper for extracting Netflix header values from the environment variables available * on the base ami. For more information see: * * https://github.com/Netflix/iep/tree/master/iep-nflxenv */ public final class NetflixHeaders { private NetflixHeaders() { } private static final String[] NETFLIX_ASG = { "NETFLIX_AUTO_SCALE_GROUP", "CLOUD_AUTO_SCALE_GROUP" }; private static final String[] NETFLIX_NODE = { "TITUS_TASK_ID", "EC2_INSTANCE_ID" }; private static final String[] NETFLIX_ZONE = { "EC2_AVAILABILITY_ZONE" }; private static void addHeader( Map<String, String> headers, Function<String, String> env, NetflixHeader header, String[] names) { for (String name : names) { String value = env.apply(name); if (value != null && !value.isEmpty()) { headers.put(header.headerName(), value); break; } } } /** * Extract common Netflix headers from the specified function for retrieving the value * of an environment variable. */ public static Map<String, String> extractFrom(Function<String, String> env) { Map<String, String> headers = new LinkedHashMap<>(); addHeader(headers, env, NetflixHeader.ASG, NETFLIX_ASG); addHeader(headers, env, NetflixHeader.Node, NETFLIX_NODE); addHeader(headers, env, NetflixHeader.Zone, NETFLIX_ZONE); return headers; } /** * Extract common Netflix headers from environment variables on the system. */ public static Map<String, String> extractFromEnvironment() { return extractFrom(System::getenv); } }
5,629
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcMetric.java
/* * Copyright 2014-2019 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.spectator.ipc; 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.Registry; import com.netflix.spectator.api.Tag; import com.netflix.spectator.api.Timer; import com.netflix.spectator.api.Utils; import java.util.Arrays; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; /** * IPC metric names and associated metadata. */ public enum IpcMetric { /** * Timer recording the number and latency of outbound requests. */ clientCall( "ipc.client.call", EnumSet.of( IpcTagKey.attempt, IpcTagKey.attemptFinal, IpcTagKey.owner, IpcTagKey.result, IpcTagKey.status ), EnumSet.of( IpcTagKey.endpoint, IpcTagKey.failureInjected, IpcTagKey.httpMethod, IpcTagKey.httpStatus, IpcTagKey.id, IpcTagKey.protocol, IpcTagKey.serverApp, IpcTagKey.serverCluster, IpcTagKey.serverAsg, IpcTagKey.statusDetail, IpcTagKey.vip ) ), /** * Timer recording the number and latency of inbound requests. */ serverCall( "ipc.server.call", EnumSet.of( IpcTagKey.owner, IpcTagKey.result, IpcTagKey.status ), EnumSet.of( IpcTagKey.endpoint, IpcTagKey.clientApp, IpcTagKey.clientCluster, IpcTagKey.clientAsg, IpcTagKey.failureInjected, IpcTagKey.httpMethod, IpcTagKey.httpStatus, IpcTagKey.id, IpcTagKey.protocol, IpcTagKey.statusDetail, IpcTagKey.vip ) ), /** * Distribution summary recording the size of the entity for client responses. */ clientCallSizeInbound( "ipc.client.call.size.inbound", EnumSet.of( IpcTagKey.attempt, IpcTagKey.attemptFinal, IpcTagKey.owner, IpcTagKey.result, IpcTagKey.status ), EnumSet.of( IpcTagKey.endpoint, IpcTagKey.failureInjected, IpcTagKey.httpMethod, IpcTagKey.httpStatus, IpcTagKey.id, IpcTagKey.protocol, IpcTagKey.serverApp, IpcTagKey.serverCluster, IpcTagKey.serverAsg, IpcTagKey.statusDetail, IpcTagKey.vip ) ), /** * Distribution summary recording the size of the entity for client requests. */ clientCallSizeOutbound( "ipc.client.call.size.outbound", EnumSet.of( IpcTagKey.attempt, IpcTagKey.attemptFinal, IpcTagKey.owner, IpcTagKey.result, IpcTagKey.status ), EnumSet.of( IpcTagKey.endpoint, IpcTagKey.failureInjected, IpcTagKey.httpMethod, IpcTagKey.httpStatus, IpcTagKey.id, IpcTagKey.protocol, IpcTagKey.serverApp, IpcTagKey.serverCluster, IpcTagKey.serverAsg, IpcTagKey.statusDetail, IpcTagKey.vip ) ), /** * Distribution summary recording the size of the entity for server requests. */ serverCallSizeInbound( "ipc.server.call.size.inbound", EnumSet.of( IpcTagKey.owner, IpcTagKey.result, IpcTagKey.status ), EnumSet.of( IpcTagKey.endpoint, IpcTagKey.clientApp, IpcTagKey.clientCluster, IpcTagKey.clientAsg, IpcTagKey.failureInjected, IpcTagKey.httpMethod, IpcTagKey.httpStatus, IpcTagKey.id, IpcTagKey.protocol, IpcTagKey.statusDetail, IpcTagKey.vip ) ), /** * Distribution summary recording the size of the entity for server responses. */ serverCallSizeOutbound( "ipc.server.call.size.outbound", EnumSet.of( IpcTagKey.owner, IpcTagKey.result, IpcTagKey.status ), EnumSet.of( IpcTagKey.endpoint, IpcTagKey.clientApp, IpcTagKey.clientCluster, IpcTagKey.clientAsg, IpcTagKey.failureInjected, IpcTagKey.httpMethod, IpcTagKey.httpStatus, IpcTagKey.id, IpcTagKey.protocol, IpcTagKey.statusDetail, IpcTagKey.vip ) ), /** * Number of outbound requests that are currently in flight. */ clientInflight( "ipc.client.inflight", EnumSet.of( IpcTagKey.owner ), EnumSet.of( IpcTagKey.endpoint, IpcTagKey.id, IpcTagKey.protocol, IpcTagKey.serverApp, IpcTagKey.serverCluster, IpcTagKey.serverAsg, IpcTagKey.vip ) ), /** * Number of inbound requests that are currently in flight. */ serverInflight( "ipc.server.inflight", EnumSet.of( IpcTagKey.owner ), EnumSet.of( IpcTagKey.clientApp, IpcTagKey.clientCluster, IpcTagKey.clientAsg, IpcTagKey.endpoint, IpcTagKey.id, IpcTagKey.protocol, IpcTagKey.vip ) ); private final String metricName; private final EnumSet<IpcTagKey> requiredDimensions; private final EnumSet<IpcTagKey> optionalDimensions; /** Create a new instance. */ IpcMetric( String metricName, EnumSet<IpcTagKey> requiredDimensions, EnumSet<IpcTagKey> optionalDimensions) { this.metricName = metricName; this.requiredDimensions = requiredDimensions; this.optionalDimensions = optionalDimensions; } /** Returns the metric name to use in the meter id. */ public String metricName() { return metricName; } /** Returns the set of dimensions that are required for this metrics. */ public EnumSet<IpcTagKey> requiredDimensions() { return requiredDimensions; } private static final Class<?>[] METER_TYPES = { Counter.class, Timer.class, DistributionSummary.class, Gauge.class }; private static final SortedSet<String> ATTEMPT_FINAL_VALUES = new TreeSet<>(); static { ATTEMPT_FINAL_VALUES.add(Boolean.TRUE.toString()); ATTEMPT_FINAL_VALUES.add(Boolean.FALSE.toString()); } private static void assertTrue(boolean condition, String description, Object... args) { if (!condition) { throw new IllegalArgumentException(String.format(description, args)); } } private static String getName(Class<?> cls) { for (Class<?> c : METER_TYPES) { if (c.isAssignableFrom(cls)) { return c.getSimpleName(); } } return cls.getSimpleName(); } private static boolean isPercentile(Id id) { final String stat = Utils.getTagValue(id, "statistic"); return "percentile".equals(stat); } private static void validateIpcMeter( Registry registry, IpcMetric metric, Class<?> type, boolean strict) { final String name = metric.metricName(); registry.stream() .filter(m -> name.equals(m.id().name()) && !isPercentile(m.id())) .forEach(m -> { assertTrue(type.isAssignableFrom(m.getClass()), "[%s] has the wrong type, expected %s but found %s", m.id(), type.getSimpleName(), getName(m.getClass())); metric.validate(m.id(), strict); }); } /** * Validate all of the common IPC metrics contained within the specified registry. * * @param registry * Registry to query for IPC metrics. */ public static void validate(Registry registry) { validate(registry, false); } /** * Validate all of the common IPC metrics contained within the specified registry. * * @param registry * Registry to query for IPC metrics. * @param strict * If true, then checks if the ids are strictly compliant with the spec without any * additions. Otherwise, just checks for minimal compliance. Integrations should be * strictly compliant to ensure consistency for users. */ public static void validate(Registry registry, boolean strict) { validateIpcMeter(registry, IpcMetric.clientCall, Timer.class, strict); validateIpcMeter(registry, IpcMetric.serverCall, Timer.class, strict); validateIpcMeter(registry, IpcMetric.clientCallSizeInbound, DistributionSummary.class, strict); validateIpcMeter(registry, IpcMetric.clientCallSizeOutbound, DistributionSummary.class, strict); validateIpcMeter(registry, IpcMetric.serverCallSizeInbound, DistributionSummary.class, strict); validateIpcMeter(registry, IpcMetric.serverCallSizeOutbound, DistributionSummary.class, strict); validateIpcMeter(registry, IpcMetric.clientInflight, DistributionSummary.class, strict); validateIpcMeter(registry, IpcMetric.serverInflight, DistributionSummary.class, strict); } @SuppressWarnings("PMD.PreserveStackTrace") private <T extends Enum<T>> void validateValues(Id id, String key, Class<T> cls) { String value = Utils.getTagValue(id, key); if (value != null) { try { Enum.valueOf(cls, value); } catch (Exception e) { String values = Arrays.stream(cls.getEnumConstants()) .map(Enum::name) .collect(Collectors.joining(", ")); throw new IllegalArgumentException(String.format( "[%s] invalid value for dimension %s, acceptable values are (%s)", id, key, values)); } } } private void validateValues(Id id, String key, SortedSet<String> allowedValues) { String value = Utils.getTagValue(id, key); if (value != null && !allowedValues.contains(value)) { String values = allowedValues.stream() .collect(Collectors.joining(", ")); throw new IllegalArgumentException(String.format( "[%s] invalid value for dimension %s, acceptable values are (%s)", id, key, values)); } } /** * Validate that the specified id has the correct tagging for this IPC metric. * * @param id * Meter identifier to validate. */ public void validate(Id id) { validate(id, false); } /** * Validate that the specified id has the correct tagging for this IPC metric. * * @param id * Meter identifier to validate. * @param strict * If true, then checks if the ids are strictly compliant with the spec without any * additions. Otherwise, just checks for minimal compliance. Integrations should be * strictly compliant to ensure consistency for users. */ public void validate(Id id, boolean strict) { assertTrue(metricName.equals(id.name()), "%s != %s", metricName, id.name()); // Check that required dimensions are present EnumSet<IpcTagKey> dimensions = requiredDimensions.clone(); dimensions.forEach(k -> { String value = Utils.getTagValue(id, k.key()); assertTrue(value != null, "[%s] is missing required dimension %s", id, k.key()); }); // Check the values are correct for enum keys validateValues(id, IpcTagKey.attemptFinal.key(), ATTEMPT_FINAL_VALUES); validateValues(id, IpcTagKey.attempt.key(), IpcAttempt.class); validateValues(id, IpcTagKey.result.key(), IpcResult.class); validateValues(id, IpcTagKey.status.key(), IpcStatus.class); validateValues(id, IpcTagKey.failureInjected.key(), IpcFailureInjection.class); // Check that result and status are consistent String status = Utils.getTagValue(id, IpcTagKey.status.key()); if (status != null) { IpcResult expected = IpcStatus.valueOf(status).result(); IpcResult actual = IpcResult.valueOf(Utils.getTagValue(id, IpcTagKey.result.key())); assertTrue(actual == expected, "[%s] result is inconsistent with status", id); } // Check that only allowed dimensions are used on the id if (strict) { Set<String> allowedDimensions = new HashSet<>(); allowedDimensions.add("statistic"); allowedDimensions.add("percentile"); requiredDimensions.forEach(d -> allowedDimensions.add(d.key())); optionalDimensions.forEach(d -> allowedDimensions.add(d.key())); for (Tag tag : id.tags()) { assertTrue(allowedDimensions.contains(tag.key()), "[%s] has unspecified dimension %s", id, tag.key()); } } } }
5,630
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogger.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Utils; import com.netflix.spectator.api.patterns.CardinalityLimiters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import org.slf4j.event.Level; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Predicate; /** * Logger for recording IPC metrics and providing a basic access log. A single logger instance * should be reused for all requests in a given context because it maintains the state such as * number of inflight requests. */ public class IpcLogger { private static final Marker CLIENT = MarkerFactory.getMarker("ipc-client"); private static final Marker SERVER = MarkerFactory.getMarker("ipc-server"); private final Registry registry; private final Clock clock; private final Logger logger; private final ConcurrentHashMap<Id, AtomicInteger> inflightRequests; private final ConcurrentHashMap<String, Function<String, String>> limiters; private final LinkedBlockingQueue<IpcLogEntry> entries; /** * Create a new instance. Allows the clock to be explicitly set for unit tests. */ IpcLogger(Registry registry, Clock clock, Logger logger) { this.registry = registry; this.clock = clock; this.logger = logger; this.inflightRequests = new ConcurrentHashMap<>(); this.limiters = new ConcurrentHashMap<>(); this.entries = new LinkedBlockingQueue<>(1000); } /** Create a new instance. */ public IpcLogger(Registry registry, Logger logger) { this(registry, registry.clock(), logger); } /** Create a new instance. */ public IpcLogger(Registry registry) { this(registry, registry.clock(), LoggerFactory.getLogger(IpcLogger.class)); } /** Return the number of inflight requests associated with the given id. */ AtomicInteger inflightRequests(Id id) { return Utils.computeIfAbsent(inflightRequests, id, i -> new AtomicInteger()); } /** * Return the cardinality limiter for a given key. This is used to protect the metrics * backend from a metrics explosion if some dimensions have a high cardinality. */ Function<String, String> limiterForKey(String key) { return Utils.computeIfAbsent(limiters, key, k -> CardinalityLimiters.rollup(25)); } private IpcLogEntry newEntry() { IpcLogEntry entry = entries.poll(); return (entry == null) ? new IpcLogEntry(clock) : entry; } /** * Create a new log entry for client requests. Log entry objects may be reused to minimize * the number of allocations so they should only be modified in the context of a single * request. */ public IpcLogEntry createClientEntry() { return newEntry() .withRegistry(registry) .withLogger(this) .withMarker(CLIENT); } /** * Create a new log entry for server requests. Log entry objects may be reused to minimize * the number of allocations so they should only be modified in the context of a single * request. */ public IpcLogEntry createServerEntry() { return newEntry() .withRegistry(registry) .withLogger(this) .withMarker(SERVER); } /** * Called by the entry to log the request. */ void log(IpcLogEntry entry) { Level level = entry.getLevel(); Predicate<Marker> enabled; BiConsumer<Marker, String> log; switch (level) { case TRACE: enabled = logger::isTraceEnabled; log = logger::trace; break; case DEBUG: enabled = logger::isDebugEnabled; log = logger::debug; break; case INFO: enabled = logger::isInfoEnabled; log = logger::info; break; case WARN: enabled = logger::isWarnEnabled; log = logger::warn; break; case ERROR: enabled = logger::isErrorEnabled; log = logger::error; break; default: enabled = logger::isDebugEnabled; log = logger::debug; break; } if (enabled.test(entry.getMarker())) { entry.populateMDC(); log.accept(entry.getMarker(), entry.toString()); MDC.clear(); } // For successful responses we can reuse the entry to avoid additional allocations. Failed // requests might have retries so we just reset the response portion to avoid incorrectly // having state bleed through from one request to the next. if (entry.isSuccessful()) { entry.reset(); entries.offer(entry); } else { entry.resetForRetry(); } } }
5,631
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcStatus.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.spectator.api.Tag; import javax.net.ssl.SSLException; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.concurrent.TimeoutException; /** * Dimension indicating the high level status for the request. * * @see IpcTagKey#status */ public enum IpcStatus implements Tag { /** * The request was successfully processed and responded to, as far as the client or server * know. */ success, /** * There was a problem with the clients' request causing it not to be fulfilled. */ bad_request, /** * The client or server encountered an unexpected error processing the request. */ unexpected_error, /** * There was an error with the underlying network connection either during establishment * or while in use. */ connection_error, /** * There were no servers available to process the request. */ unavailable, /** * The request was rejected due to the client or server considering the server to be * above capacity. */ throttled, /** * The request could not or would not be complete within the configured threshold (either * on client or server). */ timeout, /** * The client cancelled the request before it was completed. */ cancelled, /** * The request was denied access for authentication or authorization reasons. */ access_denied, /** * The request had an application level error. Application specific diagnostics would * need to be used to determine the issue. */ application_error; @Override public String key() { return IpcTagKey.status.key(); } @Override public String value() { return name(); } /** * Return the corresponding IPC result. */ public IpcResult result() { return this == success ? IpcResult.success : IpcResult.failure; } /** * Maps HTTP status codes to the appropriate status. Note, this method follows the historical * convention in Netflix where services would use the service unavailable, * <a href="https://tools.ietf.org/html/rfc7231#section-6.6.4">503</a> status code, to indicate * throttling. To get behavior inline with the RFCs use {@link #forHttpStatusStandard(int)} * instead. * * @param httpStatus * HTTP status for the request. * @return * Status value corresponding to the HTTP status code. */ public static IpcStatus forHttpStatus(int httpStatus) { return forHttpStatusStandard(httpStatus == 503 ? 429 : httpStatus); } /** * Maps HTTP status codes to the appropriate status based on the standard RFC definitions. * In particular, <a href="https://tools.ietf.org/html/rfc7231#section-6.6.4">503</a> maps * to {@link #unavailable} and <a href="https://tools.ietf.org/html/rfc6585#section-4">429</a> * maps to {@link #throttled}. * * @param httpStatus * HTTP status for the request. * @return * Status value corresponding to the HTTP status code. */ public static IpcStatus forHttpStatusStandard(int httpStatus) { IpcStatus status; switch (httpStatus) { case 200: status = success; break; // OK case 401: status = access_denied; break; // Unauthorized case 402: status = access_denied; break; // Payment Required case 403: status = access_denied; break; // Forbidden case 404: status = success; break; // Not Found case 405: status = bad_request; break; // Method Not Allowed case 406: status = bad_request; break; // Not Acceptable case 407: status = access_denied; break; // Proxy Authentication Required case 408: status = timeout; break; // Request Timeout case 429: status = throttled; break; // Too Many Requests case 503: status = unavailable; break; // Unavailable case 511: status = access_denied; break; // Network Authentication Required default: if (httpStatus < 100) { // Shouldn't get here, but since the input value isn't validated it is a possibility status = unexpected_error; } else if (httpStatus < 400) { // All 1xx, 2xx, and 3xx unless otherwise specified will be marked as a success status = success; } else if (httpStatus < 500) { // All 4xx unless otherwise specified will be marked as a bad request status = bad_request; } else { // Anything else is unexpected status = unexpected_error; } break; } return status; } /** * Maps common exceptions from the JDK to the appropriate status. * * @param t * Exception to map to a status. * @return * Status corresponding to the passed in exception. */ public static IpcStatus forException(Throwable t) { IpcStatus status; if (t instanceof SSLException) { status = access_denied; } else if (t instanceof SocketTimeoutException || t instanceof TimeoutException) { status = timeout; } else if (t instanceof IOException) { status = connection_error; } else if (t instanceof IllegalArgumentException || t instanceof IllegalStateException) { status = bad_request; } else { status = unexpected_error; } return status; } }
5,632
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/http/RetryPolicy.java
/* * Copyright 2014-2020 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.spectator.ipc.http; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.util.Locale; /** * Policy that determines if a request can be retried based on the response. */ public interface RetryPolicy { /** Retry all requests. */ RetryPolicy ALL = new RetryPolicy() { @Override public boolean shouldRetry(String method, Throwable t) { return true; } @Override public boolean shouldRetry(String method, HttpResponse response) { return true; } }; /** * Retry operations that are known to be safe without impacting the results and the operation * will potentially have a different response. */ RetryPolicy SAFE = new RetryPolicy() { /** * For modifications, only retries on connection exceptions. Others such as a read timeout * may have already started doing some work. Reads can be retried on all exceptions. */ @Override public boolean shouldRetry(String method, Throwable t) { return isConnectException(t) || allowedMethod(method); } private boolean isConnectException(Throwable t) { return t instanceof ConnectException || isConnectTimeout(t); } /** * This is fragile and based on the message, but not sure of a better way. Expecting: * <pre> * java.net.SocketTimeoutException: connect timed out * </pre> */ private boolean isConnectTimeout(Throwable t) { return t instanceof SocketTimeoutException && t.getMessage() != null && t.getMessage().toLowerCase(Locale.US).contains("connect"); } @Override public boolean shouldRetry(String method, HttpResponse response) { return isThrottled(response.status()) || isAllowed(method, response); } private boolean isThrottled(int status) { return status == 429 || status == 503; } private boolean isAllowed(String method, HttpResponse response) { return allowedMethod(method) && allowedStatus(response.status()); } private boolean allowedMethod(String method) { return "GET".equals(method) || "HEAD".equals(method); } private boolean allowedStatus(int status) { return status >= 500; } }; /** * Returns true if the request should be retried when it fails with an exception. */ boolean shouldRetry(String method, Throwable t); /** * Returns true if the request should be retried when it fails with an HTTP error code. */ boolean shouldRetry(String method, HttpResponse response); }
5,633
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/http/PathSanitizer.java
/* * Copyright 2014-2023 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.spectator.ipc.http; import com.netflix.spectator.impl.AsciiSet; import java.util.Collections; import java.util.Set; /** * Helper for sanitizing a URL path for including as the {@code ipc.endpoint} value. Makes * a best effort to try and remove segments that tend to be variable like numbers, UUIDs, * etc. */ public final class PathSanitizer { private static final int MAX_LENGTH = 120; private static final AsciiSet ALPHA_CHARS = AsciiSet.fromPattern("a-zA-Z"); private static final AsciiSet DIGITS = AsciiSet.fromPattern("0-9"); private static final AsciiSet CONSONANTS = AsciiSet.fromPattern("b-df-hj-np-tv-xzB-DF-HJ-NP-TV-XZ"); private PathSanitizer() { } /** Returns a sanitized path string for use as an endpoint tag value. */ public static String sanitize(String path) { return sanitize(path, Collections.emptySet()); } /** * Returns a sanitized path string for use as an endpoint tag value. * * @param path * Path from a URI that should be sanitized. * @param allowed * Set of allowed segment strings. This can be used to override the default rules for * a set of known good values. * @return * Sanitized path that can be used as an endpoint tag value. */ public static String sanitize(String path, Set<String> allowed) { String tmp = sanitizeSegments(removeParameters(path), allowed); return tmp.isEmpty() ? "none" : tmp; } private static String removeParameters(String path) { return removeParameters(removeParameters(path, '?'), ';'); } private static String removeParameters(String path, char c) { int i = path.indexOf(c); return i >= 0 ? path.substring(0, i) : path; } private static String sanitizeSegments(String path, Set<String> allowed) { StringBuilder builder = new StringBuilder(); int length = path.length(); int pos = path.isEmpty() || path.charAt(0) != '/' ? 0 : 1; int segmentsAdded = 0; while (pos < length && segmentsAdded < 5) { String segment; int e = path.indexOf('/', pos); if (e > 0) { segment = path.substring(pos, e); pos = e + 1; } else { segment = path.substring(pos); pos = length; } if (!segment.isEmpty()) { if (shouldSuppressSegment(segment, allowed)) appendIfSpaceAvailable(builder, "-"); else appendIfSpaceAvailable(builder, segment); ++segmentsAdded; } } return builder.toString(); } private static boolean shouldSuppressSegment(String segment, Set<String> allowed) { // GraphQL is a common endpoint, but hits the consonants check to detect strings // that are likely to be random. Special case it for now. if ("graphql".equals(segment) || allowed.contains(segment)) { return false; } final int maxSequentialConsonants = 4; int sequentialConsonants = 0; boolean version = false; boolean allAlpha = true; int n = segment.length(); for (int i = 0; i < n; ++i) { char c = segment.charAt(i); if (CONSONANTS.contains(c)) { ++sequentialConsonants; if (sequentialConsonants >= maxSequentialConsonants) return true; } else { sequentialConsonants = 0; } if (i == 0 && c == 'v') { version = true; } else { version &= DIGITS.contains(c); } allAlpha &= ALPHA_CHARS.contains(c); if (!version && !allAlpha) { return true; } } return !version && n == 2; } private static void appendIfSpaceAvailable(StringBuilder builder, String segment) { int spaceRemaining = MAX_LENGTH - builder.length() - 1; if (segment.length() < spaceRemaining) { builder.append('_').append(segment); } else if (spaceRemaining >= 2) { builder.append("_-"); } } }
5,634
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/http/HttpClient.java
/* * Copyright 2014-2019 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.spectator.ipc.http; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Spectator; import com.netflix.spectator.ipc.IpcLogger; import org.slf4j.LoggerFactory; import java.net.URI; /** * Simple blocking http client using {@link IpcLogger} and {@link java.net.HttpURLConnection}. * This can be used as an example of the logging or for light use-cases where it is more desirable * not to have dependencies on a more robust HTTP library. Usage: * * <pre> * HttpClient client = HttpClient.DEFAULT_CLIENT; * HttpResponse response = client.get(URI.create("http://example.com")).send(); * </pre> * * For testing an alternative client implementation can be used to customize the * send. For example to create a client that will always fail: * * <pre> * HttpClient client = (n, u) -> new HttpRequestBuilder(n, u) { * {@literal @}Override protected HttpResponse sendImpl() throws IOException { * throw new ConnectException("could not connect to " + u.getHost()); * } * }; * </pre> */ public interface HttpClient { /** * Default {@link IpcLogger} instance. It will report metrics to * {@link Spectator#globalRegistry()}. */ IpcLogger DEFAULT_LOGGER = new IpcLogger( Spectator.globalRegistry(), LoggerFactory.getLogger(HttpClient.class)); /** * Default client instance that can be used in static contexts where it is not * possible to inject the {@link IpcLogger} instance. It will use {@link #DEFAULT_LOGGER}. */ HttpClient DEFAULT_CLIENT = create(DEFAULT_LOGGER); /** * Create a new client instance. * * @param registry * Registry to use for reporting metrics. * @return * Client instance based on {@link java.net.HttpURLConnection}. */ static HttpClient create(Registry registry) { return create(new IpcLogger(registry, LoggerFactory.getLogger(HttpClient.class))); } /** * Create a new client instance. * * @param logger * Logger instance for recording metrics and providing an access log. * @return * Client instance based on {@link java.net.HttpURLConnection}. */ static HttpClient create(IpcLogger logger) { return uri -> new HttpRequestBuilder(logger, uri); } /** * Create a new request builder. * * @param uri * URI to use for the request. * @return * Builder for creating and executing a request. */ HttpRequestBuilder newRequest(URI uri); /** * Create a new GET request builder. The client name will be selected based * on a prefix of the host name. * * @param uri * URI to use for the request. * @return * Builder for creating and executing a request. */ default HttpRequestBuilder get(URI uri) { return newRequest(uri).withMethod("GET"); } /** * Create a new POST request builder. The client name will be selected based * on a prefix of the host name. * * @param uri * URI to use for the request. * @return * Builder for creating and executing a request. */ default HttpRequestBuilder post(URI uri) { return newRequest(uri).withMethod("POST"); } /** * Create a new PUT request builder. The client name will be selected based * on a prefix of the host name. * * @param uri * URI to use for the request. * @return * Builder for creating and executing a request. */ default HttpRequestBuilder put(URI uri) { return newRequest(uri).withMethod("PUT"); } /** * Create a new DELETE request builder. The client name will be selected based * on a prefix of the host name. * * @param uri * URI to use for the request. * @return * Builder for creating and executing a request. */ default HttpRequestBuilder delete(URI uri) { return newRequest(uri).withMethod("DELETE"); } }
5,635
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/http/HttpRequestBuilder.java
/* * Copyright 2014-2023 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.spectator.ipc.http; import com.netflix.spectator.impl.Preconditions; import com.netflix.spectator.impl.StreamHelper; import com.netflix.spectator.ipc.IpcLogEntry; import com.netflix.spectator.ipc.IpcLogger; import com.netflix.spectator.ipc.NetflixHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.zip.Deflater; /** * Helper for executing simple HTTP client requests using {@link HttpURLConnection} * and logging via {@link com.netflix.spectator.ipc.IpcLogger}. This is mostly used for simple * use-cases where it is undesirable to have additional dependencies on a more robust HTTP * library. */ public class HttpRequestBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestBuilder.class); private static final Map<String, String> NETFLIX_HEADERS = NetflixHeaders.extractFromEnvironment(); private static final StreamHelper STREAM_HELPER = new StreamHelper(); private static final Lock LOCK = new ReentrantLock(); // Should not be used directly, use the method of the same name that will create the // executor if needed on the first access. private static volatile ExecutorService defaultExecutor; private static ThreadFactory newThreadFactory() { return new ThreadFactory() { private final AtomicInteger next = new AtomicInteger(); @Override public Thread newThread(Runnable r) { final String name = "spectator-ipc-" + next.getAndIncrement(); final Thread t = new Thread(r, name); t.setDaemon(true); return t; } }; } private static ExecutorService defaultExecutor() { ExecutorService executor = defaultExecutor; if (executor != null) { return executor; } LOCK.lock(); try { defaultExecutor = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), newThreadFactory()); return defaultExecutor; } finally { LOCK.unlock(); } } private final URI uri; private final IpcLogEntry entry; private String method = "GET"; private Map<String, String> reqHeaders = new LinkedHashMap<>(); private byte[] entity = HttpUtils.EMPTY; private boolean reuseResponseStreams = false; private int connectTimeout = 1000; private int readTimeout = 30000; private RetryPolicy retryPolicy = RetryPolicy.SAFE; private long initialRetryDelay = 1000L; private int numAttempts = 3; private HostnameVerifier hostVerifier = null; private SSLSocketFactory sslFactory = null; /** Create a new instance for the specified URI. */ public HttpRequestBuilder(IpcLogger logger, URI uri) { this.uri = uri; this.entry = logger.createClientEntry() .withOwner("spectator") .withUri(uri) .withHttpMethod(method); this.reqHeaders.putAll(NETFLIX_HEADERS); } /** Set the request method (GET, PUT, POST, DELETE). */ public HttpRequestBuilder withMethod(String m) { this.method = m; entry.withHttpMethod(method); return this; } /** * Add a header to the request. Note the content type will be set automatically * when providing the content payload and should not be set here. If the value * is null, then the header will get ignored. */ public HttpRequestBuilder addHeader(String name, String value) { if (value != null) { reqHeaders.put(name, value); } return this; } /** Add user-agent header. */ public HttpRequestBuilder userAgent(String agent) { return addHeader("User-Agent", agent); } /** Add header to accept {@code application/json} data. */ public HttpRequestBuilder acceptJson() { return addHeader("Accept", "application/json"); } /** Add accept header. */ public HttpRequestBuilder accept(String type) { return addHeader("Accept", type); } /** Add header to accept-encoding of gzip. */ public HttpRequestBuilder acceptGzip() { return acceptEncoding("gzip"); } /** Add accept-encoding header. */ public HttpRequestBuilder acceptEncoding(String enc) { return addHeader("Accept-Encoding", enc); } /** Set the connection timeout for the request in milliseconds. */ public HttpRequestBuilder withConnectTimeout(int timeout) { this.connectTimeout = timeout; return this; } /** Set the read timeout for the request milliseconds. */ public HttpRequestBuilder withReadTimeout(int timeout) { this.readTimeout = timeout; return this; } /** Set the request body as JSON. */ public HttpRequestBuilder withJsonContent(String content) { return withContent("application/json", content); } /** Set the request body. */ public HttpRequestBuilder withContent(String type, String content) { return withContent(type, content.getBytes(StandardCharsets.UTF_8)); } /** Set the request body. */ public HttpRequestBuilder withContent(String type, byte[] content) { addHeader("Content-Type", type); entity = content; return this; } /** * Compress the request body using the default compression level. * The content must have already been set on the builder. */ public HttpRequestBuilder compress() throws IOException { return compress(Deflater.DEFAULT_COMPRESSION); } /** * Compress the request body using the specified compression level. * The content must have already been set on the builder. */ public HttpRequestBuilder compress(int level) throws IOException { addHeader("Content-Encoding", "gzip"); entity = HttpUtils.gzip(entity, level); return this; } /** * Set to true to re-use the byte arrays when consuming the response. This will result * in buffers being maintained that can be reused across requests resulting in fewer * allocations. However, it will increase the steady state memory usage. */ public HttpRequestBuilder reuseResponseBuffers(boolean b) { this.reuseResponseStreams = b; return this; } /** How many times to retry if the intial attempt fails? */ public HttpRequestBuilder withRetries(int n) { Preconditions.checkArg(n >= 0, "number of retries must be >= 0"); this.numAttempts = n + 1; return this; } /** * How long to delay before retrying if the request is throttled. This will get doubled * for each attempt that is throttled. Unit is milliseconds. */ public HttpRequestBuilder withInitialRetryDelay(long delay) { Preconditions.checkArg(delay >= 0L, "initial retry delay must be >= 0"); this.initialRetryDelay = delay; return this; } /** * Policy to determine whether a given failure can be retried. By default * {@link RetryPolicy#SAFE} is used. */ public HttpRequestBuilder retryPolicy(RetryPolicy policy) { this.retryPolicy = policy; return this; } private void requireHttps(String msg) { Preconditions.checkState("https".equals(uri.getScheme()), msg); } /** Sets the policy used to verify hostnames when using HTTPS. */ public HttpRequestBuilder withHostnameVerifier(HostnameVerifier verifier) { requireHttps("hostname verification cannot be used with http, switch to https"); this.hostVerifier = verifier; return this; } /** * Specify that all hosts are allowed. Using this option effectively disables hostname * verification. Use with caution. */ public HttpRequestBuilder allowAllHosts() { return withHostnameVerifier((host, session) -> true); } /** Sets the socket factory to use with HTTPS. */ public HttpRequestBuilder withSSLSocketFactory(SSLSocketFactory factory) { requireHttps("ssl cannot be used with http, use https"); this.sslFactory = factory; return this; } /** * Provides access to the {@link IpcLogEntry} object to make adjustments if needed. For * most common usage the default should be fine. */ public HttpRequestBuilder customizeLogging(Consumer<IpcLogEntry> f) { f.accept(entry); return this; } /** Send the request and log/update metrics for the results. */ @SuppressWarnings("PMD.ExceptionAsFlowControl") public HttpResponse send() throws IOException { HttpResponse response = null; for (int attempt = 1; attempt <= numAttempts; ++attempt) { entry.withAttempt(attempt).withAttemptFinal(attempt == numAttempts); try { response = sendImpl(); int s = response.status(); boolean shouldRetry = retryPolicy.shouldRetry(method, response); if (shouldRetry && (s == 429 || s == 503)) { // Request is getting throttled, exponentially back off // - 429 client sending too many requests // - 503 server unavailable try { long delay = initialRetryDelay << (attempt - 1); LOGGER.debug("request throttled, delaying for {}ms: {} {}", delay, method, uri); Thread.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("request failed " + method + " " + uri, e); } } else if (!shouldRetry) { return response; } } catch (IOException e) { if (attempt == numAttempts || !retryPolicy.shouldRetry(method, e)) { throw e; } else { LOGGER.info("attempt {} of {} failed: {} {}", attempt, numAttempts, method, uri); } } } if (response == null) { // Should not get here throw new IOException("request failed " + method + " " + uri); } return response; } /** * Send the request asynchronously and log/update metrics for the results. The request * will be sent on a background thread pool and will update the future when complete. In * the future it can be changed to use the new HttpClient in Java 11+. */ public CompletableFuture<HttpResponse> sendAsync() { Supplier<HttpResponse> responseSupplier = () -> { try { return send(); } catch (IOException e) { throw new UncheckedIOException(e); } }; return CompletableFuture.supplyAsync(responseSupplier, defaultExecutor()); } private void configureHTTPS(HttpURLConnection http) { if (http instanceof HttpsURLConnection) { HttpsURLConnection https = (HttpsURLConnection) http; if (hostVerifier != null) { https.setHostnameVerifier(hostVerifier); } if (sslFactory != null) { https.setSSLSocketFactory(sslFactory); } } } /** Send the request and log/update metrics for the results. */ protected HttpResponse sendImpl() throws IOException { HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection(); con.setConnectTimeout(connectTimeout); con.setReadTimeout(readTimeout); con.setRequestMethod(method); for (Map.Entry<String, String> h : reqHeaders.entrySet()) { entry.addRequestHeader(h.getKey(), h.getValue()); con.setRequestProperty(h.getKey(), h.getValue()); } entry.withRequestContentLength(entity.length); configureHTTPS(con); try { con.setDoInput(true); // HttpURLConnection will change method to POST if there is a body associated // with a GET request. Only try to write entity if it is not empty. entry.markStart(); if (entity.length > 0) { con.setDoOutput(true); try (OutputStream out = con.getOutputStream()) { out.write(entity); } } int status = con.getResponseCode(); entry.markEnd().withHttpStatus(status); // A null key is used to return the status line, remove it before sending to // the log entry or creating the response object Map<String, List<String>> headers = new LinkedHashMap<>(con.getHeaderFields()); headers.remove(null); for (Map.Entry<String, List<String>> h : headers.entrySet()) { for (String v : h.getValue()) { entry.addResponseHeader(h.getKey(), v); } } try (InputStream in = (status >= 400) ? con.getErrorStream() : con.getInputStream()) { byte[] data = readAll(in); entry.withResponseContentLength(data.length); return new HttpResponse(status, headers, data); } } catch (IOException e) { entry.markEnd().withException(e); throw e; } finally { entry.log(); } } @SuppressWarnings("PMD.AssignmentInOperand") private byte[] readAll(InputStream in) throws IOException { if (in == null) { // For error status codes with a content-length of 0 we see this case return new byte[0]; } else { ByteArrayOutputStream baos = reuseResponseStreams ? STREAM_HELPER.getOrCreateStream() : new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0) { baos.write(buffer, 0, length); } return baos.toByteArray(); } } }
5,636
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/http/HttpUtils.java
/* * Copyright 2014-2019 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.spectator.ipc.http; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.Deflater; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Helper functions for the http client. */ final class HttpUtils { private HttpUtils() { } /** Empty byte array constant. */ static final byte[] EMPTY = new byte[0]; private static final String DEFAULT = "default"; private static final Pattern PREFIX = Pattern.compile("^([^.-]+).*$"); /** * Extract a client name based on the host. This will currently select up * to the first dash or dot in the name. The goal is to have a reasonable * name, but avoid a large explosion in number of names in dynamic environments * such as EC2. Examples: * * <pre> * name host * ---------------------------------------------------- * foo foo.test.netflix.com * ec2 ec2-127-0-0-1.compute-1.amazonaws.com * </pre> */ static String clientNameForHost(String host) { Matcher m = PREFIX.matcher(host); return m.matches() ? m.group(1) : DEFAULT; } /** * Extract a client name based on the uri host. See {@link #clientNameForHost(String)} * for more details. */ static String clientNameForURI(URI uri) { String host = uri.getHost(); return (host == null) ? DEFAULT : clientNameForHost(host); } /** Wrap GZIPOutputStream allowing the user to override the compression level. */ static class GzipLevelOutputStream extends GZIPOutputStream { /** Creates a new output stream with a default compression level. */ GzipLevelOutputStream(OutputStream outputStream) throws IOException { super(outputStream); } /** Set the compression level for the underlying deflater. */ void setLevel(int level) { def.setLevel(level); } } /** * Compress a byte array using GZIP's default compression level. */ static byte[] gzip(byte[] data) throws IOException { return gzip(data, Deflater.DEFAULT_COMPRESSION); } /** * Compress a byte array using GZIP with the given compression level. */ static byte[] gzip(byte[] data, int level) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length); try (GzipLevelOutputStream out = new GzipLevelOutputStream(baos)) { out.setLevel(level); out.write(data); } return baos.toByteArray(); } /** Decompress a GZIP compressed byte array. */ @SuppressWarnings("PMD.AssignmentInOperand") static byte[] gunzip(byte[] data) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length * 10); try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(data))) { byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0) { baos.write(buffer, 0, length); } } return baos.toByteArray(); } }
5,637
0
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/http/HttpResponse.java
/* * Copyright 2014-2020 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.spectator.ipc.http; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; /** * Response for an HTTP request made via {@link HttpRequestBuilder}. */ public final class HttpResponse { private final int status; private final Map<String, List<String>> headers; private final byte[] data; /** Create a new response instance with an empty entity. */ public HttpResponse(int status, Map<String, List<String>> headers) { this(status, headers, HttpUtils.EMPTY); } /** Create a new response instance. */ public HttpResponse(int status, Map<String, List<String>> headers, byte[] data) { this.status = status; Map<String, List<String>> hs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); hs.putAll(headers); this.headers = Collections.unmodifiableMap(hs); this.data = data; } /** Return the status code of the response. */ public int status() { return status; } /** * Return the headers for the response as an unmodifiable map with case-insensitive keys. */ public Map<String, List<String>> headers() { return headers; } /** Return the value for the first occurrence of a given header or null if not found. */ public String header(String k) { List<String> vs = headers.get(k); return (vs == null || vs.isEmpty()) ? null : vs.get(0); } /** * Return the value for a date header. The return value will be null if the header does * not exist or if it cannot be parsed correctly as a date. */ public Instant dateHeader(String k) { String d = header(k); return (d == null) ? null : parseDate(d); } private Instant parseDate(String d) { try { return LocalDateTime.parse(d, DateTimeFormatter.RFC_1123_DATE_TIME) .atZone(ZoneOffset.UTC) .toInstant(); } catch (Exception e) { return null; } } /** Return the entity for the response. */ public byte[] entity() { return data; } /** Return the entity as a UTF-8 string. */ public String entityAsString() { return new String(data, StandardCharsets.UTF_8); } /** * Returns an input stream for consuming the response entity. If the content encoding is * {@code gzip}, then it will automatically wrap with a GZIP stream to decompress. This * can be more efficient than using {@link #decompress()} as it avoids creating an intermediate * copy of the decompressed data. The caller is responsible for ensuring that the returned * stream is closed. */ public InputStream entityInputStream() throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(data); String enc = header("Content-Encoding"); return (enc != null && enc.contains("gzip")) ? new GZIPInputStream(bais) : bais; } /** Return a copy of the response with the entity compressed. Typically used for testing. */ public HttpResponse compress() throws IOException { String enc = header("Content-Encoding"); return (enc == null) ? gzip() : this; } private HttpResponse gzip() throws IOException { Map<String, List<String>> newHeaders = new HashMap<>(headers); newHeaders.put("Content-Encoding", Collections.singletonList("gzip")); return new HttpResponse(status, newHeaders, HttpUtils.gzip(data)); } /** Return a copy of the response with the entity decompressed. */ public HttpResponse decompress() throws IOException { String enc = header("Content-Encoding"); return (enc != null && enc.contains("gzip")) ? gunzip() : this; } private HttpResponse gunzip() throws IOException { Map<String, List<String>> newHeaders = headers.entrySet().stream() .filter(e -> !"Content-Encoding".equalsIgnoreCase(e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); if (data.length == 0) { return new HttpResponse(status, newHeaders); } else { return new HttpResponse(status, newHeaders, HttpUtils.gunzip(data)); } } @Override public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("HTTP/1.1 ").append(status).append('\n'); for (Map.Entry<String, List<String>> h : headers.entrySet()) { for (String v : h.getValue()) { builder.append(h.getKey()).append(": ").append(v).append('\n'); } } builder.append("\n... ") .append(data.length) .append(" bytes ...\n"); return builder.toString(); } }
5,638
0
Create_ds/spectator/spectator-ext-ipc/src/jmh/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc/ServerGroupParsing.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.frigga.Names; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; /** * <h3>Throughput</h3> * * <pre> * Benchmark Mode Cnt Score Error Units * charSequence thrpt 10 3216353.588 ± 87966.348 ops/s * string thrpt 10 2476131.141 ± 32765.943 ops/s * frigga thrpt 10 11745.242 ± 2367.298 ops/s * </pre> * * <h3>Allocations</h3> * * <pre> * Benchmark Mode Cnt Score Error Units * charSequence thrpt 10 784.171 ± 0.006 B/op * string thrpt 10 1120.221 ± 0.005 B/op * frigga thrpt 10 124987.101 ± 11.368 B/op * </pre> */ @State(Scope.Thread) public class ServerGroupParsing { private final String[] asgs = { "application_name", "application_name-stack", "application_name-stack-detail", "application_name-stack-detail_1-detail_2", "application_name--detail", "application_name-v001", "application_name-stack-v001", "application_name-stack-detail-v001", "application_name-stack-detail_1-detail_2-v001", "application_name--detail-v001" }; @Benchmark public void string(Blackhole bh) { for (String asg : asgs) { ServerGroup group = ServerGroup.parse(asg); bh.consume(group.app()); bh.consume(group.cluster()); } } @Benchmark public void charSequence(Blackhole bh) { for (String asg : asgs) { SeqServerGroup group = SeqServerGroup.parse(asg); bh.consume(group.app()); bh.consume(group.cluster()); } } @Benchmark public void frigga(Blackhole bh) { for (String asg : asgs) { Names group = Names.parseName(asg); bh.consume(group.getApp()); bh.consume(group.getCluster()); } } }
5,639
0
Create_ds/spectator/spectator-ext-ipc/src/jmh/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc/ShardParsing.java
/* * Copyright 2014-2019 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.spectator.ipc; import com.netflix.frigga.Names; import com.netflix.frigga.conventions.sharding.Shard; import com.netflix.frigga.conventions.sharding.ShardingNamingConvention; import com.netflix.frigga.conventions.sharding.ShardingNamingResult; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import java.util.Map; /** * <h3>Throughput</h3> * * <pre> * Benchmark Mode Cnt Score Error Units * string thrpt 10 2390746.885 ± 267046.809 ops/s * frigga thrpt 10 49131.886 ± 1776.454 ops/s * </pre> * * <h3>Allocations</h3> * * <pre> * Benchmark Mode Cnt Score Error Units * string gc.alloc.rate.norm 10 512.164 ± 0.026 B/op * frigga gc.alloc.rate.norm 10 13120.752 ± 1.047 B/op * </pre> */ @State(Scope.Thread) public class ShardParsing { private final String[] asgs = { "application_name", "application_name-stack", "application_name-stack-x1foo-detail", "application_name-stack-x1foo-x2bar-detail_1-detail_2", "application_name--x1foo-x1bar-detail", "application_name-v001", "application_name-stack-v001", "application_name-stack-detail-v001", "application_name-stack-detail_1-detail_2-v001", "application_name--detail-v001" }; private final ShardingNamingConvention convention = new ShardingNamingConvention(); @Benchmark public void string(Blackhole bh) { for (String asg : asgs) { ServerGroup group = ServerGroup.parse(asg); bh.consume(group.shard1()); bh.consume(group.shard2()); } } @Benchmark public void frigga(Blackhole bh) { for (String asg : asgs) { Names group = Names.parseName(asg); String detail = group.getDetail(); if (detail != null) { ShardingNamingResult result = convention.extractNamingConvention(group.getDetail()); if (result.getResult().isPresent()) { Map<Integer, Shard> shards = result.getResult().get(); Shard s1 = shards.get(1); if (s1 != null) { bh.consume(s1.getShardValue()); } Shard s2 = shards.get(2); if (s2 != null) { bh.consume(s2.getShardValue()); } } } } } }
5,640
0
Create_ds/spectator/spectator-ext-ipc/src/jmh/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc/SeqServerGroup.java
/* * Copyright 2014-2019 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.spectator.ipc; import java.nio.CharBuffer; import java.util.Objects; /** * Helper for parsing Netflix server group names that follow the Frigga conventions. For * more information see the IEP documentation for * <a href="https://github.com/Netflix/iep/tree/master/iep-nflxenv#server-group-settings">server groups</a>. * * <p>Frigga is not used for the actual parsing as it is quite inefficient. See the * ServerGroupParsing benchmark for a comparison.</p> */ public class SeqServerGroup { /** * Create a new instance of a server group object by parsing the group name. */ public static SeqServerGroup parse(String asg) { int d1 = asg.indexOf('-'); int d2 = asg.indexOf('-', d1 + 1); int dN = asg.lastIndexOf('-'); if (dN < 0 || !isSequence(asg, dN)) { dN = asg.length(); } return new SeqServerGroup(asg, d1, d2, dN); } /** * Check if the last portion of the server group name is a version sequence (v\d+). */ private static boolean isSequence(String asg, int dN) { int length = asg.length(); if (length - dN < 3 || asg.charAt(dN + 1) != 'v') { return false; } for (int i = dN + 2; i < length; ++i) { if (!Character.isDigit(asg.charAt(i))) { return false; } } return true; } /** * The substring method will create a copy of the substring in JDK 8 and probably newer * versions. To reduce the number of allocations we use a char buffer to return a view * with just that subset. */ private static CharSequence substr(CharSequence str, int s, int e) { return (s >= e) ? null : CharBuffer.wrap(str, s, e); } private final CharSequence asg; private final int d1; private final int d2; private final int dN; /** * Create a new instance of the server group. * * @param asg * Raw group name received from the user. * @param d1 * Position of the first dash or -1 if there are no dashes in the input. * @param d2 * Position of the second dash or -1 if there is not a second dash in the input. * @param dN * Position indicating the end of the cluster name. For a server group with a * sequence this will be the final dash. If the sequence is not present, then * it will be the end of the string. */ SeqServerGroup(CharSequence asg, int d1, int d2, int dN) { this.asg = asg; this.d1 = d1; this.d2 = d2; this.dN = dN; } /** Return the application for the server group or null if invalid. */ public CharSequence app() { if (d1 < 0) { // No stack or detail is present return asg.length() > 0 ? asg : null; } else if (d1 == 0) { // Application portion is empty return null; } else { // Application is present along with stack, detail, or sequence return substr(asg, 0, d1); } } /** Return the cluster name for the server group or null if invalid. */ public CharSequence cluster() { if (d1 == 0) { // Application portion is empty return null; } else { return (dN > 0 && dN == asg.length()) ? asg() : substr(asg, 0, dN); } } /** Return the server group name or null if invalid. */ public CharSequence asg() { return (d1 != 0 && dN > 0) ? asg : null; } /** If the server group has a stack, then return the stack name. Otherwise return null. */ public CharSequence stack() { if (d1 <= 0) { // No stack, detail or sequence is present return null; } else if (d2 < 0) { // Stack, but no detail is present return substr(asg, d1 + 1, dN); } else { // Stack and at least one of detail or sequence is present return substr(asg, d1 + 1, d2); } } /** If the server group has a detail, then return the detail name. Otherwise return null. */ public CharSequence detail() { return (d1 != 0 && d2 > 0) ? substr(asg, d2 + 1, dN) : null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SeqServerGroup that = (SeqServerGroup) o; return d1 == that.d1 && d2 == that.d2 && dN == that.dN && Objects.equals(asg, that.asg); } @Override public int hashCode() { return Objects.hash(asg, d1, d2, dN); } @Override public String toString() { return "SeqServerGroup(" + asg + ", " + d1 + ", " + d2 + ", " + dN + ")"; } }
5,641
0
Create_ds/spectator/spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc
Create_ds/spectator/spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc/http/PathSanitizerBench.java
/* * Copyright 2014-2021 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.spectator.ipc.http; import com.netflix.spectator.impl.PatternMatcher; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import java.util.Random; import java.util.UUID; import java.util.function.Predicate; import java.util.regex.Pattern; /** * <pre> * Benchmark Mode Cnt Score Error Units * javaRegex thrpt 5 1991933.684 ± 40277.438 ops/s * customRegex thrpt 5 3647568.873 ± 130042.092 ops/s * handwritten thrpt 5 7345612.822 ± 385125.354 ops/s * * Benchmark Mode Cnt Score Error Units * javaRegex alloc 5 688.509 ± 0.009 B/op * customRegex alloc 5 514.248 ± 0.008 B/op * handwritten alloc 5 280.584 ± 0.005 B/op * </pre> */ @State(Scope.Thread) public class PathSanitizerBench { private final String regex = "^(v\\d+|[a-zA-Z]{1}|((?![b-df-hj-np-tv-xzB-DF-HJ-NP-TV-XZ]{4})[a-zA-Z]){3,})$"; private final Pattern javaPattern = Pattern.compile(regex); private final PatternMatcher customPattern = PatternMatcher.compile(regex); private final Sanitizer javaSanitizer = new Sanitizer(s -> javaPattern.matcher(s).matches()); private final Sanitizer customSanitizer = new Sanitizer(customPattern::matches); private static class Sanitizer { private final Predicate<String> shouldSuppressSegment; Sanitizer(Predicate<String> shouldSuppressSegment) { this.shouldSuppressSegment = shouldSuppressSegment; } private String removeMatixParameters(String path) { int i = path.indexOf(';'); return i > 0 ? path.substring(0, i) : path; } private String sanitizeSegments(String path) { StringBuilder builder = new StringBuilder(); int length = path.length(); int pos = path.charAt(0) == '/' ? 1 : 0; int segmentsAdded = 0; while (pos < length && segmentsAdded < 5) { String segment = null; int e = path.indexOf('/', pos); if (e > 0) { segment = path.substring(pos, e); pos = e + 1; } else { segment = path.substring(pos); pos = length; } if (!segment.isEmpty()) { if (shouldSuppressSegment.test(segment)) builder.append("_-"); else builder.append('_').append(segment); ++segmentsAdded; } } return builder.toString(); } String sanitize(String path) { return sanitizeSegments(removeMatixParameters(path)); } } @State(Scope.Thread) public static class Paths { private int pos; private String[] paths; public Paths() { pos = 0; paths = new String[10_000]; Random random = new Random(); for (int i = 0; i < paths.length; ++i) { paths[i] = randomPath(random); } } private String randomPath(Random random) { StringBuilder builder = new StringBuilder(); builder.append('/'); int n = random.nextInt(10); for (int i = 0; i < n; ++i) { switch (random.nextInt(10)) { case 0: builder.append(random.nextLong()); break; case 1: builder.append(random.nextDouble()); break; case 2: builder.append(UUID.randomUUID()); break; case 3: builder.append("en-US"); break; case 4: builder.append(String.format("%x", random.nextLong())); break; default: builder.append("api"); break; } } if (random.nextBoolean()) { builder.append(";q=").append(UUID.randomUUID()); } return builder.toString(); } public String next() { int i = Integer.remainderUnsigned(pos++, paths.length); return paths[i]; } } @Benchmark public void javaRegex(Paths paths, Blackhole bh) { bh.consume(javaSanitizer.sanitize(paths.next())); } @Benchmark public void customRegex(Paths paths, Blackhole bh) { bh.consume(customSanitizer.sanitize(paths.next())); } @Benchmark public void handwritten(Paths paths, Blackhole bh) { bh.consume(PathSanitizer.sanitize(paths.next())); } }
5,642
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/MdcTagFactoryTest.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.slf4j.MDC; /** * Unit tests for the MdcTagFactory class. */ public class MdcTagFactoryTest { @Test public void testNullName() { Assertions.assertThrows(NullPointerException.class, () -> new MdcTagFactory(null)); } @Test public void testNameFromKey() throws Exception { String expected = "factoryName"; TagFactory factory = new MdcTagFactory(expected); Assertions.assertEquals(expected, factory.name()); } @Test public void testNoValueInMdc() { TagFactory factory = new MdcTagFactory("unused"); Assertions.assertNull(factory.createTag()); } @Test public void testValueInMdc() { String mdcName = "key"; String expectedValue = "value"; Tag expectedTag = new BasicTag(mdcName, expectedValue); TagFactory factory = new MdcTagFactory("key"); try (MDC.MDCCloseable closeable = MDC.putCloseable(mdcName, expectedValue)) { Tag actualTag = factory.createTag(); Assertions.assertEquals(expectedTag, actualTag); } // Make sure that the factory returns null after the MDC has been cleaned up. Assertions.assertNull(factory.createTag()); } }
5,643
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/DefaultPlaceholderDistributionSummaryTest.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.DistributionSummary; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Registry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Collections; /** * Unit tests for the DefaultPlaceholderDistributionSummary class. */ public class DefaultPlaceholderDistributionSummaryTest { private final ManualClock clock = new ManualClock(); private final Registry registry = new DefaultRegistry(clock); private final PlaceholderFactory factory = PlaceholderFactory.from(registry); @Test public void testInit() { DistributionSummary summary = new DefaultPlaceholderDistributionSummary(new DefaultPlaceholderId("testInit", registry), registry); Assertions.assertEquals(0L, summary.count()); Assertions.assertEquals(0L, summary.totalAmount()); } @Test public void testRecord() { String[] tagValue = new String[] { "default" }; DistributionSummary summary = factory.distributionSummary(factory.createId("testRecord", Collections.singleton(new TestTagFactory(tagValue)))); summary.record(42L); Assertions.assertEquals("testRecord:tag=default", summary.id().toString()); Assertions.assertEquals(summary.count(), 1L); Assertions.assertEquals(42L, summary.totalAmount()); tagValue[0] = "value2"; Assertions.assertEquals("testRecord:tag=value2", summary.id().toString()); Assertions.assertEquals(0L, summary.count()); Assertions.assertEquals(0L, summary.totalAmount()); } @Test public void testRecordNegative() { DistributionSummary summary = factory.distributionSummary(factory.createId("testRecordNegative")); summary.record(-42L); Assertions.assertEquals(summary.count(), 0L); Assertions.assertEquals(0L, summary.totalAmount()); } @Test public void testRecordZero() { DistributionSummary summary = factory.distributionSummary(factory.createId("testRecordNegative")); summary.record(0); Assertions.assertEquals(summary.count(), 1L); Assertions.assertEquals(summary.totalAmount(), 0L); } }
5,644
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/DefaultPlaceholderCounterTest.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Measurement; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; /** * Unit tests for DefaultPlaceholderCounter class. * * Created on 10/8/15. */ public class DefaultPlaceholderCounterTest { private final ManualClock clock = new ManualClock(); private final Registry registry = new DefaultRegistry(clock); private final PlaceholderFactory factory = PlaceholderFactory.from(registry); @Test public void testInit() { Counter c = new DefaultPlaceholderCounter(new DefaultPlaceholderId("unused", registry), registry); Assertions.assertEquals(c.count(), 0L); } @Test public void testIncrement() { String[] tagValue = new String[] { "default" }; Counter c = factory.counter(factory.createId("testIncrement", Collections.singleton(new TestTagFactory(tagValue)))); Assertions.assertEquals(0L, c.count()); Assertions.assertEquals("testIncrement:tag=default", c.id().toString()); c.increment(); Assertions.assertEquals(1L, c.count()); c.increment(); c.increment(); Assertions.assertEquals(3L, c.count()); tagValue[0] = "value2"; Assertions.assertEquals("testIncrement:tag=value2", c.id().toString()); c.increment(); Assertions.assertEquals(1L, c.count()); tagValue[0] = "default"; Assertions.assertEquals("testIncrement:tag=default", c.id().toString()); c.increment(); Assertions.assertEquals(4L, c.count()); } @Test public void testIncrementAmount() { String[] tagValue = new String[] { "default" }; Counter c = factory.counter(factory.createId("testIncrementAmount", Collections.singleton(new TestTagFactory(tagValue)))); c.increment(42); Assertions.assertEquals(42L, c.count()); tagValue[0] = "value2"; c.increment(54); Assertions.assertEquals(54L, c.count()); } @Test public void testMeasure() { String[] tagValue = new String[] { "default" }; Counter c = factory.counter(factory.createId("testMeasure", Collections.singleton(new TestTagFactory(tagValue)))); doMeasurementTest(c, 42, 3712345L); tagValue[0] = "value2"; doMeasurementTest(c, 54, 3712346L); } private void doMeasurementTest(Counter c, int expectedValue, long expectedTime) { c.increment(expectedValue); clock.setWallTime(expectedTime); List<Measurement> measurements = Utils.toList(c.measure()); Assertions.assertEquals(1, measurements.size()); Measurement m = measurements.get(0); Assertions.assertEquals(c.id(), m.id()); Assertions.assertEquals(expectedTime, m.timestamp()); Assertions.assertEquals(expectedValue, m.value(), 0.1e-12); } @Test public void testHasExpired() { String[] tagValue = new String[] { "default" }; Counter c = factory.counter(factory.createId("testHasExpired", Collections.singleton(new TestTagFactory(tagValue)))); Assertions.assertFalse(c.hasExpired()); } }
5,645
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/DefaultPlaceholderIdTest.java
/* * Copyright 2014-2019 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.spectator.placeholders; 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.Tag; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class DefaultPlaceholderIdTest { private static final Registry REGISTRY = new DefaultRegistry(); private static final Id ID_1 = REGISTRY.createId("foo", "k1", "v1"); private static final Id ID_2 = REGISTRY.createId("foo", "k1", "v1", "k2", "v2"); @Test public void testNullName() { Assertions.assertThrows(NullPointerException.class, () -> new DefaultPlaceholderId(null, REGISTRY)); } @Test public void testName() { PlaceholderId id = new DefaultPlaceholderId("foo", REGISTRY); Assertions.assertEquals(id.name(), "foo"); } @Test public void equalsContractTest() { EqualsVerifier .forClass(DefaultPlaceholderId.class) .withPrefabValues(Iterable.class, ID_1.tags(), ID_2.tags()) .suppress(Warning.NULL_FIELDS) .verify(); } @Test public void testToString() { DefaultPlaceholderId id = (new DefaultPlaceholderId("foo", REGISTRY)).withTag("k1", "v1").withTag("k2", "v2"); Assertions.assertEquals("foo:k1=v1:k2=v2", id.toString()); } @Test public void testToStringNameOnly() { DefaultPlaceholderId id = new DefaultPlaceholderId("foo", REGISTRY); Assertions.assertEquals(id.toString(), "foo"); } @Test public void testWithTag() { Tag expected = new BasicTag("key", "value"); DefaultPlaceholderId id = new DefaultPlaceholderId("foo", REGISTRY).withTag(expected); Iterator<Tag> tags = id.resolveToId().tags().iterator(); Assertions.assertTrue(tags.hasNext(), "tags empty"); Assertions.assertEquals(expected, tags.next()); } @Test public void testWithTagsIterable() { List<Tag> tags = new ArrayList<>(); tags.add(new BasicTag("k1", "v1")); tags.add(new BasicTag("k2", "v2")); DefaultPlaceholderId id = (new DefaultPlaceholderId("foo", REGISTRY)).withTags(tags); Assertions.assertEquals("foo:k1=v1:k2=v2", id.toString()); } @Test public void testWithTagsMap() { Map<String, String> map = new LinkedHashMap<>(); map.put("k1", "v1"); map.put("k2", "v2"); DefaultPlaceholderId id = (new DefaultPlaceholderId("foo", REGISTRY)).withTags(map); Assertions.assertEquals("foo:k1=v1:k2=v2", id.toString()); } @Test public void testWithNoopTagFactory() { DefaultPlaceholderId id = new DefaultPlaceholderId("foo", REGISTRY).withTagFactory(new TagFactory() { @Override public String name() { return "noopTagFactory"; } @Override /* Implementation that always returns null, which should result in the tag being omitted. */ public Tag createTag() { return null; } }); Iterator<Tag> tags = id.resolveToId().tags().iterator(); Assertions.assertFalse(tags.hasNext(), "tags not empty"); } @Test public void testWithTagFactory() { Tag expected = new BasicTag("key", "value"); DefaultPlaceholderId id = new DefaultPlaceholderId("foo", REGISTRY).withTagFactory(new ConstantTagFactory(expected)); Iterator<Tag> tags = id.resolveToId().tags().iterator(); Assertions.assertTrue(tags.hasNext(), "tags empty"); Assertions.assertEquals(expected, tags.next()); } @Test public void testWithTagFactories() { Tag tags1 = new BasicTag("k1", "v1"); Tag tags2 = new BasicTag("k2", "v2"); List<TagFactory> factories = Arrays.asList(new ConstantTagFactory(tags1), new ConstantTagFactory(tags2)); DefaultPlaceholderId id = new DefaultPlaceholderId("foo", REGISTRY).withTagFactories(factories); Iterator<Tag> tags = id.resolveToId().tags().iterator(); Assertions.assertTrue(tags.hasNext(), "tags empty"); Assertions.assertEquals(tags1, tags.next()); Assertions.assertEquals(tags2, tags.next()); } @Test public void testResolveToId() { Tag tag = new BasicTag("key", "value"); Id expected = REGISTRY.createId("foo").withTag(tag); PlaceholderId placeholderId = new DefaultPlaceholderId("foo", REGISTRY).withTag(tag); Assertions.assertEquals(expected, placeholderId.resolveToId()); } @Test public void testCreateWithFactories() { Tag tags1 = new BasicTag("k1", "v1"); Tag tags2 = new BasicTag("k2", "v2"); List<TagFactory> factories = Arrays.asList(new ConstantTagFactory(tags1), new ConstantTagFactory(tags2)); DefaultPlaceholderId id = DefaultPlaceholderId.createWithFactories("foo", factories, REGISTRY); Iterator<Tag> tags = id.resolveToId().tags().iterator(); Assertions.assertEquals("foo", id.name()); Assertions.assertTrue(tags.hasNext(), "tags empty"); Assertions.assertEquals(tags1, tags.next()); Assertions.assertEquals(tags2, tags.next()); } @Test public void testCreateWithFactoriesNullIterable() { DefaultPlaceholderId id = DefaultPlaceholderId.createWithFactories("foo", null, REGISTRY); Iterator<Tag> tags = id.resolveToId().tags().iterator(); Assertions.assertEquals("foo", id.name()); Assertions.assertFalse(tags.hasNext(), "tags not empty"); } }
5,646
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/ConstantTagFactoryTest.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class ConstantTagFactoryTest { @Test public void testNullTag() { Assertions.assertThrows(NullPointerException.class, () -> new ConstantTagFactory(null)); } @Test public void testNullKey() { Assertions.assertThrows(NullPointerException.class, () -> new ConstantTagFactory(null, "value")); } @Test public void testNullValue() { Assertions.assertThrows(NullPointerException.class, () -> new ConstantTagFactory("key", null)); } @Test public void testNameFromTag() throws Exception { String expected = "factoryName"; Tag tag = new BasicTag(expected, "unused"); TagFactory factory = new ConstantTagFactory(tag); Assertions.assertEquals(expected, factory.name()); } @Test public void testNameFromKey() throws Exception { String expected = "factoryName"; TagFactory factory = new ConstantTagFactory(expected, "unused"); Assertions.assertEquals(expected, factory.name()); } @Test public void testCreateTagUsingTagConstructor() throws Exception { Tag expected = new BasicTag("key", "value"); TagFactory factory = new ConstantTagFactory(expected); Tag actual = factory.createTag(); Assertions.assertSame(expected, actual); } @Test public void testCreateTagUsingKeyValueConstructor() throws Exception { String expectedKey = "key"; String expectedValue = "value"; TagFactory factory = new ConstantTagFactory(expectedKey, expectedValue); Tag actual = factory.createTag(); Assertions.assertEquals(expectedKey, actual.key()); Assertions.assertEquals(expectedValue, actual.value()); } @Test public void equalsContractTest() { EqualsVerifier .forClass(ConstantTagFactory.class) .suppress(Warning.NULL_FIELDS) .verify(); } }
5,647
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/TagFactoryTest.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.BasicTag; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicReference; public class TagFactoryTest { @Test public void fromSupplier() { TagFactory f = TagFactory.from("foo", () -> "bar"); Assertions.assertEquals("foo", f.name()); Assertions.assertEquals(new BasicTag("foo", "bar"), f.createTag()); } @Test public void fromSupplierNull() { TagFactory f = TagFactory.from("foo", () -> null); Assertions.assertEquals("foo", f.name()); Assertions.assertNull(f.createTag()); } @Test public void fromSupplierDynamic() { AtomicReference<String> value = new AtomicReference<>(); TagFactory f = TagFactory.from("foo", value::get); Assertions.assertEquals("foo", f.name()); Assertions.assertNull(f.createTag()); value.set("bar"); Assertions.assertEquals(new BasicTag("foo", "bar"), f.createTag()); } }
5,648
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/DefaultPlaceholderGaugeTest.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Measurement; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; public class DefaultPlaceholderGaugeTest { private final ManualClock clock = new ManualClock(); private final Registry registry = new DefaultRegistry(clock); private final PlaceholderFactory factory = PlaceholderFactory.from(registry); @Test public void testInit() { Gauge g = new DefaultPlaceholderGauge(new DefaultPlaceholderId("unused", registry), registry); Assertions.assertEquals(g.value(), Double.NaN, 1e-12); } @Test public void testIncrement() { String[] tagValue = new String[] { "default" }; Gauge g = factory.gauge(factory.createId("testIncrement", Collections.singleton(new TestTagFactory(tagValue)))); Assertions.assertEquals(Double.NaN, g.value(), 1e-12); Assertions.assertEquals("testIncrement:tag=default", g.id().toString()); g.set(1); Assertions.assertEquals(1.0, g.value(), 1e-12); g.set(3); Assertions.assertEquals(3.0, g.value(), 1e-12); tagValue[0] = "value2"; Assertions.assertEquals("testIncrement:tag=value2", g.id().toString()); g.set(1); Assertions.assertEquals(1.0, g.value(), 1e-12); tagValue[0] = "default"; Assertions.assertEquals("testIncrement:tag=default", g.id().toString()); g.set(4); Assertions.assertEquals(4.0, g.value(), 1e-12); } @Test public void testIncrementAmount() { String[] tagValue = new String[] { "default" }; Gauge g = factory.gauge(factory.createId("testIncrementAmount", Collections.singleton(new TestTagFactory(tagValue)))); g.set(42); Assertions.assertEquals(42.0, g.value(), 1e-12); tagValue[0] = "value2"; g.set(54); Assertions.assertEquals(54.0, g.value(), 1e-12); } @Test public void testMeasure() { String[] tagValue = new String[] { "default" }; Gauge g = factory.gauge(factory.createId("testMeasure", Collections.singleton(new TestTagFactory(tagValue)))); doMeasurementTest(g, 42, 3712345L); tagValue[0] = "value2"; doMeasurementTest(g, 54, 3712346L); } private void doMeasurementTest(Gauge g, int expectedValue, long expectedTime) { g.set(expectedValue); clock.setWallTime(expectedTime); List<Measurement> measurements = Utils.toList(g.measure()); Assertions.assertEquals(1, measurements.size()); Measurement m = measurements.get(0); Assertions.assertEquals(g.id(), m.id()); Assertions.assertEquals(expectedTime, m.timestamp()); Assertions.assertEquals(expectedValue, m.value(), 0.1e-12); } @Test public void testHasExpired() { String[] tagValue = new String[] { "default" }; Gauge g = factory.gauge(factory.createId("testHasExpired", Collections.singleton(new TestTagFactory(tagValue)))); Assertions.assertFalse(g.hasExpired()); } }
5,649
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/DefaultPlaceholderTimerTest.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Measurement; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Statistic; import com.netflix.spectator.api.Timer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.concurrent.TimeUnit; /** * Unit tests for the DefaultPlaceholderTimer class. */ public class DefaultPlaceholderTimerTest { private final ManualClock clock = new ManualClock(); private final Registry registry = new DefaultRegistry(clock); private final PlaceholderFactory factory = PlaceholderFactory.from(registry); @Test public void testInit() { Timer timer = new DefaultPlaceholderTimer(new DefaultPlaceholderId("testInit", registry), registry); Assertions.assertEquals(0L, timer.count()); Assertions.assertEquals(0L, timer.totalTime()); } @Test public void testRecord() { String[] tagValue = new String[] { "default" }; Timer timer = factory.timer(factory.createId("testRecord", Collections.singleton(new TestTagFactory(tagValue)))); timer.record(42, TimeUnit.MILLISECONDS); Assertions.assertEquals("testRecord:tag=default", timer.id().toString()); Assertions.assertEquals(timer.count(), 1L); Assertions.assertEquals(42000000L, timer.totalTime()); tagValue[0] = "value2"; Assertions.assertEquals("testRecord:tag=value2", timer.id().toString()); Assertions.assertEquals(0L, timer.count()); Assertions.assertEquals(0L, timer.totalTime()); } @Test public void testRecordNegative() { Timer timer = factory.timer(factory.createId("testRecordNegative")); timer.record(-42, TimeUnit.MILLISECONDS); Assertions.assertEquals(timer.count(), 0L); Assertions.assertEquals(0L, timer.totalTime()); } @Test public void testRecordZero() { Timer timer = factory.timer(factory.createId("testRecordZero")); timer.record(0, TimeUnit.MILLISECONDS); Assertions.assertEquals(1L, timer.count(), 1L); Assertions.assertEquals(0L, timer.totalTime()); } @Test public void testRecordCallable() throws Exception { int expected = 42; Timer timer = factory.timer(factory.createId("testRecordCallable")); clock.setMonotonicTime(100L); int actual = timer.record(() -> { clock.setMonotonicTime(500L); return expected; }); Assertions.assertEquals(expected, actual); Assertions.assertEquals(1L, timer.count()); Assertions.assertEquals(400L, timer.totalTime()); } @Test public void testRecordCallableException() throws Exception { Timer timer = factory.timer(factory.createId("testRecordCallableException")); clock.setMonotonicTime(100L); boolean seen = false; try { timer.record(() -> { clock.setMonotonicTime(500L); throw new Exception("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); Assertions.assertEquals(1L, timer.count()); Assertions.assertEquals(400L, timer.totalTime()); } @Test public void testRecordRunnable() throws Exception { Timer timer = factory.timer(factory.createId("testRecordRunnable")); clock.setMonotonicTime(100L); timer.record(() -> clock.setMonotonicTime(500L)); Assertions.assertEquals(1L, timer.count()); Assertions.assertEquals(timer.totalTime(), 400L); } @Test public void testRecordRunnableException() throws Exception { Timer timer = factory.timer(factory.createId("testRecordRunnableException")); clock.setMonotonicTime(100L); Exception expectedExc = new RuntimeException("foo"); Exception actualExc = null; try { timer.record(() -> { clock.setMonotonicTime(500L); throw expectedExc; }); } catch (Exception e) { actualExc = e; } Assertions.assertSame(expectedExc, actualExc); Assertions.assertEquals(1L, timer.count()); Assertions.assertEquals(timer.totalTime(), 400L); } @Test public void testMeasure() { Timer timer = factory.timer(factory.createId("testMeasure")); timer.record(42, TimeUnit.MILLISECONDS); clock.setWallTime(3712345L); for (Measurement m : timer.measure()) { Assertions.assertEquals(m.timestamp(), 3712345L); if (m.id().equals(timer.id().withTag(Statistic.count))) { Assertions.assertEquals(1.0, m.value(), 0.1e-12); } else if (m.id().equals(timer.id().withTag(Statistic.totalTime))) { Assertions.assertEquals(42e6, m.value(), 0.1e-12); } else { Assertions.fail("unexpected id: " + m.id()); } } } }
5,650
0
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/test/java/com/netflix/spectator/placeholders/TestTagFactory.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import org.junit.jupiter.api.Disabled; /** * Helper class for testing dynamic metrics. */ @Disabled class TestTagFactory implements TagFactory { private final String name; private final String[] valueHolder; TestTagFactory(String[] valueHolder) { this("tag", valueHolder); } TestTagFactory(String name, String[] valueHolder) { this.name = name; this.valueHolder = valueHolder; } @Override public String name() { return name; } @Override public Tag createTag() { return new BasicTag(name, valueHolder[0]); } }
5,651
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/DefaultPlaceholderDistributionSummary.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.DistributionSummary; import com.netflix.spectator.api.Registry; /** * Distribution summary implementation that delegates the value tracking to * component distribution summaries based on the current value of the tags * associated with the PlaceholderId when the interface methods are called. */ class DefaultPlaceholderDistributionSummary extends AbstractDefaultPlaceholderMeter<DistributionSummary> implements DistributionSummary { /** * Constructs a new distribution summary with the specified dynamic id. * * @param id the dynamic (template) id for generating the individual distribution summaries * @param registry the registry to use to instantiate the individual distribution summaries */ DefaultPlaceholderDistributionSummary(PlaceholderId id, Registry registry) { super(id, registry::distributionSummary); } @Override public void record(long amount) { resolveToCurrentMeter().record(amount); } @Override public long count() { return resolveToCurrentMeter().count(); } @Override public long totalAmount() { return resolveToCurrentMeter().totalAmount(); } }
5,652
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/PlaceholderFactory.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DistributionSummary; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; /** * Factory for creating instances of activity based meters with placeholders in the * identifiers so that the final id can be resolved when the activity takes place. */ public interface PlaceholderFactory { /** * Create a new instance of the factory. * * @param registry * the registry to use when creating ids */ static PlaceholderFactory from(Registry registry) { return new DefaultPlaceholderFactory(registry); } /** * Creates an identifier with placeholders for a counter, timer, or distribution summary. * * @param name * Description of the measurement that is being collected. * @return * The newly created identifier. */ PlaceholderId createId(String name); /** * Creates an identifier with placeholders for a counter, timer, or distribution summary. * * @param name * Description of the measurement that is being collected. * @param tagFactories * Other factories that can generate other dimensions that can be used to classify * the measurement. * @return * The newly created identifier. */ PlaceholderId createId(String name, Iterable<TagFactory> tagFactories); /** * Represents a value sampled at a given time. * * @param id * Identifier created by a call to {@link #createId} */ Gauge gauge(PlaceholderId id); /** * Measures the rate of some activity. A counter is for continuously incrementing sources like * the number of requests that are coming into a server. * * @param id * Identifier created by a call to {@link #createId} */ Counter counter(PlaceholderId id); /** * Measures the rate and variation in amount for some activity. For example, it could be used to * get insight into the variation in response sizes for requests to a server. * * @param id * Identifier created by a call to {@link #createId} */ DistributionSummary distributionSummary(PlaceholderId id); /** * Measures the rate and time taken for short running tasks. * * @param id * Identifier created by a call to {@link #createId} */ Timer timer(PlaceholderId id); }
5,653
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/MdcTagFactory.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import com.netflix.spectator.impl.Preconditions; import org.slf4j.MDC; /** * A TagFactory implementation that extracts information from the Sl4fj MDC data. * If the MDC for the current thread has no value associated with the specified * name at the time that the createTag method is invoked, then that method will * return null, which will result in the tag being omitted. */ public class MdcTagFactory implements TagFactory { private final String name; /** * Construct a new instance that will return a Tag with the MDC value associated * with the specified name at the time that the createTag method is invoked. * * @param name * the non-null name of the MDC value to use for the tag */ public MdcTagFactory(String name) { this.name = Preconditions.checkNotNull(name, "name"); } @Override public String name() { return name; } @Override public Tag createTag() { String value = MDC.get(name); return value != null ? new BasicTag(name, value) : null; } }
5,654
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/DefaultPlaceholderId.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import com.netflix.spectator.impl.Preconditions; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; /** * Default/standard implementation of the PlaceholderId interface. */ final class DefaultPlaceholderId implements PlaceholderId { /** * Utility class for sorting and deduplicating lists of tag factories. */ private static final class FactorySorterAndDeduplicator { /** Map used to sort and deduplicate the presented tag factories. */ private final Map<String, TagFactory> map = new TreeMap<>(); /** Construct a new instance with the specified factories in it. */ FactorySorterAndDeduplicator(Iterable<TagFactory> tagFactories) { addFactories(tagFactories); } /** * Adds the specified tag to the collected tags. It will overwrite any existing value * associated the key in the specified tag. * * @param factory * The tag factory to add to the collection */ void addFactory(TagFactory factory) { map.put(factory.name(), factory); } /** * Adds the tags (key, value)-pairs to the collected tags. Any values associated with the tags * in the map will overwrite any existing values with the same key that are already in the * collection. * * @param factories * The set of tag factories to add. */ void addFactories(Iterable<TagFactory> factories) { for (TagFactory factory : factories) { map.put(factory.name(), factory); } } /** Returns the sorted set of tag factories as an unmodifiable collection. */ Collection<TagFactory> asCollection() { return Collections.unmodifiableCollection(map.values()); } } private final String name; private final Collection<TagFactory> tagFactories; private final Registry registry; /** * Creates a new id with the specified name and collection of factories. * * @param name * the name of the new id * @param tagFactories * the possibly empty collection of factories to be attached to the new id * @param registry * the registry to use when resolving to an {@link Id} * @return * the newly created id */ static DefaultPlaceholderId createWithFactories(String name, Iterable<TagFactory> tagFactories, Registry registry) { if (tagFactories == null) { return new DefaultPlaceholderId(name, registry); } else { FactorySorterAndDeduplicator sorter = new FactorySorterAndDeduplicator(tagFactories); return new DefaultPlaceholderId(name, sorter.asCollection(), registry); } } /** * Constructs a new id with the specified name and no associated tag factories. */ DefaultPlaceholderId(String name, Registry registry) { this(name, Collections.emptyList(), registry); } /** * Constructs a new id with the specified name and tag factories. * @param name * the name of the new id * @param tagFactories * the possibly empty collection of factories to be attached to the new id * @param registry * the registry to use when resolving to an {@link Id} */ private DefaultPlaceholderId(String name, Collection<TagFactory> tagFactories, Registry registry) { this.name = Preconditions.checkNotNull(name, "name"); this.tagFactories = tagFactories; this.registry = registry; } @Override public String name() { return name; } @Override public DefaultPlaceholderId withTag(String k, String v) { return withTagFactory(new ConstantTagFactory(new BasicTag(k, v))); } @Override public DefaultPlaceholderId withTag(Tag t) { return withTagFactory(new ConstantTagFactory(t)); } @Override public DefaultPlaceholderId withTags(Iterable<Tag> tags) { return createNewId(sorter -> tags.forEach(tag -> sorter.addFactory(new ConstantTagFactory(tag)))); } @Override public DefaultPlaceholderId withTags(Map<String, String> tags) { return createNewId(sorter -> tags.forEach((key, value) -> sorter.addFactory(new ConstantTagFactory(new BasicTag(key, value))))); } @Override public DefaultPlaceholderId withTagFactory(TagFactory factory) { if (tagFactories.isEmpty()) { return new DefaultPlaceholderId(name, Collections.singleton(factory), registry); } else { return createNewId(sorter -> sorter.addFactory(factory)); } } @Override public DefaultPlaceholderId withTagFactories(Iterable<TagFactory> factories) { return createNewId(sorter -> sorter.addFactories(factories)); } @Override public Id resolveToId() { Iterable<Tag> tags = tagFactories.stream() .map(TagFactory::createTag) .filter(Objects::nonNull) .collect(Collectors.toList()); return registry.createId(name, tags); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DefaultPlaceholderId that = (DefaultPlaceholderId) o; // We cannot use tagFactories.equals(that.tagFactories) below, because Java // unmodifiable collections do not override equals appropriately. return name.equals(that.name) && registry == that.registry && tagFactories.size() == that.tagFactories.size() && tagFactories.containsAll(that.tagFactories); } @Override public int hashCode() { return 31 * name.hashCode() + 31 * registry.hashCode() + tagFactories.hashCode(); } @Override public String toString() { return resolveToId().toString(); } /** * Creates a new dynamic id based on the factories associated with this id * and whatever additions are made by the specified consumer. * * @param consumer * lambda that can update the sorter with additional tag factories * @return * the newly created id */ private DefaultPlaceholderId createNewId(Consumer<FactorySorterAndDeduplicator> consumer) { FactorySorterAndDeduplicator sorter = new FactorySorterAndDeduplicator(tagFactories); consumer.accept(sorter); return new DefaultPlaceholderId(name, sorter.asCollection(), registry); } }
5,655
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/DefaultPlaceholderTimer.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * Timer implementation that delegates the value tracking to component timers * based on the current value of the tags associated with the PlaceholderId when the * interface methods are called. */ class DefaultPlaceholderTimer extends AbstractDefaultPlaceholderMeter<Timer> implements Timer { /** * Constructs a new timer with the specified dynamic id. * * @param id the dynamic (template) id for generating the individual timers * @param registry the registry to use to instantiate the individual timers */ DefaultPlaceholderTimer(PlaceholderId id, Registry registry) { super(id, registry::timer); } @Override public void record(long amount, TimeUnit unit) { resolveToCurrentMeter().record(amount, unit); } @Override public <T> T record(Callable<T> f) throws Exception { return resolveToCurrentMeter().record(f); } @Override public void record(Runnable f) { resolveToCurrentMeter().record(f); } @Override public long count() { return resolveToCurrentMeter().count(); } @Override public long totalTime() { return resolveToCurrentMeter().totalTime(); } }
5,656
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/DefaultPlaceholderFactory.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DistributionSummary; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; /** * Factory for creating instances of activity based meters with placeholders in the * identifiers so that the final id can be resolved when the activity takes place. */ final class DefaultPlaceholderFactory implements PlaceholderFactory { private final Registry registry; /** * Create a new instance of the factory. * * @param registry * the registry to use when creating ids */ DefaultPlaceholderFactory(Registry registry) { this.registry = registry; } @Override public PlaceholderId createId(String name) { return new DefaultPlaceholderId(name, registry); } @Override public PlaceholderId createId(String name, Iterable<TagFactory> tagFactories) { return DefaultPlaceholderId.createWithFactories(name, tagFactories, registry); } @Override public Gauge gauge(PlaceholderId id) { return new DefaultPlaceholderGauge(id, registry); } @Override public Counter counter(PlaceholderId id) { return new DefaultPlaceholderCounter(id, registry); } @Override public DistributionSummary distributionSummary(PlaceholderId id) { return new DefaultPlaceholderDistributionSummary(id, registry); } @Override public Timer timer(PlaceholderId id) { return new DefaultPlaceholderTimer(id, registry); } }
5,657
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/ConstantTagFactory.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import com.netflix.spectator.impl.Preconditions; /** * TagFactory implementation that always produces the same tag. Useful for * providing a default value for a tag. */ public final class ConstantTagFactory implements TagFactory { private final Tag tag; /** * Construct a new instance that will always return a Tag with the specified value. * * @param key * the non-null key for the tag * @param value * the non-null value for the tag */ public ConstantTagFactory(String key, String value) { this(new BasicTag(key, value)); } /** * Construct a new instance that will always return the specified tag. * * @param tag * the non-null Tag instance to return from createTag */ public ConstantTagFactory(Tag tag) { this.tag = Preconditions.checkNotNull(tag, "tag"); } @Override public String name() { return tag.key(); } @Override public Tag createTag() { return tag; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConstantTagFactory other = (ConstantTagFactory) o; return tag.equals(other.tag); } @Override public int hashCode() { return tag.hashCode(); } }
5,658
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/PlaceholderId.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Tag; import java.util.Map; /** * An extension of the {@link Id} interface that allows the list of tag names attached * to the Id to be declared in advance of the use of the metric. This can be used to * provide a default value for a tag or to use a TagFactory implementation that uses * context available in the execution environment to compute the value of the tag. */ public interface PlaceholderId { /** Description of the measurement that is being collected. */ String name(); /** New id with an additional tag value. */ PlaceholderId withTag(String k, String v); /** New id with an additional tag value. */ PlaceholderId withTag(Tag t); /** New id with additional tag values. */ PlaceholderId withTags(Iterable<Tag> tags); /** New id with additional tag values. */ PlaceholderId withTags(Map<String, String> tags); /** * New id with an additional tag factory. * @param factory * the factory to use to generate the values for the tag */ PlaceholderId withTagFactory(TagFactory factory); /** * New id with additional tag factories. * @param factories * a collection of factories for producing values for the tags */ PlaceholderId withTagFactories(Iterable<TagFactory> factories); /** * Invokes each of the associated tag factories to produce a Id based on the * runtime context available when this method is invoked. If an associated * TagFactory produces a non-null Tag, then the returned Id will have that * Tag associated with it. * * @return an Id that has the same name as this id and the resolved tag values attached */ Id resolveToId(); }
5,659
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/DefaultPlaceholderCounter.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; /** * Counter implementation that delegates the value tracking to component counters * based on the current value of the tags associated with the PlaceholderId when the * increment methods are called. */ class DefaultPlaceholderCounter extends AbstractDefaultPlaceholderMeter<Counter> implements Counter { /** * Constructs a new counter with the specified dynamic id. * * @param id the dynamic (template) id for generating the individual counters * @param registry the registry to use to instantiate the individual counters */ DefaultPlaceholderCounter(PlaceholderId id, Registry registry) { super(id, registry::counter); } @Override public void add(double amount) { resolveToCurrentMeter().add(amount); } @Override public double actualCount() { return resolveToCurrentMeter().count(); } }
5,660
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/AbstractDefaultPlaceholderMeter.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Measurement; import com.netflix.spectator.api.Meter; import java.util.function.Function; /** * Base class for dynamic meters that provides implementations for the core * interface methods. */ abstract class AbstractDefaultPlaceholderMeter<T extends Meter> implements Meter { private final PlaceholderId id; private final Function<Id, T> meterResolver; /** * Creates a new dynamic meter. * * @param id the dynamic id for the meter * @param meterResolver the function to map a resolved id to concrete metric */ AbstractDefaultPlaceholderMeter(PlaceholderId id, Function<Id, T> meterResolver) { this.id = id; this.meterResolver = meterResolver; } /** * Resolve the dynamic id to the current metric instance. */ protected final T resolveToCurrentMeter() { return meterResolver.apply(id()); } @Override public final Id id() { return id.resolveToId(); } @Override public final Iterable<Measurement> measure() { return resolveToCurrentMeter().measure(); } @Override public final boolean hasExpired() { // Without tracking all of the regular meters that are created from this // dynamic meter we don't have any way of knowing whether the "master" // counter has expired. Instead of adding the tracking, we choose to // rely on the regular expiration mechanism for the underlying meters. return false; } }
5,661
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/DefaultPlaceholderGauge.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Registry; /** * Gauge implementation that delegates the value tracking to component gauges * based on the current value of the tags associated with the PlaceholderId when the * increment methods are called. */ class DefaultPlaceholderGauge extends AbstractDefaultPlaceholderMeter<Gauge> implements Gauge { /** * Constructs a new counter with the specified dynamic id. * * @param id * The dynamic (template) id for generating the individual counters. * @param registry * The registry to use to instantiate the individual counters. */ DefaultPlaceholderGauge(PlaceholderId id, Registry registry) { super(id, registry::gauge); } @Override public void set(double value) { resolveToCurrentMeter().set(value); } @Override public double value() { return resolveToCurrentMeter().value(); } }
5,662
0
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/TagFactory.java
/* * Copyright 2014-2019 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.spectator.placeholders; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import java.util.function.Supplier; /** * A factory for producing tag values. */ public interface TagFactory { /** * Helper method for creating a tag factory that uses a lambda to supply * the value. * * @param name * Key to use for the returned tag value. * @param value * Supplier used to retrieve the value for the tag. If the return * value is null, then a null tag is returned an the dimension will * be suppressed. * @return * Factory for producing tags using the value supplier. */ static TagFactory from(String name, Supplier<String> value) { return new TagFactory() { @Override public String name() { return name; } @Override public Tag createTag() { final String v = value.get(); return (v == null) ? null : new BasicTag(name, v); } }; } /** * Returns the name of the factory, which is used as the key for any Tag * produced by the createTag method. */ String name(); /** * Produces a tag based on the runtime context available to the factory. * * @return * the appropriate tag given the available context data, possibly null */ Tag createTag(); }
5,663
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/SchedulerTest.java
/* * Copyright 2014-2019 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.spectator.impl; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.ManualClock; import com.netflix.spectator.api.Registry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOError; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class SchedulerTest { @Test public void updateNextFixedDelay() { ManualClock clock = new ManualClock(); Registry registry = new DefaultRegistry(clock); Counter skipped = registry.counter("skipped"); Scheduler.Options options = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofSeconds(10)); clock.setWallTime(5437L); Scheduler.DelayedTask task = new Scheduler.DelayedTask(clock, options, () -> {}); Assertions.assertEquals(5437L, task.getNextExecutionTime()); Assertions.assertEquals(0L, skipped.count()); clock.setWallTime(12123L); task.updateNextExecutionTime(skipped); Assertions.assertEquals(22123L, task.getNextExecutionTime()); Assertions.assertEquals(0L, skipped.count()); clock.setWallTime(27000L); task.updateNextExecutionTime(skipped); Assertions.assertEquals(37000L, task.getNextExecutionTime()); Assertions.assertEquals(0L, skipped.count()); } @Test public void updateNextFixedRateSkip() { ManualClock clock = new ManualClock(); Registry registry = new DefaultRegistry(clock); Counter skipped = registry.counter("skipped"); Scheduler.Options options = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_RATE_SKIP_IF_LONG, Duration.ofSeconds(10)); clock.setWallTime(5437L); Scheduler.DelayedTask task = new Scheduler.DelayedTask(clock, options, () -> {}); Assertions.assertEquals(5437L, task.getNextExecutionTime()); Assertions.assertEquals(0L, skipped.count()); clock.setWallTime(12123L); task.updateNextExecutionTime(skipped); Assertions.assertEquals(15437L, task.getNextExecutionTime()); Assertions.assertEquals(0L, skipped.count()); clock.setWallTime(27000L); task.updateNextExecutionTime(skipped); Assertions.assertEquals(35437L, task.getNextExecutionTime()); Assertions.assertEquals(1L, skipped.count()); clock.setWallTime(57000L); task.updateNextExecutionTime(skipped); Assertions.assertEquals(65437L, task.getNextExecutionTime()); Assertions.assertEquals(3L, skipped.count()); } private long numberOfThreads(String id) { return Thread.getAllStackTraces() .keySet() .stream() .filter(t -> t.getName().startsWith("spectator-" + id)) .count(); } @Test public void shutdownStopsThreads() throws Exception { Scheduler s = new Scheduler(new DefaultRegistry(), "shutdown", 1); // Schedule something to force it to start the threads Scheduler.Options opts = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_RATE_SKIP_IF_LONG, Duration.ofMillis(10)) .withStopOnFailure(false); ScheduledFuture<?> f = s.schedule(opts, () -> {}); Assertions.assertEquals(1L, numberOfThreads("shutdown")); // Shutdown and wait a bit, this gives the thread a chance to restart s.shutdown(); Thread.sleep(300); Assertions.assertEquals(0L, numberOfThreads("shutdown")); } @Test public void stopOnFailureFalseThrowable() throws Exception { Scheduler s = new Scheduler(new DefaultRegistry(), "test", 1); Scheduler.Options opts = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_RATE_SKIP_IF_LONG, Duration.ofMillis(10)) .withStopOnFailure(false); final CountDownLatch latch = new CountDownLatch(5); ScheduledFuture<?> f = s.schedule(opts, () -> { latch.countDown(); throw new IOError(new RuntimeException("stop")); }); Assertions.assertTrue(latch.await(60, TimeUnit.SECONDS)); Assertions.assertFalse(f.isDone()); s.shutdown(); } @Test public void stopOnFailureFalse() throws Exception { Scheduler s = new Scheduler(new DefaultRegistry(), "test", 2); Scheduler.Options opts = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofMillis(10)) .withStopOnFailure(false); final CountDownLatch latch = new CountDownLatch(5); ScheduledFuture<?> f = s.schedule(opts, () -> { latch.countDown(); throw new RuntimeException("stop"); }); Assertions.assertTrue(latch.await(60, TimeUnit.SECONDS)); Assertions.assertFalse(f.isDone()); s.shutdown(); } @Test public void stopOnFailureTrue() throws Exception { Scheduler s = new Scheduler(new DefaultRegistry(), "test", 2); Scheduler.Options opts = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofMillis(10)) .withStopOnFailure(true); final CountDownLatch latch = new CountDownLatch(1); ScheduledFuture<?> f = s.schedule(opts, () -> { latch.countDown(); throw new RuntimeException("stop"); }); Assertions.assertTrue(latch.await(60, TimeUnit.SECONDS)); while (!f.isDone()); // This will be an endless loop if broken s.shutdown(); } @Test public void cancel() throws Exception { Scheduler s = new Scheduler(new DefaultRegistry(), "test", 2); Scheduler.Options opts = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofMillis(10)) .withStopOnFailure(false); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<ScheduledFuture<?>> ref = new AtomicReference<>(); ref.set(s.schedule(opts, () -> { try { while (ref.get() == null); ref.get().cancel(true); Thread.sleep(600000L); } catch (InterruptedException e) { latch.countDown(); } })); Assertions.assertTrue(latch.await(60, TimeUnit.SECONDS)); Assertions.assertTrue(ref.get().isDone()); s.shutdown(); } @Test public void threadsAreReplaced() throws Exception { Scheduler s = new Scheduler(new DefaultRegistry(), "test", 1); Scheduler.Options opts = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofMillis(10)) .withStopOnFailure(false); final CountDownLatch latch = new CountDownLatch(10); s.schedule(opts, () -> { latch.countDown(); Thread.currentThread().interrupt(); }); Assertions.assertTrue(latch.await(60, TimeUnit.SECONDS)); s.shutdown(); } }
5,664
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/StreamHelperTest.java
/* * Copyright 2014-2023 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.spectator.impl; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; public class StreamHelperTest { @Test public void getOrCreateStream() { StreamHelper helper = new StreamHelper(); ByteArrayOutputStream o1 = helper.getOrCreateStream(); ByteArrayOutputStream o2 = helper.getOrCreateStream(); Assertions.assertSame(o1, o2); } @Test public void streamIsResetBeforeNextUse() { StreamHelper helper = new StreamHelper(); ByteArrayOutputStream out = helper.getOrCreateStream(); out.write(42); Assertions.assertEquals(1, out.size()); helper.getOrCreateStream(); Assertions.assertEquals(0, out.size()); } }
5,665
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/Hash64Test.java
/* * Copyright 2014-2023 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.spectator.impl; import net.openhft.hashing.LongHashFunction; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; public class Hash64Test { private final Random random = new Random(42L); private boolean[] randomBooleanArray(int length) { boolean[] vs = new boolean[length]; for (int i = 0; i < length; ++i) { vs[i] = random.nextBoolean(); } return vs; } private long checkBooleans(boolean[] vs) { Hash64 h64 = new Hash64(); for (boolean v : vs) h64.updateBoolean(v); long a = h64.computeAndReset(); long b = h64.updateBooleans(vs).compute(); Assertions.assertEquals(a, b); return a; } @Test public void hashBooleans() { Set<Long> hashes = new HashSet<>(); for (int i = 0; i < 1000; ++i) { boolean[] vs = randomBooleanArray(i); long h = checkBooleans(vs); Assertions.assertFalse(hashes.contains(h)); hashes.add(h); } } private String randomString(int length) { StringBuilder builder = new StringBuilder(length); for (int i = 0; i < length; ++i) { char c = (char) random.nextInt(Character.MAX_VALUE); builder.append(c); } return builder.toString(); } private long checkBytes(String str) { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); Hash64 h64 = new Hash64(); for (byte b : bytes) h64.updateByte(b); long a = h64.computeAndReset(); long b = h64.updateBytes(bytes).computeAndReset(); Assertions.assertEquals(a, b, "input: " + str+ ", " + bytes.length); for (int i = 0; i < bytes.length; i += 7) { int length = Math.min(7, bytes.length - i); h64.updateBytes(bytes, i, length); } long c = h64.compute(); Assertions.assertEquals(a, c); return a; } @Test public void hashBytes() { Map<Long, String> hashes = new HashMap<>(); for (int i = 0; i < 1000; ++i) { String str = randomString(i); long h = checkBytes(str); Assertions.assertFalse(hashes.containsKey(h), () -> "[" + str + "] and [" + hashes.get(h) + "] have same hash value, h = " + h ); hashes.put(h, str); } } private long checkString(String str) { long a = new Hash64().updateString(str).compute(); long b = new Hash64().updateChars(str.toCharArray()).compute(); long c = new Hash64() .updateString(new StringBuilder().append(str)) .compute(); Assertions.assertEquals(a, b); Assertions.assertEquals(a, c); return a; } @Test public void hashString() { Map<Long, String> hashes = new HashMap<>(); for (int i = 0; i < 1000; ++i) { String str = randomString(i); long h = checkString(str); Assertions.assertFalse(hashes.containsKey(h), () -> "[" + str + "] and [" + hashes.get(h) + "] have same hash value, h = " + h ); hashes.put(h, str); } } private short[] randomShortArray(int length) { short[] vs = new short[length]; for (int i = 0; i < length; ++i) { vs[i] = (short) random.nextInt(Short.MAX_VALUE); } return vs; } private long checkShorts(short[] vs) { Hash64 h64 = new Hash64(); for (short v : vs) h64.updateShort(v); long a = h64.computeAndReset(); long b = h64.updateShorts(vs).compute(); Assertions.assertEquals(a, b); return a; } @Test public void hashShorts() { Set<Long> hashes = new HashSet<>(); for (int i = 0; i < 1000; ++i) { short[] vs = randomShortArray(i); long h = checkShorts(vs); Assertions.assertFalse(hashes.contains(h)); hashes.add(h); } } private int[] randomIntArray(int length) { int[] vs = new int[length]; for (int i = 0; i < length; ++i) { vs[i] = random.nextInt(); } return vs; } private long checkInts(int[] vs) { Hash64 h64 = new Hash64(); for (int v : vs) h64.updateInt(v); long a = h64.computeAndReset(); long b = h64.updateInts(vs).compute(); Assertions.assertEquals(a, b); return a; } @Test public void hashInts() { Set<Long> hashes = new HashSet<>(); for (int i = 0; i < 1000; ++i) { int[] vs = randomIntArray(i); long h = checkInts(vs); Assertions.assertFalse(hashes.contains(h)); hashes.add(h); } } @Test public void hashLong() { // Sanity check implementation with openhft version final LongHashFunction xx64 = LongHashFunction.xx(); final Hash64 h64 = new Hash64(); for (int i = 0; i < 1; ++i) { long v = random.nextLong(); long h = h64.updateLong(v).computeAndReset(); Assertions.assertEquals(xx64.hashLong(v), h); } } private long[] randomLongArray(int length) { long[] vs = new long[length]; for (int i = 0; i < length; ++i) { vs[i] = random.nextLong(); } return vs; } @Test public void hashLongs() { // Sanity check implementation with openhft version final LongHashFunction xx64 = LongHashFunction.xx(); final Hash64 h64 = new Hash64(); for (int i = 0; i < 1000; ++i) { long[] vs = randomLongArray(i); long h = h64.updateLongs(vs).computeAndReset(); Assertions.assertEquals(xx64.hashLongs(vs), h); } } private float[] randomFloatArray(int length) { float[] vs = new float[length]; for (int i = 0; i < length; ++i) { vs[i] = random.nextFloat(); } return vs; } private long checkFloats(float[] vs) { Hash64 h64 = new Hash64(); for (float v : vs) h64.updateFloat(v); long a = h64.computeAndReset(); long b = h64.updateFloats(vs).compute(); Assertions.assertEquals(a, b); return a; } @Test public void hashFloats() { Set<Long> hashes = new HashSet<>(); for (int i = 0; i < 1000; ++i) { float[] vs = randomFloatArray(i); long h = checkFloats(vs); Assertions.assertFalse(hashes.contains(h)); hashes.add(h); } } private double[] randomDoubleArray(int length) { double[] vs = new double[length]; for (int i = 0; i < length; ++i) { vs[i] = random.nextDouble(); } return vs; } private long checkDoubles(double[] vs) { Hash64 h64 = new Hash64(); for (double v : vs) h64.updateDouble(v); long a = h64.computeAndReset(); long b = h64.updateDoubles(vs).compute(); Assertions.assertEquals(a, b); return a; } @Test public void hashDoubles() { Set<Long> hashes = new HashSet<>(); for (int i = 0; i < 1000; ++i) { double[] vs = randomDoubleArray(i); long h = checkDoubles(vs); Assertions.assertFalse(hashes.contains(h)); hashes.add(h); } } }
5,666
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/PatternExprTest.java
/* * Copyright 2014-2022 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.spectator.impl; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; public class PatternExprTest { private List<PatternExpr> list(PatternExpr... exprs) { return Arrays.asList(exprs); } private PatternExpr sampleExpr() { return new PatternExpr.And(list( new PatternExpr.Not( new PatternExpr.And(list( new PatternExpr.Regex(PatternMatcher.compile("a")), new PatternExpr.Regex(PatternMatcher.compile("b")) )) ), new PatternExpr.Or(list( new PatternExpr.Regex(PatternMatcher.compile("c")), new PatternExpr.Regex(PatternMatcher.compile("d")), new PatternExpr.Regex(PatternMatcher.compile("e")) )), new PatternExpr.Or(list( new PatternExpr.Regex(PatternMatcher.compile("f")) )), new PatternExpr.And(list( new PatternExpr.Regex(PatternMatcher.compile("g")) )) )); } @Test public void infix() { PatternExpr.Encoder encoder = new PatternExpr.Encoder() { @Override public String regex(PatternMatcher matcher) { return "'" + matcher + "'"; } @Override public String startAnd() { return "("; } @Override public String separatorAnd() { return " AND "; } @Override public String endAnd() { return ")"; } @Override public String startOr() { return "("; } @Override public String separatorOr() { return " OR "; } @Override public String endOr() { return ")"; } @Override public String startNot() { return "NOT "; } @Override public String endNot() { return ""; } }; String query = sampleExpr().toQueryString(encoder); Assertions.assertEquals("(NOT ('.*a' AND '.*b') AND ('.*c' OR '.*d' OR '.*e') AND '.*f' AND '.*g')", query); } @Test public void postfix() { PatternExpr.Encoder encoder = new PatternExpr.Encoder() { @Override public String regex(PatternMatcher matcher) { return matcher + ",:re"; } @Override public String startAnd() { return "(,"; } @Override public String separatorAnd() { return ","; } @Override public String endAnd() { return ",),:and"; } @Override public String startOr() { return "(,"; } @Override public String separatorOr() { return ","; } @Override public String endOr() { return ",),:or"; } @Override public String startNot() { return ""; } @Override public String endNot() { return ",:not"; } }; String query = sampleExpr().toQueryString(encoder); Assertions.assertEquals("(,(,.*a,:re,.*b,:re,),:and,:not,(,.*c,:re,.*d,:re,.*e,:re,),:or,.*f,:re,.*g,:re,),:and", query); } @Test public void functions() { PatternExpr.Encoder encoder = new PatternExpr.Encoder() { @Override public String regex(PatternMatcher matcher) { return "'" + matcher + "'"; } @Override public String startAnd() { return "and("; } @Override public String separatorAnd() { return ","; } @Override public String endAnd() { return ")"; } @Override public String startOr() { return "or("; } @Override public String separatorOr() { return ","; } @Override public String endOr() { return ")"; } @Override public String startNot() { return "not("; } @Override public String endNot() { return ")"; } }; String query = sampleExpr().toQueryString(encoder); Assertions.assertEquals("and(not(and('.*a','.*b')),or('.*c','.*d','.*e'),'.*f','.*g')", query); } @Test public void equalsContractRegex() { EqualsVerifier.forClass(PatternExpr.Regex.class) .withNonnullFields("matcher") .verify(); } @Test public void equalsContractAnd() { EqualsVerifier.forClass(PatternExpr.And.class) .withNonnullFields("exprs") .verify(); } @Test public void equalsContractOr() { EqualsVerifier.forClass(PatternExpr.Or.class) .withNonnullFields("exprs") .verify(); } @Test public void equalsContractNot() { EqualsVerifier.forClass(PatternExpr.Not.class) .withNonnullFields("expr") .verify(); } @Test public void indexOfNegativeLookahead() { PatternExpr expr = PatternMatcher.compile("foo-(?!bar)").toPatternExpr(50); Assertions.assertEquals("(NOT '.*foo-bar' AND '.*foo-')", expr.toString()); } @Test public void indexOfPositiveLookahead() { PatternExpr expr = PatternMatcher.compile("foo-(?=bar)").toPatternExpr(50); Assertions.assertEquals("('.*foo-bar' AND '.*foo-')", expr.toString()); } @Test public void seqNegativeLookahead() { PatternExpr expr = PatternMatcher.compile("foo-(?!bar)(?!baz)").toPatternExpr(50); Assertions.assertEquals( "(NOT '.*foo-bar' AND NOT '.*foo-baz' AND '.*foo-')", expr.toString()); } @Test public void seqPositiveLookahead() { PatternExpr expr = PatternMatcher.compile("foo-(?=bar)(?=baz)").toPatternExpr(50); Assertions.assertEquals( "('.*foo-bar' AND '.*foo-baz' AND '.*foo-')", expr.toString()); } @Test public void repeatedNegativeLookahead() { PatternExpr expr = PatternMatcher.compile("(foo(?!bar)){4}").toPatternExpr(50); Assertions.assertNull(expr); } @Test public void repeatedPositiveLookahead() { PatternExpr expr = PatternMatcher.compile("(foo(?=bar)){4}").toPatternExpr(50); Assertions.assertNull(expr); } @Test public void zeroOrMoreRepeatedNegativeLookahead() { PatternExpr expr = PatternMatcher.compile("((?!bar)foo)*baz").toPatternExpr(50); Assertions.assertNull(expr); } @Test public void zeroOrMoreRepeatedPositiveLookahead() { PatternExpr expr = PatternMatcher.compile("((?=bar)foo)*baz").toPatternExpr(50); Assertions.assertNull(expr); } @Test public void zeroOrMoreNextNegativeLookahead() { PatternExpr expr = PatternMatcher.compile("(foo-)*(?!bar)").toPatternExpr(50); Assertions.assertEquals("(NOT '(.)*(foo-)*bar' AND '(.)*(foo-)*')", expr.toString()); } @Test public void zeroOrMoreNextPositiveLookahead() { PatternExpr expr = PatternMatcher.compile("(foo-)*(?=bar)").toPatternExpr(50); Assertions.assertEquals("('(.)*(foo-)*bar' AND '(.)*(foo-)*')", expr.toString()); } @Test public void zeroOrOneRepeatedNegativeLookahead() { PatternExpr expr = PatternMatcher.compile("((?!bar)foo)?baz").toPatternExpr(50); Assertions.assertNull(expr); } @Test public void zeroOrOneRepeatedPositiveLookahead() { PatternExpr expr = PatternMatcher.compile("((?=bar)foo)?baz").toPatternExpr(50); Assertions.assertNull(expr); } @Test public void zeroOrOneNextNegativeLookahead() { PatternExpr expr = PatternMatcher.compile("(foo-)?(?!bar)").toPatternExpr(50); Assertions.assertEquals("(NOT '(.)*(?:foo-)?bar' AND '(.)*(?:foo-)?')", expr.toString()); } @Test public void zeroOrOneNextPositiveLookahead() { PatternExpr expr = PatternMatcher.compile("(foo-)?(?=bar)").toPatternExpr(50); Assertions.assertEquals("('(.)*(?:foo-)?bar' AND '(.)*(?:foo-)?')", expr.toString()); } }
5,667
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/AsciiSetTest.java
/* * Copyright 2014-2019 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.spectator.impl; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class AsciiSetTest { @Test public void empty() { AsciiSet s = AsciiSet.fromPattern(""); Assertions.assertEquals("", s.toString()); } @Test public void nonAsciiPattern() { Assertions.assertThrows(IllegalArgumentException.class, () -> AsciiSet.fromPattern("\u26A0")); } @Test public void patternEndOfAscii() { AsciiSet s = AsciiSet.fromPattern("\u007F"); Assertions.assertEquals("\u007F", s.toString()); } @Test public void rangeToString() { AsciiSet s1 = AsciiSet.fromPattern("A-C"); AsciiSet s2 = AsciiSet.fromPattern("ABC"); Assertions.assertEquals("A-C", s2.toString()); Assertions.assertEquals(s1, s2); } @Test public void rangeShortToString() { AsciiSet s1 = AsciiSet.fromPattern("A-B"); AsciiSet s2 = AsciiSet.fromPattern("AB"); Assertions.assertEquals("AB", s1.toString()); Assertions.assertEquals(s1, s2); } @Test public void rangeContains() { AsciiSet s = AsciiSet.fromPattern("A-C"); Assertions.assertTrue(s.contains('A')); Assertions.assertFalse(s.contains('D')); Assertions.assertFalse(s.contains('-')); } @Test public void rangeContainsAll() { AsciiSet s = AsciiSet.fromPattern("A-C"); Assertions.assertTrue(s.containsAll("BCAAABCBCBB")); Assertions.assertFalse(s.containsAll("BCAAABCBCBBD")); } @Test public void dash() { AsciiSet s = AsciiSet.fromPattern("-"); Assertions.assertTrue(s.contains('-')); Assertions.assertFalse(s.contains('A')); } @Test public void dashStart() { AsciiSet s = AsciiSet.fromPattern("-A-C"); Assertions.assertTrue(s.contains('-')); Assertions.assertTrue(s.contains('B')); Assertions.assertFalse(s.contains('D')); } @Test public void dashEnd() { AsciiSet s = AsciiSet.fromPattern("A-C-"); Assertions.assertTrue(s.contains('-')); Assertions.assertTrue(s.contains('B')); Assertions.assertFalse(s.contains('D')); } @Test public void multiRangeContains() { AsciiSet s = AsciiSet.fromPattern("0-2A-C"); Assertions.assertTrue(s.containsAll("012ABC")); Assertions.assertFalse(s.containsAll("3")); Assertions.assertFalse(s.contains('-')); } @Test public void tab() { AsciiSet s = AsciiSet.fromPattern("\t"); Assertions.assertTrue(s.contains('\t')); Assertions.assertFalse(s.contains(' ')); } @Test public void badReplacement() { Assertions.assertThrows(IllegalArgumentException.class, () -> { AsciiSet s = AsciiSet.fromPattern("0-2A-C"); s.replaceNonMembers("012ABC", '*'); }); } @Test public void replaceAllOk() { AsciiSet s = AsciiSet.fromPattern("*0-2A-C"); Assertions.assertEquals("012ABC", s.replaceNonMembers("012ABC", '*')); } @Test public void replace() { AsciiSet s = AsciiSet.fromPattern("*0-2A-C"); Assertions.assertEquals("012*ABC*", s.replaceNonMembers("0123ABCD", '*')); } @Test public void replaceNullChar() { AsciiSet s = AsciiSet.fromPattern("*A-Z"); Assertions.assertEquals("ABC*DEF", s.replaceNonMembers("ABC\u0000DEF", '*')); } @Test public void replaceMultiCharUnicode() { // http://www.fileformat.info/info/unicode/char/1f701/index.htm AsciiSet s = AsciiSet.fromPattern("_"); String str = new String(Character.toChars(0x1F701)); Assertions.assertEquals(2, str.length()); Assertions.assertEquals("__", s.replaceNonMembers(str, '_')); } @Test public void replaceBoundaries() { AsciiSet s = AsciiSet.fromPattern("_"); String str = "\u0000\u0080\uFFFF"; Assertions.assertEquals(3, str.length()); Assertions.assertEquals("___", s.replaceNonMembers(str, '_')); } @Test public void equalsContractTest() { EqualsVerifier .forClass(AsciiSet.class) .suppress(Warning.NULL_FIELDS) .verify(); } }
5,668
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/StepDoubleTest.java
/* * Copyright 2014-2019 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.spectator.impl; import com.netflix.spectator.api.ManualClock; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class StepDoubleTest { private final ManualClock clock = new ManualClock(); @BeforeEach public void init() { clock.setWallTime(0L); } @Test public void empty() { StepDouble v = new StepDouble(0.0, clock, 10L); Assertions.assertEquals(0.0, v.getCurrent().get(), 1e-12); Assertions.assertEquals(0.0, v.poll(), 1e-12); } @Test public void increment() { StepDouble v = new StepDouble(0.0, clock, 10L); v.getCurrent().addAndGet(1.0); Assertions.assertEquals(1.0, v.getCurrent().get(), 1e-12); Assertions.assertEquals(0.0, v.poll(), 1e-12); } @Test public void incrementAndCrossStepBoundary() { StepDouble v = new StepDouble(0.0, clock, 10L); v.getCurrent().addAndGet(1.0); clock.setWallTime(10L); Assertions.assertEquals(0.0, v.getCurrent().get(), 1e-12); Assertions.assertEquals(1.0, v.poll(), 1e-12); } @Test public void missedRead() { StepDouble v = new StepDouble(0.0, clock, 10L); v.getCurrent().addAndGet(1.0); clock.setWallTime(20L); Assertions.assertEquals(0.0, v.getCurrent().get(), 1e-12); Assertions.assertEquals(0.0, v.poll(), 1e-12); } }
5,669
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/AtomicDoubleTest.java
/* * Copyright 2014-2019 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.spectator.impl; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class AtomicDoubleTest { @Test public void init() { AtomicDouble v = new AtomicDouble(); Assertions.assertEquals(0.0, v.get(), 1e-12); } @Test public void initWithValue() { AtomicDouble v = new AtomicDouble(42.0); Assertions.assertEquals(42.0, v.get(), 1e-12); } @Test public void set() { AtomicDouble v = new AtomicDouble(13.0); v.set(42.0); Assertions.assertEquals(42.0, v.get(), 1e-12); } @Test public void getAndSet() { AtomicDouble v = new AtomicDouble(13.0); Assertions.assertEquals(13.0, v.getAndSet(42.0), 1e-12); Assertions.assertEquals(42.0, v.get(), 1e-12); } @Test public void compareAndSet() { AtomicDouble v = new AtomicDouble(13.0); Assertions.assertTrue(v.compareAndSet(13.0, 42.0)); Assertions.assertEquals(42.0, v.get(), 1e-12); } @Test public void compareAndSetFail() { AtomicDouble v = new AtomicDouble(13.0); Assertions.assertFalse(v.compareAndSet(12.0, 42.0)); Assertions.assertEquals(13.0, v.get(), 1e-12); } @Test public void addAndGet() { AtomicDouble v = new AtomicDouble(13.0); Assertions.assertEquals(55.0, v.addAndGet(42.0), 1e-12); Assertions.assertEquals(55.0, v.get(), 1e-12); } @Test public void getAndAdd() { AtomicDouble v = new AtomicDouble(13.0); Assertions.assertEquals(13.0, v.getAndAdd(42.0), 1e-12); Assertions.assertEquals(55.0, v.get(), 1e-12); } @Test public void maxGt() { AtomicDouble v = new AtomicDouble(0.0); v.max(2.0); Assertions.assertEquals(2.0, v.get(), 1e-12); } @Test public void maxLt() { AtomicDouble v = new AtomicDouble(2.0); v.max(0.0); Assertions.assertEquals(2.0, v.get(), 1e-12); } @Test public void maxNegative() { AtomicDouble v = new AtomicDouble(-42.0); v.max(-41.0); Assertions.assertEquals(-41.0, v.get(), 1e-12); } @Test public void maxNaN() { AtomicDouble v = new AtomicDouble(Double.NaN); v.max(0.0); Assertions.assertEquals(0.0, v.get(), 1e-12); } @Test public void maxValueNaN() { AtomicDouble v = new AtomicDouble(0.0); v.max(Double.NaN); Assertions.assertEquals(0.0, v.get(), 1e-12); } @Test public void maxNegativeNaN() { AtomicDouble v = new AtomicDouble(Double.NaN); v.max(-42.0); Assertions.assertEquals(-42.0, v.get(), 1e-12); } @Test public void maxValueInfinity() { AtomicDouble v = new AtomicDouble(0.0); v.max(Double.POSITIVE_INFINITY); Assertions.assertEquals(0.0, v.get(), 1e-12); } }
5,670
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/LfuCacheTest.java
/* * Copyright 2014-2019 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.spectator.impl; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class LfuCacheTest { private Registry registry; @BeforeEach public void before() { registry = new DefaultRegistry(); } private long hits() { return registry .counter("spectator.cache.requests", "id", "test", "result", "hit") .count(); } private long misses() { return registry .counter("spectator.cache.requests", "id", "test", "result", "miss") .count(); } private long compactions() { return registry .counter("spectator.cache.compactions", "id", "test") .count(); } private Cache<String, String> create(int baseSize, int compactionSize) { return Cache.lfu(registry, "test", baseSize, compactionSize); } private String[] createTestData() { int n = 10000; String[] values = new String[n]; int i = 0; int amount = 140; // should have ~98% hit rate with base size > 140 while (i < n && amount > 0) { String v = UUID.randomUUID().toString(); for (int j = 0; j < amount; ++j) { values[i] = v; ++i; } --amount; } for (; i < values.length; ++i) { values[i] = UUID.randomUUID().toString(); } List<String> list = Arrays.asList(values); Collections.shuffle(list); return list.toArray(new String[0]); } @Test public void computeIfAbsent() { Cache<String, String> cache = create(1, 2); Assertions.assertEquals("A", cache.computeIfAbsent("a", String::toUpperCase)); Assertions.assertEquals(0, hits()); Assertions.assertEquals(1, misses()); } @Test public void computeIfAbsentRepeat() { Cache<String, String> cache = create(1, 2); Assertions.assertEquals("A", cache.computeIfAbsent("a", String::toUpperCase)); Assertions.assertEquals("A", cache.computeIfAbsent("a", s -> { // Shouldn't get called since key is cached throw new RuntimeException("fail"); })); Assertions.assertEquals(1, hits()); Assertions.assertEquals(1, misses()); } @Test public void computeIfAbsentCompaction() { Cache<String, String> cache = create(1, 2); Assertions.assertEquals("A", cache.computeIfAbsent("a", String::toUpperCase)); Assertions.assertEquals("B", cache.computeIfAbsent("b", String::toUpperCase)); Assertions.assertEquals("B", cache.computeIfAbsent("b", String::toUpperCase)); Assertions.assertEquals(2, cache.size()); Assertions.assertEquals("C", cache.computeIfAbsent("c", String::toUpperCase)); Assertions.assertEquals(1, hits()); Assertions.assertEquals(3, misses()); Assertions.assertEquals(1, compactions()); Assertions.assertEquals(1, cache.size()); Map<String, String> expected = new HashMap<>(); expected.put("b", "B"); Assertions.assertEquals(expected, cache.asMap()); } @Test public void computeIfAbsentHitRate() { Cache<String, String> cache = create(100, 1000); for (String s : createTestData()) { cache.computeIfAbsent(s, String::toUpperCase); } Assertions.assertEquals(9730, hits()); Assertions.assertEquals(270, misses()); Assertions.assertEquals(0, compactions()); } }
5,671
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/StepLongTest.java
/* * Copyright 2014-2019 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.spectator.impl; import com.netflix.spectator.api.ManualClock; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class StepLongTest { private final ManualClock clock = new ManualClock(); @BeforeEach public void init() { clock.setWallTime(0L); } @Test public void empty() { StepLong v = new StepLong(0L, clock, 10L); Assertions.assertEquals(0L, v.getCurrent().get()); Assertions.assertEquals(0L, v.poll()); } @Test public void increment() { StepLong v = new StepLong(0L, clock, 10L); v.getCurrent().incrementAndGet(); Assertions.assertEquals(1L, v.getCurrent().get()); Assertions.assertEquals(0L, v.poll()); } @Test public void incrementAndCrossStepBoundary() { StepLong v = new StepLong(0L, clock, 10L); v.getCurrent().incrementAndGet(); clock.setWallTime(10L); Assertions.assertEquals(0L, v.getCurrent().get()); Assertions.assertEquals(1L, v.poll()); } @Test public void missedRead() { StepLong v = new StepLong(0L, clock, 10L); v.getCurrent().incrementAndGet(); clock.setWallTime(20L); Assertions.assertEquals(0L, v.getCurrent().get()); Assertions.assertEquals(0L, v.poll()); } }
5,672
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/ToSqlPatternTest.java
/* * Copyright 2014-2020 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class ToSqlPatternTest { @Test public void any() { String sql = PatternMatcher.compile(".*").toSqlPattern(); Assertions.assertEquals("%", sql); } @Test public void single() { String sql = PatternMatcher.compile("^.$").toSqlPattern(); Assertions.assertEquals("_", sql); } @Test public void exactSeq() { String sql = PatternMatcher.compile("^abc$").toSqlPattern(); Assertions.assertEquals("abc", sql); } @Test public void indexOf() { String sql = PatternMatcher.compile(".*foo.*").toSqlPattern(); Assertions.assertEquals("%foo%", sql); } @Test public void indexOfImplicit() { String sql = PatternMatcher.compile("foo").toSqlPattern(); Assertions.assertEquals("%foo%", sql); } @Test public void startsWith() { String sql = PatternMatcher.compile("^foo.*").toSqlPattern(); Assertions.assertEquals("foo%", sql); } @Test public void endsWith() { String sql = PatternMatcher.compile(".*foo$").toSqlPattern(); Assertions.assertEquals("%foo", sql); } @Test public void combination() { String sql = PatternMatcher.compile(".*foo.*bar.baz.*").toSqlPattern(); Assertions.assertEquals("%foo%bar_baz%", sql); } @Test public void escaping() { String sql = PatternMatcher.compile(".*foo_bar%baz.*").toSqlPattern(); Assertions.assertEquals("%foo\\_bar\\%baz%", sql); } @Test public void tooComplex() { String sql = PatternMatcher.compile(".*foo_(bar|baz).*").toSqlPattern(); Assertions.assertNull(sql); } }
5,673
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/MatcherSerializationTest.java
/* * Copyright 2014-2019 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.spectator.impl.matcher; import com.netflix.spectator.impl.AsciiSet; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class MatcherSerializationTest { static void checkSerde(PatternMatcher matcher) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(baos)) { out.writeObject(matcher); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); try (ObjectInputStream in = new ObjectInputStream(bais)) { PatternMatcher deserialized = (PatternMatcher) in.readObject(); Assertions.assertEquals(matcher, deserialized); } } catch (Exception e) { throw new RuntimeException(e); } } @Test public void any() { checkSerde(AnyMatcher.INSTANCE); } @Test public void charClass() { checkSerde(new CharClassMatcher(AsciiSet.fromPattern("abc"))); } @Test public void charSeq() { checkSerde(new CharSeqMatcher("abc")); } @Test public void end() { checkSerde(EndMatcher.INSTANCE); } @Test public void falseMatcher() { checkSerde(FalseMatcher.INSTANCE); } @Test public void ignoreCase() { checkSerde(new IgnoreCaseMatcher(EndMatcher.INSTANCE)); } @Test public void indexOf() { checkSerde(new IndexOfMatcher("abc", EndMatcher.INSTANCE)); } @Test public void negativeLookahead() { checkSerde(new NegativeLookaheadMatcher(AnyMatcher.INSTANCE)); } @Test public void or() { checkSerde(OrMatcher.create(AnyMatcher.INSTANCE, EndMatcher.INSTANCE)); } @Test public void positiveLookahead() { checkSerde(new PositiveLookaheadMatcher(AnyMatcher.INSTANCE)); } @Test public void repeat() { checkSerde(new RepeatMatcher(AnyMatcher.INSTANCE, 0, 3)); } @Test public void seq() { checkSerde(SeqMatcher.create(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE)); } @Test public void start() { checkSerde(StartMatcher.INSTANCE); } @Test public void startsWith() { checkSerde(new StartsWithMatcher("abc")); } @Test public void trueMatcher() { checkSerde(TrueMatcher.INSTANCE); } @Test public void zeroOrMore() { checkSerde(new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, EndMatcher.INSTANCE)); } }
5,674
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/TrigramsPatternMatcherTest.java
/* * Copyright 2014-2023 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import java.util.SortedSet; public class TrigramsPatternMatcherTest extends AbstractPatternMatcherTest { @Override protected void testRE(String regex, String value) { PatternMatcher matcher = PatternMatcher.compile(regex); SortedSet<String> trigrams = matcher.trigrams(); // Trigrams should be more lenient than the actual pattern, so anything that is matched // by the pattern must be a possible match with the trigrams. if (matcher.matches(value)) { Assertions.assertTrue(couldMatch(trigrams, value)); } } private boolean couldMatch(SortedSet<String> trigrams, String value) { return trigrams.stream().allMatch(value::contains); } }
5,675
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/AbstractPatternMatcherTest.java
/* * Copyright 2014-2022 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public abstract class AbstractPatternMatcherTest { protected abstract void testRE(String regex, String value); private void intercept(Class<? extends Throwable> cls, String message, Runnable task) { try { task.run(); Assertions.fail("expected " + cls.getName() + " but no exception was thrown"); } catch (Throwable t) { if (!cls.isAssignableFrom(t.getClass())) { String error = "expected " + cls.getName() + " but received " + t.getClass().getName(); throw new AssertionError(error, t); } if (message != null) { // Ignore context of the message String actual = t.getMessage().split("\n")[0]; Assertions.assertEquals(message, actual); } } } private void testBadExpression(String regex, String message) { //Pattern.compile(regex); intercept(IllegalArgumentException.class, message, () -> PatternMatcher.compile(regex)); } private void testUnsupported(String regex, String message) { intercept(UnsupportedOperationException.class, message, () -> PatternMatcher.compile(regex)); } @Test public void prefix() { Assertions.assertEquals("abc", PatternMatcher.compile("^abc").prefix()); Assertions.assertNull(PatternMatcher.compile("abc").prefix()); Assertions.assertEquals("abc", PatternMatcher.compile("^(abc)").prefix()); Assertions.assertEquals("abc", PatternMatcher.compile("^(abc|abcdef)").prefix()); Assertions.assertEquals("abc", PatternMatcher.compile("^[a][b][c]").prefix()); Assertions.assertEquals("abc", PatternMatcher.compile("^[a][b][c]+").prefix()); } @Test public void startAnchor() { testRE("^abc", "abcdef"); testRE("^abc", "123456"); testRE("^abc^def", "def"); } @Test public void isStartAnchored() { Assertions.assertTrue(PatternMatcher.compile("^abc").isStartAnchored()); Assertions.assertTrue(PatternMatcher.compile("^[a-z]").isStartAnchored()); Assertions.assertTrue(PatternMatcher.compile("(^a|^b)").isStartAnchored()); Assertions.assertFalse(PatternMatcher.compile("(^a|b)").isStartAnchored()); Assertions.assertFalse(PatternMatcher.compile("abc").isStartAnchored()); } @Test public void endAnchor() { testRE("def$", "abcdef"); testRE("def$", "123456"); } @Test public void isEndAnchored() { Assertions.assertTrue(PatternMatcher.compile("abc$").isEndAnchored()); Assertions.assertTrue(PatternMatcher.compile("[a-z]$").isEndAnchored()); Assertions.assertTrue(PatternMatcher.compile("(a|b)$").isEndAnchored()); Assertions.assertFalse(PatternMatcher.compile("(a$|b)").isEndAnchored()); Assertions.assertFalse(PatternMatcher.compile("abc").isEndAnchored()); } @Test public void alwaysMatches() { Assertions.assertTrue(PatternMatcher.compile(".*").alwaysMatches()); Assertions.assertFalse(PatternMatcher.compile(".?").alwaysMatches()); Assertions.assertFalse(PatternMatcher.compile("$.").alwaysMatches()); } @Test public void neverMatches() { Assertions.assertFalse(PatternMatcher.compile(".*").neverMatches()); Assertions.assertFalse(PatternMatcher.compile(".?").neverMatches()); Assertions.assertTrue(PatternMatcher.compile("$.").neverMatches()); } @Test public void exact() { testRE("^abc$", "abc"); testRE("^abc$", "abcd"); testRE("^abc$", "abd"); testRE("^abc$", "123"); } @Test public void indexOf() { testRE(".*abc", "abc"); testRE(".*abc", " abc"); testRE(".*abc.*", " abc "); } @Test public void substr() { testRE("abc", "12345 abc 67890"); } @Test public void glob() { testRE("^*.abc", "12345 abc 67890"); testRE("^*abc", "12345 abc 67890"); } @Test public void danglingModifier() { testBadExpression("?:?abc", "dangling modifier"); testBadExpression("*abc", "dangling modifier"); testBadExpression("+abc", "dangling modifier"); } @Test public void unclosedCharClass() { // unclosed character class, closing brace as first character will be treated as part // of the set testBadExpression("[]", "unclosed character class"); testBadExpression("[\\]", "unclosed character class"); testBadExpression("[^]", "unclosed character class"); testBadExpression("[^\\]", "unclosed character class"); testBadExpression("[", "unclosed character class"); } @Test public void oneOrMore() { testRE("a+", "abc"); testRE("^.+$", "abc"); testRE("^(.+)$", "abc"); } @Test public void numbers() { testRE("^1*", "1000"); testRE("^1*", "3110"); testRE("^1*", "3691"); testRE("^1*", "3692"); } @Test public void unicodeChars() { testRE("abc_\\u003b", "abc_\u003b"); } @Test public void predefinedCharClasses() { for (char c = 0; c < 128; ++c) { String v = "" + c; testRE("\\d", v); testRE("\\D", v); testRE("\\s", v); testRE("\\S", v); testRE("\\w", v); testRE("\\W", v); } } @Test public void posixCharClasses() { String[] names = { "Lower", "Upper", "ASCII", "Digit", "Alpha", "Alnum", "Punct", "Graph", "Print", "Blank", "Cntrl", "XDigit", "Space" }; for (char c = 0; c < 128; ++c) { String v = Character.toString(c); for (String name : names) { testRE("\\p{" + name + "}", v); testRE("\\P{" + name + "}", v); } } } @Test public void posixAbbreviations() { testBadExpression("\\pabc", "unknown character property name: a"); testBadExpression("\\pLbc", "unknown character property name: L"); } @Test public void escapeInCharClass() { testRE("abc_[\\w]+_ghi", "abc_def_ghi"); testRE("abc_[\\w-\\s]+_ghi", "abc_de f-_ghi"); testRE("abc_[\\]]+_ghi", "abc_]_ghi"); testRE("abc_[]]+_ghi", "abc_]_ghi"); testRE("abc_[de\\sf]+_ghi", "abc_ \t\ndef_ghi"); testRE("abc_[\\p{Space}9\\w]+_ghi", "abc_ \t\n9def_ghi"); testRE("abc_[\\t- ]+_ghi", "abc_ \t\n_ghi"); } @Test public void nestedCharClass() { testRE("^[a-f&&]*$", "abcdef&"); testRE("^[a-f&]*$", "abcdef&"); testRE("^[a-f[A-F]]*$", "abcdefABCDEF"); testRE("^[a-f[A-F][G-I&&[^H]]]*$", "abcdefABCDEFGI"); testRE("^[a-f[A-F][G-I&&[H]]]*$", "abcdefABCDEFH"); testRE("^[a-f[A-F][G-I&&[H]]]*$", "abcdef&"); testRE("^[a-f[A-F]]*$", "abcdef[]ABCDEF"); testRE("^[a-f[A-F[0-2]]]*$", "abcdefABCDEF012"); } @Test public void quotation() { testRE("(\\Q])(?\\${*\\E)", "])(?\\${*"); testRE("\\Q])(?\\${*\\Ef(o)o", "])(?\\${*foo"); testBadExpression("\\Q])(?\\${*", "unclosed quotation"); } @Test public void unsupportedFeatures() { testUnsupported("\\h", "horizontal whitespace class"); testUnsupported("\\H", "horizontal whitespace class"); testUnsupported("\\v", "vertical whitespace class"); testUnsupported("\\V", "vertical whitespace class"); testUnsupported("\\1", "back references"); testUnsupported("\\99", "back references"); testUnsupported("\\k<foo>", "back references"); } @Test public void endsWith() { testRE("^abc_(def|ghi)$", "abc_ghi"); testRE("^abc_(def|ghi)$", "abc_foo_ghi"); testRE("^abcd.*def$", "abcdef"); } @Test public void chained() { testRE("(a*)(b?)(b+)b{3}", "aaabbbbbbb"); } @Test public void greedyStartAndEnd() { testRE("^([^!.]+).att.com!(.+)$", "gryphon.att.com!eby"); } @Test public void or() { testRE("(ab)c|abc", "abc"); testRE("(a|b)*c|(a|ab)*c", "abc"); testRE("^a(bc+|b[eh])g|.h$", "abh"); testRE(".*abc.*|.*def.*|.*ghi.*", "ghi"); testRE("[a-z]|\\p{Lower}", "ghi"); testRE("^(\\d|\\d\\d|\\d\\d\\d)$", "123"); testRE("^(\\d|\\d\\d|\\d\\d\\d)$", "1"); } @Test public void orDedup() { testRE( "781|910|1109|1222|1223|1193|1224|1700|1436|1080|1278|1287|1698|1699|1580|1481|770|1191|1416|1605", "1710"); } @Test public void namedCapturingGroup() { testRE("(?<foo>abc)", "abc"); } @Test public void charSeqRepeat() { testRE("(abc){2,5}", "abc"); testRE("(abc){2,5}", "abcabc"); testRE("(abc){2,5}", "abcc"); testRE("(abc){2}", "abc"); testRE("(abc){2}", "abcabc"); testRE("(abc){2}", "abcc"); } @Test public void unclosedNamedCapturingGroup() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternMatcher.compile("(?<foo)")); } @Test public void unbalancedOpeningParen() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternMatcher.compile("((abc)")); } @Test public void unbalancedClosingParen() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternMatcher.compile("(abc))")); } @Test public void unknownQuantifier() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternMatcher.compile(".+*")); } @Test public void controlEscape() { Assertions.assertThrows(UnsupportedOperationException.class, () -> PatternMatcher.compile("\\cM")); } @Test public void inlineFlags() { Assertions.assertThrows(UnsupportedOperationException.class, () -> PatternMatcher.compile("(?u)abc")); } private List<String[]> loadTestFile(String name) throws Exception { List<String[]> pairs = new ArrayList<>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try (InputStream in = classLoader.getResourceAsStream(name)) { new BufferedReader(new InputStreamReader(in)) .lines() .filter(line -> line.startsWith("BE") || line.startsWith("E")) .forEach(line -> { String[] parts = line.split("\\t+"); pairs.add(new String[] { parts[1].replace("\\n", "\n"), parts[2].replace("\\n", "\n") }); }); } return pairs; } @Test public void basic() throws Exception { // Check against basic compatibility tests for re2j loadTestFile("basic.dat").forEach(pair -> testRE(pair[0], pair[1])); } @Test public void jdk() throws Exception { // Check against basic compatibility tests for jdk based on description in Pattern // javadocs: // https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html loadTestFile("jdk.dat").forEach(pair -> testRE(pair[0], pair[1])); } @Test public void zeroOrMoreEmptyOrClause() throws Exception { testRE("foo-h2(prod|)*-bar-*", "foo-h2prod-abc-v123"); testRE("foo-h2(prod|)*-bar-*", "foo-h2prod-bar-v123"); } @Test public void repeatedEmptyOrClause() throws Exception { testRE("foo-h2(prod|)+-bar-*", "foo-h2prod-abc-v123"); testRE("foo-h2(prod|)+-bar-*", "foo-h2prod-bar-v123"); } @Test public void negativeLookaheadWithOr() { testRE("foo-(?!b|c|d)", "foo-a"); testRE("foo-(?!b|c|d)", "foo-b"); testRE("foo-(?!b|c|d)", "foo-f"); } @Test public void positiveLookaheadWithOr() { testRE("foo-(?=b|c|d)", "foo-a"); testRE("foo-(?=b|c|d)", "foo-b"); testRE("foo-(?=b|c|d)", "foo-f"); } @Test public void zeroOrMoreThenOr() { testRE("a*(b|c|d)", "aaa"); testRE("a*(b|c|d)", "aab"); testRE("a*(b|c|d)", "ac"); testRE("a*(b|c|d)", "b"); testRE("a*(b|c|d)", "af"); testRE("a*(b|c|d)", "f"); } @Test public void zeroOrMoreWithOr() { testRE("(a|b|c)*d", "aaad"); testRE("(a|b|c)*d", "aaa"); testRE("(a|b|c)*d", "ababcd"); } @Test public void repeatZero() { testRE("(abc){0,3}def", "def"); testRE("(abc){0,3}def", "abcdef"); testRE("(abc){1,3}def", "def"); testRE("(abc){1,3}def", "abcdef"); } @Test public void repeatWithOr() { testRE("(a|b|c){1,3}d", "aaad"); testRE("(a|b|c){1,3}d", "aaa"); testRE("(a|b|c){1,3}d", "ababcd"); testRE("(a|b|c){1,5}d", "ababcd"); } @Test public void indexOfLookahead() { testRE("foo-(?!bar)", "foo-bar"); testRE("foo-(?!bar)", "foo-baz"); testRE("foo-(?=bar)", "foo-bar"); testRE("foo-(?=bar)", "foo-baz"); } @Test public void seqLookahead() { testRE("^[fF]oo-(?!bar)$", "foo-bar"); testRE("^[fF]oo-(?!bar)$", "foo-baz"); testRE("^[fF]oo-(?=bar)$", "foo-bar"); testRE("^[fF]oo-(?=bar)$", "foo-baz"); } @Test public void repeatLookahead() { testRE("^((?!1234)[0-9]{4}-){2,5}", "4321-1234-"); } @Test public void repeatInvalid() { Assertions.assertThrows( IllegalArgumentException.class, () -> PatternMatcher.compile("a{-1,2}")); Assertions.assertThrows( IllegalArgumentException.class, () -> PatternMatcher.compile("a{4,3}")); Assertions.assertThrows( IllegalArgumentException.class, () -> PatternMatcher.compile("a{1000,-5}")); testRE("a{0,100000}", "a"); } }
5,676
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/OptimizerTest.java
/* * Copyright 2014-2022 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.spectator.impl.matcher; import com.netflix.spectator.impl.AsciiSet; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class OptimizerTest { @Test public void removeTrueInSequence() { Matcher input = SeqMatcher.create( AnyMatcher.INSTANCE, TrueMatcher.INSTANCE, AnyMatcher.INSTANCE ); Matcher expected = SeqMatcher.create( AnyMatcher.INSTANCE, AnyMatcher.INSTANCE ); Assertions.assertEquals(expected, Optimizer.removeTrueInSequence(input)); } @Test public void sequenceWithFalseIsFalse() { Matcher input = SeqMatcher.create( AnyMatcher.INSTANCE, FalseMatcher.INSTANCE, AnyMatcher.INSTANCE ); Matcher expected = FalseMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.sequenceWithFalseIsFalse(input)); } @Test public void sequenceWithStuffAfterEndIsFalse() { Matcher input = SeqMatcher.create( AnyMatcher.INSTANCE, EndMatcher.INSTANCE, AnyMatcher.INSTANCE ); Matcher expected = FalseMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.sequenceWithStuffAfterEndIsFalse(input)); } @Test public void zeroOrMoreFalse_Repeated() { Matcher input = new ZeroOrMoreMatcher(FalseMatcher.INSTANCE, AnyMatcher.INSTANCE); Matcher expected = AnyMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.zeroOrMoreFalse(input)); } @Test public void zeroOrMoreFalse_Next() { Matcher input = new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, FalseMatcher.INSTANCE); Matcher expected = FalseMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.zeroOrMoreFalse(input)); } @Test public void zeroOrOneFalse_Repeated() { Matcher input = new ZeroOrOneMatcher(FalseMatcher.INSTANCE, AnyMatcher.INSTANCE); Matcher expected = AnyMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.zeroOrMoreFalse(input)); } @Test public void zeroOrOneFalse_Next() { Matcher input = new ZeroOrOneMatcher(AnyMatcher.INSTANCE, FalseMatcher.INSTANCE); Matcher expected = FalseMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.zeroOrMoreFalse(input)); } @Test public void convertEmptyCharClassToFalse() { Matcher input = new CharClassMatcher(AsciiSet.none()); Matcher expected = FalseMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.convertEmptyCharClassToFalse(input)); } @Test public void convertSingleCharClassToSeq() { Matcher input = new CharClassMatcher(AsciiSet.fromPattern("a")); Matcher expected = new CharSeqMatcher('a'); Assertions.assertEquals(expected, Optimizer.convertSingleCharClassToSeq(input)); } @Test public void removeStartFollowedByMatchAny() { Matcher input = SeqMatcher.create( StartMatcher.INSTANCE, new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE) ); Matcher expected = new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE); Assertions.assertEquals(expected, Optimizer.removeStartFollowedByMatchAny(input)); } @Test public void removeMatchAnyFollowedByStart() { Matcher input = new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, SeqMatcher.create( StartMatcher.INSTANCE, AnyMatcher.INSTANCE )); Matcher expected = SeqMatcher.create(StartMatcher.INSTANCE, AnyMatcher.INSTANCE); Assertions.assertEquals(expected, Optimizer.removeMatchAnyFollowedByStart(input)); } @Test public void removeMatchAnyFollowedByIndexOf() { Matcher input = new ZeroOrMoreMatcher( AnyMatcher.INSTANCE, new IndexOfMatcher("foo", TrueMatcher.INSTANCE)); Matcher expected = new IndexOfMatcher("foo", TrueMatcher.INSTANCE); Assertions.assertEquals(expected, Optimizer.removeMatchAnyFollowedByIndexOf(input)); } @Test public void removeTrailingMatchAny() { Matcher input = new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, EndMatcher.INSTANCE); Matcher expected = TrueMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.removeTrailingMatchAny(input)); } @Test public void removeSequentialMatchAny() { Matcher input = new ZeroOrMoreMatcher( AnyMatcher.INSTANCE, new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE) ); Matcher expected = new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE); Assertions.assertEquals(expected, Optimizer.removeSequentialMatchAny(input)); } @Test public void flattenNestedSequences() { Matcher input = SeqMatcher.create( SeqMatcher.create(AnyMatcher.INSTANCE), AnyMatcher.INSTANCE, SeqMatcher.create(AnyMatcher.INSTANCE, SeqMatcher.create(AnyMatcher.INSTANCE)) ); Matcher expected = SeqMatcher.create( AnyMatcher.INSTANCE, AnyMatcher.INSTANCE, AnyMatcher.INSTANCE, AnyMatcher.INSTANCE ); Assertions.assertEquals(expected, Optimizer.flattenNestedSequences(input)); } @Test public void flattenNestedOr() { Matcher input = OrMatcher.create( OrMatcher.create(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE), AnyMatcher.INSTANCE, OrMatcher.create(AnyMatcher.INSTANCE, OrMatcher.create(AnyMatcher.INSTANCE)) ); Matcher expected = OrMatcher.create( AnyMatcher.INSTANCE, AnyMatcher.INSTANCE, AnyMatcher.INSTANCE, AnyMatcher.INSTANCE, AnyMatcher.INSTANCE ); Assertions.assertEquals(expected, Optimizer.flattenNestedOr(input)); } @Test public void dedupOr() { Matcher input = OrMatcher.create( new CharSeqMatcher("a"), new CharSeqMatcher("b"), new CharSeqMatcher("a") ); Matcher expected = OrMatcher.create( new CharSeqMatcher("a"), new CharSeqMatcher("b") ); Assertions.assertEquals(expected, Optimizer.dedupOr(input)); } @Test public void removeFalseBranchesFromOr() { Matcher input = OrMatcher.create( new CharSeqMatcher("a"), FalseMatcher.INSTANCE, new CharSeqMatcher("b") ); Matcher expected = OrMatcher.create( new CharSeqMatcher("a"), new CharSeqMatcher("b") ); Assertions.assertEquals(expected, Optimizer.removeFalseBranchesFromOr(input)); } @Test public void extractPrefixFromOr() { Matcher a = new CharSeqMatcher("a"); Matcher b = new CharSeqMatcher("b"); Matcher input = OrMatcher.create( new ZeroOrMoreMatcher(a, AnyMatcher.INSTANCE), new ZeroOrMoreMatcher(a, a), new ZeroOrMoreMatcher(a, b) ); Matcher expected = SeqMatcher.create( new ZeroOrMoreMatcher(a, TrueMatcher.INSTANCE), OrMatcher.create(AnyMatcher.INSTANCE, a, b) ); Assertions.assertEquals(expected, Optimizer.extractPrefixFromOr(input)); } @Test public void inlineMatchAnyPrecedingOr() { Matcher a = new CharSeqMatcher("a"); Matcher b = new CharSeqMatcher("b"); Matcher input = new ZeroOrMoreMatcher( AnyMatcher.INSTANCE, OrMatcher.create(a, b) ); Matcher expected = OrMatcher.create( new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, a), new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, b) ); Assertions.assertEquals(expected, Optimizer.inlineMatchAnyPrecedingOr(input)); } @Test public void startsWithCharSeq() { Matcher input = SeqMatcher.create( StartMatcher.INSTANCE, new CharSeqMatcher("ab"), AnyMatcher.INSTANCE ); Matcher expected = SeqMatcher.create( new StartsWithMatcher("ab"), AnyMatcher.INSTANCE ); Assertions.assertEquals(expected, Optimizer.startsWithCharSeq(input)); } @Test public void combineCharSeqAfterStartsWith() { Matcher input = SeqMatcher.create( new StartsWithMatcher("a"), new CharSeqMatcher("b"), AnyMatcher.INSTANCE ); Matcher expected = SeqMatcher.create( new StartsWithMatcher("ab"), AnyMatcher.INSTANCE ); Assertions.assertEquals(expected, Optimizer.combineCharSeqAfterStartsWith(input)); } @Test public void combineCharSeqAfterIndexOf() { Matcher input = new IndexOfMatcher("ab", new CharSeqMatcher("cd")); Matcher expected = new IndexOfMatcher("abcd", TrueMatcher.INSTANCE); Assertions.assertEquals(expected, Optimizer.combineCharSeqAfterIndexOf(input)); } @Test public void combineAdjacentCharSeqs() { Matcher input = SeqMatcher.create( new CharSeqMatcher("a"), new CharSeqMatcher("b"), AnyMatcher.INSTANCE, new CharSeqMatcher("c"), new CharSeqMatcher("d") ); Matcher expected = SeqMatcher.create( new CharSeqMatcher("ab"), AnyMatcher.INSTANCE, new CharSeqMatcher("cd") ); Assertions.assertEquals(expected, Optimizer.combineAdjacentCharSeqs(input)); } @Test public void zeroOrMoreMergeNext() { Matcher input = SeqMatcher.create( AnyMatcher.INSTANCE, new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE), AnyMatcher.INSTANCE ); Matcher expected = SeqMatcher.create( AnyMatcher.INSTANCE, new ZeroOrMoreMatcher( AnyMatcher.INSTANCE, SeqMatcher.create(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE)) ); Assertions.assertEquals(expected, Optimizer.mergeNext(input)); } @Test public void orMergeNext() { Matcher input = SeqMatcher.create( AnyMatcher.INSTANCE, OrMatcher.create(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE), AnyMatcher.INSTANCE ); Matcher expected = SeqMatcher.create( AnyMatcher.INSTANCE, (new OrMatcher(AnyMatcher.INSTANCE, AnyMatcher.INSTANCE)).mergeNext(AnyMatcher.INSTANCE) ); Assertions.assertEquals(expected, Optimizer.mergeNext(input)); } @Test public void removeRepeatedStart() { Matcher input = new ZeroOrMoreMatcher(StartMatcher.INSTANCE, AnyMatcher.INSTANCE); Matcher expected = AnyMatcher.INSTANCE; Assertions.assertEquals(expected, Optimizer.removeRepeatedStart(input)); } @Test public void combineAdjacentStart() { Matcher input = SeqMatcher.create( StartMatcher.INSTANCE, StartMatcher.INSTANCE, StartMatcher.INSTANCE, StartMatcher.INSTANCE, AnyMatcher.INSTANCE ); Matcher expected = SeqMatcher.create(StartMatcher.INSTANCE, AnyMatcher.INSTANCE); Assertions.assertEquals(expected, Optimizer.combineAdjacentStart(input)); } @Test public void convertRepeatedAnyCharSeqToIndexOf() { Matcher input = new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, SeqMatcher.create( new CharSeqMatcher("abc"), new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, SeqMatcher.create( new CharSeqMatcher("def"), new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, TrueMatcher.INSTANCE) )) )); Matcher expected = SeqMatcher.create( new IndexOfMatcher( "abc", new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, SeqMatcher.create( new CharSeqMatcher("def"), new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, TrueMatcher.INSTANCE) )) ) ); Assertions.assertEquals(expected, Optimizer.convertRepeatedAnyCharSeqToIndexOf(input)); } @Test public void optimizeStartsWith() { PatternMatcher actual = PatternMatcher.compile("^foo"); PatternMatcher expected = new StartsWithMatcher("foo"); Assertions.assertEquals(expected, actual); } @Test public void optimizeEndStart() { PatternMatcher actual = PatternMatcher.compile("$^"); PatternMatcher expected = FalseMatcher.INSTANCE; Assertions.assertEquals(expected, actual); } @Test public void optimizeEndsWith() { PatternMatcher actual = PatternMatcher.compile(".*foo$"); PatternMatcher expected = new IndexOfMatcher("foo", EndMatcher.INSTANCE); Assertions.assertEquals(expected, actual); } @Test public void optimizeEndsWithPattern() { PatternMatcher actual = PatternMatcher.compile(".*foo.bar$"); PatternMatcher expected = new IndexOfMatcher( "foo", SeqMatcher.create( AnyMatcher.INSTANCE, new CharSeqMatcher("bar"), EndMatcher.INSTANCE ) ); Assertions.assertEquals(expected, actual); } @Test public void optimizeIndexOfSeq() { PatternMatcher actual = PatternMatcher.compile("^.*abc.*def"); PatternMatcher expected = new IndexOfMatcher( "abc", new IndexOfMatcher("def", TrueMatcher.INSTANCE) ); Assertions.assertEquals(expected, actual); } @Test public void optimizeIndexOfSeqAny() { PatternMatcher actual = PatternMatcher.compile("^.*abc.*def.*"); PatternMatcher expected = new IndexOfMatcher( "abc", new IndexOfMatcher("def", TrueMatcher.INSTANCE) ); Assertions.assertEquals(expected, actual); } @Test public void optimizeDuplicateOr() { PatternMatcher actual = PatternMatcher.compile("^(abc|a(bc)|((a)(b))c)"); PatternMatcher expected = new StartsWithMatcher("abc"); Assertions.assertEquals(expected, actual); } @Test public void optimizeOptionValue() { PatternMatcher actual = PatternMatcher.compile("^a?a"); PatternMatcher expected = SeqMatcher.create( StartMatcher.INSTANCE, new ZeroOrOneMatcher(new CharSeqMatcher("a"), new CharSeqMatcher("a")) ); Assertions.assertEquals(expected, actual); } @Test public void optimizeOrSimple() { PatternMatcher actual = PatternMatcher.compile("^abc|def|ghi"); PatternMatcher expected = OrMatcher.create( new StartsWithMatcher("abc"), new IndexOfMatcher("def", TrueMatcher.INSTANCE), new IndexOfMatcher("ghi", TrueMatcher.INSTANCE) ); Assertions.assertEquals(expected, actual); } @Test public void optimizeOrIndexOf() { PatternMatcher actual = PatternMatcher.compile("^.*abc.*|.*def.*|.*ghi*."); PatternMatcher expected = OrMatcher.create( new IndexOfMatcher("abc", TrueMatcher.INSTANCE), new IndexOfMatcher("def", TrueMatcher.INSTANCE), new IndexOfMatcher( "gh", new ZeroOrMoreMatcher(new CharSeqMatcher("i"), AnyMatcher.INSTANCE) ) ); Assertions.assertEquals(expected, actual); } @Test public void optimizeOrPrefix() { PatternMatcher actual = PatternMatcher.compile("^(abc123|abc456)"); PatternMatcher expected = SeqMatcher.create( new StartsWithMatcher("abc"), new OrMatcher(new CharSeqMatcher("123"), new CharSeqMatcher("456")) ); Assertions.assertEquals(expected, actual); } @Test public void optimizeOrPrefixPattern() { PatternMatcher actual = PatternMatcher.compile("^abc.*foo$|^abc.*bar$|^abc.*baz$"); PatternMatcher expected = SeqMatcher.create( new StartsWithMatcher("abc"), new OrMatcher( new IndexOfMatcher("foo", EndMatcher.INSTANCE), new IndexOfMatcher("bar", EndMatcher.INSTANCE), new IndexOfMatcher("baz", EndMatcher.INSTANCE) ) ); Assertions.assertEquals(expected, actual); } @Test public void optimizeOrFalse() { PatternMatcher actual = PatternMatcher.compile("abc|$foo|$bar"); PatternMatcher expected = new IndexOfMatcher("abc", TrueMatcher.INSTANCE); Assertions.assertEquals(expected, actual); } @Test public void optimizeOrFalseEmpty() { PatternMatcher actual = PatternMatcher.compile("$foo|$bar"); PatternMatcher expected = FalseMatcher.INSTANCE; Assertions.assertEquals(expected, actual); } @Test public void optimizeNegativeLookaheadOr() { PatternMatcher actual = PatternMatcher.compile("^^abc.def(?!.*(1000|1500))"); PatternMatcher expected = SeqMatcher.create( new StartsWithMatcher("abc"), AnyMatcher.INSTANCE, new CharSeqMatcher("def"), new NegativeLookaheadMatcher(new IndexOfMatcher( "1", OrMatcher.create(new CharSeqMatcher("000"), new CharSeqMatcher("500")) )) ); Assertions.assertEquals(expected, actual); } }
5,677
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/CaseInsensitivePatternMatcherTest.java
/* * Copyright 2014-2020 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import java.util.regex.Pattern; public class CaseInsensitivePatternMatcherTest extends AbstractPatternMatcherTest { private boolean shouldCheckRegex(String regex) { // Java regex has inconsistent behavior for POSIX character classes and the literal version // of the same character class. For now we skip regex that use POSIX classes. // https://bugs.openjdk.java.net/browse/JDK-8214245 // Bug was fixed in jdk15. return JavaVersion.major() < 15 && !regex.contains("\\p{") && !regex.contains("\\P{") && !regex.contains("[^"); } @Override protected void testRE(String regex, String value) { if (shouldCheckRegex(regex)) { int flags = Pattern.DOTALL | Pattern.CASE_INSENSITIVE; Pattern pattern = Pattern.compile("^.*(" + regex + ")", flags); PatternMatcher matcher = PatternMatcher.compile(regex).ignoreCase(); if (pattern.matcher(value).find()) { Assertions.assertTrue(matcher.matches(value), regex + " should match " + value); } else { Assertions.assertFalse(matcher.matches(value), regex + " shouldn't match " + value); } // Check pattern can be recreated from toString PatternMatcher actual = PatternMatcher.compile(matcher.toString()); Assertions.assertEquals(matcher, actual); } } }
5,678
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/ContainsPatternMatcherTest.java
/* * Copyright 2014-2023 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; public class ContainsPatternMatcherTest extends AbstractPatternMatcherTest { @Override protected void testRE(String regex, String value) { PatternMatcher matcher = PatternMatcher.compile(regex); String str = matcher.containedString(); // Contains should be more lenient than the actual pattern, so anything that is matched // by the pattern must be a possible match with the trigrams. if (str != null && matcher.matches(value)) { Assertions.assertTrue(value.contains(str)); } } }
5,679
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/MatcherEqualsTest.java
/* * Copyright 2014-2019 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.spectator.impl.matcher; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class MatcherEqualsTest { @Test public void any() { EqualsVerifier.forClass(AnyMatcher.class).verify(); } @Test public void charClass() { EqualsVerifier .forClass(CharClassMatcher.class) .withNonnullFields("set") .verify(); } @Test public void charSeq() { EqualsVerifier .forClass(CharSeqMatcher.class) .withNonnullFields("pattern") .verify(); } @Test public void end() { EqualsVerifier.forClass(EndMatcher.class).verify(); } @Test public void falseMatcher() { EqualsVerifier.forClass(FalseMatcher.class).verify(); } @Test public void ignoreCase() { EqualsVerifier .forClass(IgnoreCaseMatcher.class) .withNonnullFields("matcher") .verify(); } @Test public void indexOf() { EqualsVerifier .forClass(IndexOfMatcher.class) .withNonnullFields("pattern", "next") .verify(); } @Test public void negativeLookahead() { EqualsVerifier .forClass(NegativeLookaheadMatcher.class) .withNonnullFields("matcher") .verify(); } @Test public void or() { EqualsVerifier.forClass(OrMatcher.class).verify(); } @Test public void positiveLookahead() { EqualsVerifier .forClass(PositiveLookaheadMatcher.class) .withNonnullFields("matcher") .verify(); } @Test public void repeat() { EqualsVerifier .forClass(RepeatMatcher.class) .withNonnullFields("repeated") .verify(); } @Test public void seq() { EqualsVerifier.forClass(SeqMatcher.class).verify(); } @Test public void start() { EqualsVerifier.forClass(StartMatcher.class).verify(); } @Test public void startsWith() { EqualsVerifier .forClass(StartsWithMatcher.class) .withNonnullFields("pattern") .verify(); } @Test public void trueMatcher() { EqualsVerifier.forClass(TrueMatcher.class).verify(); } @Test public void zeroOrMore() { EqualsVerifier .forClass(ZeroOrMoreMatcher.class) .withNonnullFields("repeated", "next") .verify(); } @Test public void zeroOrOne() { EqualsVerifier .forClass(ZeroOrOneMatcher.class) .withNonnullFields("repeated", "next") .verify(); } }
5,680
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/TrigramsTest.java
/* * Copyright 2014-2023 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; public class TrigramsTest { @Test public void startsWith() { PatternMatcher m = PatternMatcher.compile("^abcd"); Assertions.assertEquals(sortedSet("abc", "bcd"), m.trigrams()); } @Test public void contains() { PatternMatcher m = PatternMatcher.compile(".*abcd"); Assertions.assertEquals(sortedSet("abc", "bcd"), m.trigrams()); } @Test public void endsWith() { PatternMatcher m = PatternMatcher.compile(".*abcd$"); Assertions.assertEquals(sortedSet("abc", "bcd"), m.trigrams()); } @Test public void zeroOrMore() { PatternMatcher m = PatternMatcher.compile("(abc)*def"); Assertions.assertEquals(sortedSet("def"), m.trigrams()); } @Test public void zeroOrOne() { PatternMatcher m = PatternMatcher.compile("(abc)?def"); Assertions.assertEquals(sortedSet("def"), m.trigrams()); } @Test public void oneOrMore() { PatternMatcher m = PatternMatcher.compile("(abc)+def"); Assertions.assertEquals(sortedSet("abc", "def"), m.trigrams()); } @Test public void repeat() { PatternMatcher m = PatternMatcher.compile("(abc){0,5}def"); Assertions.assertEquals(sortedSet("def"), m.trigrams()); } @Test public void repeatAtLeastOne() { PatternMatcher m = PatternMatcher.compile("(abc){1,5}def"); Assertions.assertEquals(sortedSet("abc", "def"), m.trigrams()); } @Test public void partOfSequence() { PatternMatcher m = PatternMatcher.compile(".*[0-9]abcd[efg]hij"); Assertions.assertEquals(sortedSet("abc", "bcd", "hij"), m.trigrams()); } @Test public void multiple() { PatternMatcher m = PatternMatcher.compile("^abc.*def.*ghi"); Assertions.assertEquals(sortedSet("abc", "def", "ghi"), m.trigrams()); } @Test public void orClause() { PatternMatcher matcher = PatternMatcher.compile(".*(abc|def|ghi)"); Assertions.assertEquals(Collections.emptySortedSet(), matcher.trigrams()); List<PatternMatcher> ms = matcher.expandOrClauses(5); Assertions.assertEquals(3, ms.size()); SortedSet<String> trigrams = new TreeSet<>(); for (PatternMatcher m : ms) { SortedSet<String> ts = m.trigrams(); Assertions.assertEquals(1, ts.size()); trigrams.addAll(ts); } Assertions.assertEquals(sortedSet("abc", "def", "ghi"), trigrams); } private SortedSet<String> sortedSet(String... items) { return new TreeSet<>(Arrays.asList(items)); } }
5,681
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/Re2PatternMatcherTest.java
/* * Copyright 2014-2022 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternExpr; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import java.util.regex.Pattern; public class Re2PatternMatcherTest extends AbstractPatternMatcherTest { @Override protected void testRE(String regex, String value) { PatternExpr expr = PatternMatcher.compile(regex).toPatternExpr(1000); if (expr == null) { return; } else { // Validate that all remaining patterns can be processed with RE2 expr.toQueryString(new Re2Encoder()); } Pattern pattern = Pattern.compile("^.*(" + regex + ")", Pattern.DOTALL); if (pattern.matcher(value).find()) { Assertions.assertTrue(expr.matches(value), regex + " should match " + value); } else { Assertions.assertFalse(expr.matches(value), regex + " shouldn't match " + value); } } private static class Re2Encoder implements PatternExpr.Encoder { @Override public String regex(PatternMatcher matcher) { // RE2 unicode escape is \\x{NNNN} instead of \\uNNNN String re = matcher.toString().replaceAll("\\\\u([0-9a-fA-F]{4})", "\\\\x{$1}"); com.google.re2j.Pattern p = com.google.re2j.Pattern.compile( "^.*(" + re + ")", com.google.re2j.Pattern.DOTALL ); return p.pattern(); } @Override public String startAnd() { return "("; } @Override public String separatorAnd() { return " AND "; } @Override public String endAnd() { return ")"; } @Override public String startOr() { return "("; } @Override public String separatorOr() { return " OR "; } @Override public String endOr() { return ")"; } @Override public String startNot() { return "NOT "; } @Override public String endNot() { return ""; } } }
5,682
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/JavaVersion.java
/* * Copyright 2014-2020 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.spectator.impl.matcher; import java.lang.reflect.Method; /** Helper for accessing the major Java version. */ class JavaVersion { private JavaVersion() { } /** * Return the major java version. */ static int major() { try { Method versionMethod = Runtime.class.getMethod("version"); Object version = versionMethod.invoke(null); Method majorMethod = version.getClass().getMethod("major"); return (Integer) majorMethod.invoke(version); } catch (Exception e) { // The Runtime.version() method was added in jdk9 and spectator has a minimum // version of 8. return 8; } } }
5,683
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/PatternUtilsTest.java
/* * Copyright 2014-2023 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.spectator.impl.matcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.SortedSet; import java.util.TreeSet; public class PatternUtilsTest { @Test public void expandTab() { Assertions.assertEquals("\t", PatternUtils.expandEscapedChars("\\t")); } @Test public void expandNewLine() { Assertions.assertEquals("\n", PatternUtils.expandEscapedChars("\\n")); } @Test public void expandCarriageReturn() { Assertions.assertEquals("\r", PatternUtils.expandEscapedChars("\\r")); } @Test public void expandFormFeed() { Assertions.assertEquals("\f", PatternUtils.expandEscapedChars("\\f")); } @Test public void expandAlert() { Assertions.assertEquals("\u0007", PatternUtils.expandEscapedChars("\\a")); } @Test public void expandEscape() { Assertions.assertEquals("\u001B", PatternUtils.expandEscapedChars("\\e")); } @Test public void expandSlash() { Assertions.assertEquals("\\\\", PatternUtils.expandEscapedChars("\\\\")); } @Test public void expandOctalEmpty() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternUtils.expandEscapedChars("\\0")); } @Test public void expandOctal() { for (int i = 0; i < 128; ++i) { String expected = Character.toString((char) i); String str = "\\0" + Integer.toString(i, 8); Assertions.assertEquals(expected, PatternUtils.expandEscapedChars(str)); } } @Test public void expandOctalInvalid() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternUtils.expandEscapedChars("\\0AAA")); } @Test public void expandHexLower() { for (int i = 0; i < 0xFF; ++i) { String expected = Character.toString((char) i); String str = String.format("\\x%02x", i); Assertions.assertEquals(expected, PatternUtils.expandEscapedChars(str)); } } @Test public void expandHexUpper() { for (int i = 0; i < 0xFF; ++i) { String expected = Character.toString((char) i); String str = String.format("\\x%02X", i); Assertions.assertEquals(expected, PatternUtils.expandEscapedChars(str)); } } @Test public void expandHexPartial() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternUtils.expandEscapedChars("\\xF")); } @Test public void expandHexInvalid() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternUtils.expandEscapedChars("\\xZZ")); } @Test public void expandUnicode() { for (int i = 0; i < 0xFFFF; ++i) { String expected = Character.toString((char) i); String str = String.format("\\u%04x", i); Assertions.assertEquals(expected, PatternUtils.expandEscapedChars(str)); } } @Test public void expandUnicodePartial() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternUtils.expandEscapedChars("\\u00A")); } @Test public void expandUnicodeInvalid() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternUtils.expandEscapedChars("\\uZZZZ")); } @Test public void danglingEscape() { Assertions.assertThrows(IllegalArgumentException.class, () -> PatternUtils.expandEscapedChars("\\")); } @Test public void other() { Assertions.assertEquals("\\[", PatternUtils.expandEscapedChars("\\[")); } @Test public void nonEscapedData() { Assertions.assertEquals("abc", PatternUtils.expandEscapedChars("abc")); } @Test public void escapeSpecial() { String input = "\t\n\r\f\\^$.?*+[](){}"; String expected = "\\t\\n\\r\\f\\\\\\^\\$\\.\\?\\*\\+\\[\\]\\(\\)\\{\\}"; Assertions.assertEquals(expected, PatternUtils.escape(input)); } @Test public void escapePrintable() { String special = "\t\n\r\f\\^$.?*+[](){}"; for (char i = '!'; i <= '~'; ++i) { if (special.indexOf(i) != -1) { continue; } String expected = Character.toString(i); Assertions.assertEquals(expected, PatternUtils.escape(expected)); } } @Test public void escapeControl() { String special = "\t\n\r\f"; for (int i = 0; i < '!'; ++i) { if (special.indexOf(i) != -1) { continue; } String input = Character.toString((char) i); String expected = String.format("\\u%04x", i); Assertions.assertEquals(expected, PatternUtils.escape(input)); } } @Test public void escapeDelete() { Assertions.assertEquals("\\u007f", PatternUtils.escape("\u007f")); } @Test public void computeTrigramsTooShort() { Assertions.assertEquals(Collections.emptySortedSet(), PatternUtils.computeTrigrams("")); Assertions.assertEquals(Collections.emptySortedSet(), PatternUtils.computeTrigrams("a")); Assertions.assertEquals(Collections.emptySortedSet(), PatternUtils.computeTrigrams("ab")); } private SortedSet<String> sortedSet(String... items) { return new TreeSet<>(Arrays.asList(items)); } @Test public void computeTrigrams() { Assertions.assertEquals(sortedSet("abc"), PatternUtils.computeTrigrams("abc")); Assertions.assertEquals( sortedSet("abc", "bcd", "cde", "def", "efg"), PatternUtils.computeTrigrams("abcdefg") ); } }
5,684
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/PatternMatcherTest.java
/* * Copyright 2014-2019 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import java.util.regex.Pattern; public class PatternMatcherTest extends AbstractPatternMatcherTest { @Override protected void testRE(String regex, String value) { Pattern pattern = Pattern.compile("^.*(" + regex + ")", Pattern.DOTALL); PatternMatcher matcher = PatternMatcher.compile(regex); if (pattern.matcher(value).find()) { Assertions.assertTrue(matcher.matches(value), regex + " should match " + value); } else { Assertions.assertFalse(matcher.matches(value), regex + " shouldn't match " + value); } // Check pattern can be recreated from toString PatternMatcher actual = PatternMatcher.compile(matcher.toString()); Assertions.assertEquals(matcher, actual); // Check we can serialize and deserialize the matchers MatcherSerializationTest.checkSerde(matcher); } }
5,685
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/ExpandOrTest.java
/* * Copyright 2014-2022 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ExpandOrTest { private static List<String> expand(String pattern) { return PatternMatcher.compile(pattern) .expandOrClauses(50) .stream() .map(Object::toString) .sorted() .collect(Collectors.toList()); } private static List<String> list(String... vs) { return Arrays.asList(vs); } @Test public void expandIndexOf() { Assertions.assertEquals(list(".*fooABC", ".*fooabc"), expand("foo(ABC|abc)")); } @Test public void expandNegativeLookaheadMatcher() { // OR within negative lookahead cannot be expanded without changing the // interpretation. Assertions.assertEquals(list("(.)*(?!(ABC|abc))"), expand("(?!ABC|abc)")); } @Test public void expandPositiveLookaheadMatcher() { Assertions.assertEquals(list("(.)*(?=ABC)", "(.)*(?=abc)"), expand("(?=ABC|abc)")); } @Test public void expandRepeatMatcher() { // OR within repeat cannot be expanded without changing the interpretation. Assertions.assertEquals(list("(.)*(?:((ABC)|(abc))){2,5}"), expand("(ABC|abc){2,5}")); } @Test public void expandZeroOrMoreMatcher() { // OR within repeat cannot be expanded without changing the interpretation, however, pattern // following it can be expanded. List<String> rs = expand("(ABC|abc)*(DEF|def)"); List<String> expected = list( "(.)*((ABC|abc))*DEF", "(.)*((ABC|abc))*def" ); Assertions.assertEquals(expected, rs); } @Test public void expandZeroOrOneMatcher() { List<String> rs = expand("(ABC|abc)?(DEF|def)"); List<String> expected = list( "(.)*(?:ABC)?DEF", "(.)*(?:ABC)?def", "(.)*(?:abc)?DEF", "(.)*(?:abc)?def", ".*DEF", ".*def" ); Assertions.assertEquals(expected, rs); } @Test public void expandZeroOrOneMatcherExceedsLimit() { List<PatternMatcher> rs = PatternMatcher .compile("^(ABC|abc)?(DEF|def)") .expandOrClauses(5); Assertions.assertNull(rs); } @Test public void expandZeroOrOneMatcherNoChange() { List<String> rs = expand("ab?c"); List<String> expected = list(".*a(?:b)?c"); Assertions.assertEquals(expected, rs); } @Test public void expandSeqMatcher() { List<String> rs = expand("(ABC|abc).(DEF|def)"); List<String> expected = list( ".*ABC(.DEF)", ".*ABC(.def)", ".*abc(.DEF)", ".*abc(.def)" ); Assertions.assertEquals(expected, rs); } @Test public void expandOrClauses() { List<String> rs = expand("abc(d|e(f|g|h)ijk|lm)nop(qrs|tuv)wxyz"); List<String> expected = list( ".*abcdnopqrswxyz", ".*abcdnoptuvwxyz", ".*abcefijknopqrswxyz", ".*abcefijknoptuvwxyz", ".*abcegijknopqrswxyz", ".*abcegijknoptuvwxyz", ".*abcehijknopqrswxyz", ".*abcehijknoptuvwxyz", ".*abclmnopqrswxyz", ".*abclmnoptuvwxyz" ); Assertions.assertEquals(expected, rs); } @Test public void crossProduct() { // Pattern with 26^10 expanded patterns, ~141 trillion String alpha = "(a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)"; String pattern = ""; for (int i = 0; i < 10; ++i) { pattern += alpha; } Assertions.assertNull(PatternMatcher.compile(pattern).expandOrClauses(5)); } }
5,686
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/ContainsTest.java
/* * Copyright 2014-2023 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class ContainsTest { private PatternMatcher re(String pattern) { return PatternMatcher.compile(pattern); } private void assertStartsWith(String pattern) { PatternMatcher m = re(pattern); Assertions.assertTrue(m.isPrefixMatcher(), pattern); Assertions.assertTrue(m.isContainsMatcher(), pattern); } private void assertContainsOnly(String pattern) { PatternMatcher m = re(pattern); Assertions.assertFalse(m.isPrefixMatcher(), pattern); Assertions.assertTrue(m.isContainsMatcher(), pattern); } @Test public void startsWith() { assertStartsWith("^abc"); assertStartsWith("^abc[.]def"); assertStartsWith("^abc\\.def"); } @Test public void notStartsWith() { Assertions.assertFalse(re("abc").isPrefixMatcher()); Assertions.assertFalse(re("ab[cd]").isPrefixMatcher()); Assertions.assertFalse(re("^abc.def").isPrefixMatcher()); } @Test public void contains() { assertContainsOnly("abc"); assertContainsOnly(".*abc"); assertContainsOnly("abc\\.def"); } @Test public void notContains() { Assertions.assertFalse(re("ab[cd]").isContainsMatcher()); Assertions.assertFalse(re("abc.def").isContainsMatcher()); } @Test public void containedString() { Assertions.assertEquals("abc", re("abc").containedString()); Assertions.assertEquals("abc", re(".*abc").containedString()); Assertions.assertEquals("abc", re(".*abc$").containedString()); Assertions.assertEquals("ab", re(".*ab[cd]").containedString()); Assertions.assertEquals("abc", re("abc.def").containedString()); Assertions.assertEquals("abc.def", re("abc\\.def").containedString()); Assertions.assertEquals("abc", re("^abc.def").containedString()); Assertions.assertEquals("abc.def", re("^abc\\.def").containedString()); } @Test public void containsZeroOrMore() { Assertions.assertEquals("def", re("(abc)*def").containedString()); } @Test public void containsZeroOrOne() { Assertions.assertEquals("def", re("(abc)?def").containedString()); } @Test public void containsOneOrMore() { Assertions.assertEquals("abc", re("(abc)+def").containedString()); } @Test public void containsRepeat() { Assertions.assertEquals("def", re("(abc){0,5}def").containedString()); } @Test public void containsRepeatAtLeastOne() { Assertions.assertEquals("abc", re("(abc){1,5}def").containedString()); } @Test public void containsPartOfSequence() { Assertions.assertEquals("abcd", re(".*[0-9]abcd[efg]hij").containedString()); } @Test public void containsMultiple() { Assertions.assertEquals("abc", re("^abc.*def.*ghi").containedString()); } }
5,687
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/SqlPatternMatcherTest.java
/* * Copyright 2014-2020 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class SqlPatternMatcherTest extends AbstractPatternMatcherTest { @Override protected void testRE(String regex, String value) { PatternMatcher matcher = PatternMatcher.compile(regex); String sqlPattern = PatternMatcher.compile(regex).toSqlPattern(); // hsqldb 2.6+ requires jdk11+ if (sqlPattern != null && JavaVersion.major() >= 11) { String desc = "[" + matcher + "] => [" + sqlPattern + "]"; if (matcher.matches(value)) { Assertions.assertTrue(sqlMatches(sqlPattern, value), desc + " should match " + value); } else { Assertions.assertFalse(sqlMatches(sqlPattern, value), desc + " shouldn't match " + value); } } } private boolean sqlMatches(String pattern, String value) { try { Class.forName("org.hsqldb.jdbcDriver"); try (Connection con = DriverManager.getConnection("jdbc:hsqldb:mem:test")) { try (Statement stmt = con.createStatement()) { String v = enquoteLiteral(value); String p = enquoteLiteral(pattern); stmt.executeUpdate("drop table if exists test"); stmt.executeUpdate("create table test(v varchar(255))"); stmt.executeUpdate("insert into test (v) values (" + v + ")"); String query = "select * from test where v like " + p + " escape '\\'"; try (ResultSet rs = stmt.executeQuery(query)) { return rs.next(); } } } } catch (Exception e) { throw new RuntimeException(e); } } // Corresponding method on the Statement interface wasn't added until JDK9 so we cannot // use it. private String enquoteLiteral(String str) { return "'" + str.replace("'", "''") + "'"; } }
5,688
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/impl/matcher/ExpandOrPatternMatcherTest.java
/* * Copyright 2014-2022 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.spectator.impl.matcher; import com.netflix.spectator.impl.PatternMatcher; import org.junit.jupiter.api.Assertions; import java.util.List; import java.util.regex.Pattern; public class ExpandOrPatternMatcherTest extends AbstractPatternMatcherTest { @Override protected void testRE(String regex, String value) { Pattern pattern = Pattern.compile("^.*(" + regex + ")", Pattern.DOTALL); List<PatternMatcher> matchers = PatternMatcher.compile(regex).expandOrClauses(1000); if (pattern.matcher(value).find()) { Assertions.assertTrue(matches(matchers, value), regex + " should match " + value); } else { Assertions.assertFalse(matches(matchers, value), regex + " shouldn't match " + value); } } private boolean matches(List<PatternMatcher> matchers, String value) { for (PatternMatcher m : matchers) { if (m.matches(value)) return true; } return false; } }
5,689
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/CompositeTimerTest.java
/* * Copyright 2014-2019 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class CompositeTimerTest { private final ManualClock clock = new ManualClock(); private final Id id = new DefaultId("foo"); private List<Registry> registries; private Timer newTimer() { List<Timer> ts = registries.stream() .map(r -> r.timer(id)) .collect(Collectors.toList()); return new CompositeTimer(new DefaultId("foo"), clock, ts); } private void assertCountEquals(Timer t, long expected) { Assertions.assertEquals(t.count(), expected); for (Registry r : registries) { Assertions.assertEquals(r.timer(id).count(), expected); } } private void assertTotalEquals(Timer t, long expected) { Assertions.assertEquals(t.totalTime(), expected); for (Registry r : registries) { Assertions.assertEquals(r.timer(id).totalTime(), expected); } } @BeforeEach public void init() { registries = new ArrayList<>(); for (int i = 0; i < 5; ++i) { registries.add(new DefaultRegistry(clock)); } } @Test public void empty() { Timer t = new CompositeTimer(NoopId.INSTANCE, clock, Collections.emptyList()); assertCountEquals(t, 0L); assertTotalEquals(t, 0L); t.record(1L, TimeUnit.SECONDS); assertCountEquals(t, 0L); assertTotalEquals(t, 0L); } @Test public void testInit() { Timer t = newTimer(); assertCountEquals(t, 0L); assertTotalEquals(t, 0L); } @Test public void testRecord() { Timer t = newTimer(); t.record(42, TimeUnit.MILLISECONDS); assertCountEquals(t, 1L); assertTotalEquals(t, 42000000L); } @Test public void testRecordCallable() throws Exception { Timer t = newTimer(); clock.setMonotonicTime(100L); int v = t.record(() -> { clock.setMonotonicTime(500L); return 42; }); Assertions.assertEquals(v, 42); assertCountEquals(t, 1L); assertTotalEquals(t, 400L); } @Test public void testRecordCallableException() throws Exception { Timer t = newTimer(); clock.setMonotonicTime(100L); boolean seen = false; try { t.record((Callable<Integer>) () -> { clock.setMonotonicTime(500L); throw new RuntimeException("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); assertCountEquals(t, 1L); assertTotalEquals(t, 400L); } @Test public void testRecordRunnable() throws Exception { Timer t = newTimer(); clock.setMonotonicTime(100L); t.record(() -> clock.setMonotonicTime(500L)); assertCountEquals(t, 1L); assertTotalEquals(t, 400L); } @Test public void testRecordRunnableException() throws Exception { Timer t = newTimer(); clock.setMonotonicTime(100L); boolean seen = false; try { t.record((Runnable) () -> { clock.setMonotonicTime(500L); throw new RuntimeException("foo"); }); } catch (Exception e) { seen = true; } Assertions.assertTrue(seen); assertCountEquals(t, 1L); assertTotalEquals(t, 400L); } @Test public void testMeasure() { Timer t = newTimer(); t.record(42, TimeUnit.MILLISECONDS); clock.setWallTime(3712345L); for (Measurement m : t.measure()) { Assertions.assertEquals(m.timestamp(), 3712345L); if (m.id().equals(t.id().withTag(Statistic.count))) { Assertions.assertEquals(m.value(), 1.0, 0.1e-12); } else if (m.id().equals(t.id().withTag(Statistic.totalTime))) { Assertions.assertEquals(m.value(), 42e6, 0.1e-12); } else { Assertions.fail("unexpected id: " + m.id()); } } } }
5,690
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/MeasurementTest.java
/* * Copyright 2014-2019 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.spectator.api; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class MeasurementTest { @Test public void testEqualsContract() { EqualsVerifier .forClass(Measurement.class) .suppress(Warning.NULL_FIELDS) .verify(); } @Test public void testToString() { Id id = new DefaultId("foo"); Measurement m = new Measurement(id, 42L, 42.0); Assertions.assertEquals(m.toString(), "Measurement(foo,42,42.0)"); } }
5,691
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/CompositeCounterTest.java
/* * Copyright 2014-2019 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class CompositeCounterTest { private final ManualClock clock = new ManualClock(); private final Id id = new DefaultId("foo"); private List<Registry> registries; private Counter newCounter() { List<Counter> cs = registries.stream() .map(r -> r.counter(id)) .collect(Collectors.toList()); return new CompositeCounter(id, cs); } private void assertCountEquals(Counter c, long expected) { Assertions.assertEquals(c.count(), expected); for (Registry r : registries) { Assertions.assertEquals(r.counter(id).count(), expected); } } @BeforeEach public void before() { registries = new ArrayList<>(); for (int i = 0; i < 5; ++i) { registries.add(new DefaultRegistry(clock)); } } @Test public void empty() { Counter c = new CompositeCounter(NoopId.INSTANCE, Collections.emptyList()); assertCountEquals(c, 0L); c.increment(); assertCountEquals(c, 0L); } @Test public void init() { Counter c = newCounter(); assertCountEquals(c, 0L); } @Test public void increment() { Counter c = newCounter(); c.increment(); assertCountEquals(c, 1L); c.increment(); c.increment(); assertCountEquals(c, 3L); } @Test public void incrementAmount() { Counter c = newCounter(); c.increment(42); assertCountEquals(c, 42L); } @Test public void measure() { Counter c = newCounter(); c.increment(42); clock.setWallTime(3712345L); for (Measurement m : c.measure()) { Assertions.assertEquals(m.id(), c.id()); Assertions.assertEquals(m.timestamp(), 3712345L); Assertions.assertEquals(m.value(), 42.0, 0.1e-12); } } }
5,692
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/SpectatorTest.java
/* * Copyright 2014-2019 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class SpectatorTest { @Test public void testRegistry() { Assertions.assertNotNull(Spectator.registry()); } @Test public void globalIterator() { Registry dflt = new DefaultRegistry(); CompositeRegistry global = Spectator.globalRegistry(); global.removeAll(); global.add(dflt); boolean found = false; Counter counter = dflt.counter("testCounter"); for (Meter m : global) { found |= m.id().equals(counter.id()); } Assertions.assertTrue(found, "id for sub-registry could not be found in global iterator"); } @Test public void globalIteratorWithDifferences() { Registry r1 = new DefaultRegistry(); Registry r2 = new DefaultRegistry(); CompositeRegistry global = Spectator.globalRegistry(); global.removeAll(); global.add(r1); global.add(r2); boolean found = false; Counter counter = r2.counter("testCounter"); for (Meter m : global) { found |= m.id().equals(counter.id()); } Assertions.assertTrue(found, "id for sub-registry could not be found in global iterator"); } }
5,693
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/ObjectGaugeTest.java
/* * Copyright 2014-2019 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicLong; public class ObjectGaugeTest { private final ManualClock clock = new ManualClock(); @Test public void testGC() { ObjectGauge<AtomicLong> g = new ObjectGauge<>( clock, NoopId.INSTANCE, new AtomicLong(42L), Number::doubleValue); for (Measurement m : g.measure()) { Assertions.assertEquals(m.value(), 42.0, 1e-12); } // Verify we get NaN after gc, this is quite possibly flakey and can be commented out // if needed System.gc(); Assertions.assertTrue(g.hasExpired()); for (Measurement m : g.measure()) { Assertions.assertEquals(m.value(), Double.NaN, 1e-12); } } }
5,694
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/FilteredIteratorTest.java
/* * Copyright 2014-2019 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Predicate; public class FilteredIteratorTest { private static final Predicate<String> ALL = v -> true; private static final Predicate<String> NONE = v -> false; private static final Predicate<String> EVEN = v -> Integer.parseInt(v) % 2 == 0; private static final Predicate<String> ODD = v -> !EVEN.test(v); private List<String> newList(String... vs) { List<String> data = new ArrayList<>(); Collections.addAll(data, vs); return data; } @Test public void matchesAll() { List<String> vs = newList("1", "2", "3"); List<String> out = Utils.toList(new FilteredIterator<>(vs.iterator(), ALL)); Assertions.assertEquals(vs, out); } @Test public void matchesNone() { List<String> vs = newList("1", "2", "3"); List<String> out = Utils.toList(new FilteredIterator<>(vs.iterator(), NONE)); Assertions.assertEquals(0, out.size()); } @Test public void matchesEven() { List<String> vs = newList("1", "2", "3"); List<String> out = Utils.toList(new FilteredIterator<>(vs.iterator(), EVEN)); Assertions.assertEquals(newList("2"), out); } @Test public void matchesOdd() { List<String> vs = newList("1", "2", "3"); List<String> out = Utils.toList(new FilteredIterator<>(vs.iterator(), ODD)); Assertions.assertEquals(newList("1", "3"), out); } }
5,695
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/NoopDistributionSummaryTest.java
/* * Copyright 2014-2019 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class NoopDistributionSummaryTest { @Test public void testId() { Assertions.assertEquals(NoopDistributionSummary.INSTANCE.id(), NoopId.INSTANCE); Assertions.assertFalse(NoopDistributionSummary.INSTANCE.hasExpired()); } @Test public void testIncrement() { NoopDistributionSummary t = NoopDistributionSummary.INSTANCE; t.record(42); Assertions.assertEquals(t.count(), 0L); Assertions.assertEquals(t.totalAmount(), 0L); } @Test public void testMeasure() { NoopDistributionSummary t = NoopDistributionSummary.INSTANCE; t.record(42); Assertions.assertFalse(t.measure().iterator().hasNext()); } }
5,696
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/DefaultDistributionSummaryTest.java
/* * Copyright 2014-2022 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class DefaultDistributionSummaryTest { private final ManualClock clock = new ManualClock(); @Test public void testInit() { DistributionSummary t = new DefaultDistributionSummary(clock, NoopId.INSTANCE); Assertions.assertEquals(t.count(), 0L); Assertions.assertEquals(t.totalAmount(), 0L); Assertions.assertFalse(t.hasExpired()); } @Test public void testRecord() { DistributionSummary t = new DefaultDistributionSummary(clock, NoopId.INSTANCE); t.record(42); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalAmount(), 42L); } @Test public void testRecordBatch() throws Exception { DistributionSummary t = new DefaultDistributionSummary(clock, NoopId.INSTANCE); try (DistributionSummary.BatchUpdater b = t.batchUpdater(2)) { b.record(42); b.record(42); Assertions.assertEquals(t.count(), 2L); Assertions.assertEquals(t.totalAmount(), 84L); b.record(1); } Assertions.assertEquals(t.count(), 3L); Assertions.assertEquals(t.totalAmount(), 85L); } @Test public void testRecordNegative() { DistributionSummary t = new DefaultDistributionSummary(clock, NoopId.INSTANCE); t.record(-42); Assertions.assertEquals(t.count(), 0L); Assertions.assertEquals(t.totalAmount(), 0L); } @Test public void testRecordNegativeBatch() throws Exception { DistributionSummary t = new DefaultDistributionSummary(clock, NoopId.INSTANCE); try (DistributionSummary.BatchUpdater b = t.batchUpdater(2)) { b.record(-42); } Assertions.assertEquals(t.count(), 0L); Assertions.assertEquals(t.totalAmount(), 0L); } @Test public void testRecordZero() { DistributionSummary t = new DefaultDistributionSummary(clock, NoopId.INSTANCE); t.record(0); Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalAmount(), 0L); } @Test public void testRecordZeroBatch() throws Exception { DistributionSummary t = new DefaultDistributionSummary(clock, NoopId.INSTANCE); try (DistributionSummary.BatchUpdater b = t.batchUpdater(2)) { b.record(0); } Assertions.assertEquals(t.count(), 1L); Assertions.assertEquals(t.totalAmount(), 0L); } @Test public void testMeasure() { DistributionSummary t = new DefaultDistributionSummary(clock, new DefaultId("foo")); t.record(42); clock.setWallTime(3712345L); for (Measurement m : t.measure()) { Assertions.assertEquals(m.timestamp(), 3712345L); if (m.id().equals(t.id().withTag(Statistic.count))) { Assertions.assertEquals(m.value(), 1.0, 0.1e-12); } else if (m.id().equals(t.id().withTag(Statistic.totalAmount))) { Assertions.assertEquals(m.value(), 42.0, 0.1e-12); } else { Assertions.fail("unexpected id: " + m.id()); } } } }
5,697
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/CompositeDistributionSummaryTest.java
/* * Copyright 2014-2019 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class CompositeDistributionSummaryTest { private final ManualClock clock = new ManualClock(); private final Id id = new DefaultId("foo"); private List<Registry> registries; private DistributionSummary newDistributionSummary() { List<DistributionSummary> ds = registries.stream() .map(r -> r.distributionSummary(id)) .collect(Collectors.toList()); return new CompositeDistributionSummary(id, ds); } private void assertCountEquals(DistributionSummary t, long expected) { Assertions.assertEquals(t.count(), expected); for (Registry r : registries) { Assertions.assertEquals(r.distributionSummary(id).count(), expected); } } private void assertTotalEquals(DistributionSummary t, long expected) { Assertions.assertEquals(t.totalAmount(), expected); for (Registry r : registries) { Assertions.assertEquals(r.distributionSummary(id).totalAmount(), expected); } } @BeforeEach public void init() { registries = new ArrayList<>(); for (int i = 0; i < 5; ++i) { registries.add(new DefaultRegistry(clock)); } } @Test public void empty() { DistributionSummary t = new CompositeDistributionSummary( NoopId.INSTANCE, Collections.emptyList()); assertCountEquals(t, 0L); assertTotalEquals(t, 0L); t.record(1L); assertCountEquals(t, 0L); assertTotalEquals(t, 0L); } @Test public void testInit() { DistributionSummary t = newDistributionSummary(); assertCountEquals(t, 0L); assertTotalEquals(t, 0L); } @Test public void testRecord() { DistributionSummary t = newDistributionSummary(); t.record(42); assertCountEquals(t, 1L); assertTotalEquals(t, 42L); } @Test public void testMeasure() { DistributionSummary t = newDistributionSummary(); t.record(42); clock.setWallTime(3712345L); for (Measurement m : t.measure()) { Assertions.assertEquals(m.timestamp(), 3712345L); if (m.id().equals(t.id().withTag(Statistic.count))) { Assertions.assertEquals(m.value(), 1.0, 0.1e-12); } else if (m.id().equals(t.id().withTag(Statistic.totalAmount))) { Assertions.assertEquals(m.value(), 42, 0.1e-12); } else { Assertions.fail("unexpected id: " + m.id()); } } } }
5,698
0
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-api/src/test/java/com/netflix/spectator/api/FunctionsTest.java
/* * Copyright 2014-2019 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.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicLong; import java.util.function.ToDoubleFunction; public class FunctionsTest { private final ManualClock clock = new ManualClock(); @Test public void ageFunction() { clock.setWallTime(5000L); final DoubleFunction<AtomicLong> f = Functions.age(clock); Assertions.assertEquals(f.apply(1000L), 4.0, 1e-12); } private byte byteMethod() { return (byte) 1; } @Test public void invokeMethodByte() throws Exception { final ToDoubleFunction<FunctionsTest> f = Functions.invokeMethod(Utils.getMethod(getClass(), "byteMethod")); Assertions.assertEquals(f.applyAsDouble(this), 1.0, 1e-12); } private short shortMethod() { return (short) 2; } @Test public void invokeMethodShort() throws Exception { final ToDoubleFunction<FunctionsTest> f = Functions.invokeMethod(Utils.getMethod(getClass(), "shortMethod")); Assertions.assertEquals(f.applyAsDouble(this), 2.0, 1e-12); } private int intMethod() { return 3; } @Test public void invokeMethodInt() throws Exception { final ToDoubleFunction<FunctionsTest> f = Functions.invokeMethod(Utils.getMethod(getClass(), "intMethod")); Assertions.assertEquals(f.applyAsDouble(this), 3.0, 1e-12); } private long longMethod() { return 4L; } @Test public void invokeMethodLong() throws Exception { final ToDoubleFunction<FunctionsTest> f = Functions.invokeMethod(Utils.getMethod(getClass(), "longMethod")); Assertions.assertEquals(f.applyAsDouble(this), 4.0, 1e-12); } private Long wrapperLongMethod() { return 5L; } @Test public void invokeMethodWrapperLong() throws Exception { final ToDoubleFunction<FunctionsTest> f = Functions.invokeMethod( Utils.getMethod(getClass(), "wrapperLongMethod")); Assertions.assertEquals(f.applyAsDouble(this), 5.0, 1e-12); } private Long throwsMethod() { throw new IllegalStateException("fubar"); } @Test public void invokeBadMethod() throws Exception { final ToDoubleFunction<FunctionsTest> f = Functions.invokeMethod(Utils.getMethod(getClass(), "throwsMethod")); Assertions.assertEquals(f.applyAsDouble(this), Double.NaN, 1e-12); } @Test public void invokeNoSuchMethod() throws Exception { Assertions.assertThrows(NoSuchMethodException.class, () -> Functions.invokeMethod(Utils.getMethod(getClass(), "unknownMethod"))); } @Test public void invokeOnSubclass() throws Exception { final ToDoubleFunction<B> f = Functions.invokeMethod(Utils.getMethod(B.class, "two")); Assertions.assertEquals(f.applyAsDouble(new B()), 2.0, 1e-12); } @Test public void invokeOneA() throws Exception { final ToDoubleFunction<A> f = Functions.invokeMethod(Utils.getMethod(A.class, "one")); Assertions.assertEquals(f.applyAsDouble(new A()), 1.0, 1e-12); } @Test public void invokeOneB() throws Exception { final ToDoubleFunction<B> f = Functions.invokeMethod(Utils.getMethod(B.class, "one")); Assertions.assertEquals(f.applyAsDouble(new B()), -1.0, 1e-12); } private static class A { public int one() { return 1; } } private static class B extends A { public int one() { return -1; } public int two() { return 2; } } }
5,699