@Override public String getFormattedElement(AccessLogParam accessLogParam) { HttpServerRequest request = accessLogParam.getRoutingContext().request(); if (null == request) { return EMPTY_RESULT; } SocketAddress remoteAddress = request.remoteAddress(); if (null == remoteAddress) { return EMPTY_RESULT; } String remoteHost = remoteAddress.host(); if (StringUtils.isEmpty(remoteHost)) { return EMPTY_RESULT; } return remoteHost; }
@Override public String getFormattedElement(AccessLogParam accessLogParam) { HttpServerRequest request = accessLogParam.getRoutingContext().request(); if (null == request) { return EMPTY_RESULT; } SocketAddress localAddress = request.localAddress(); if (null == localAddress) { return EMPTY_RESULT; } String localHost = localAddress.host(); if (StringUtils.isEmpty(localHost)) { return EMPTY_RESULT; } return localHost; }
@Test public void getFormattedElement() { AccessLogParam param = new AccessLogParam(); RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); SocketAddress localAddress = Mockito.mock(SocketAddress.class); param.setRoutingContext(context); Mockito.when(context.request()).thenReturn(request); Mockito.when(request.localAddress()).thenReturn(localAddress); Mockito.when(localAddress.port()).thenReturn(8080); String result = new LocalPortElement().getFormattedElement(param); assertEquals("8080", result); }
@Test public void getFormattedElement() { AccessLogParam param = new AccessLogParam(); RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); SocketAddress localAddress = Mockito.mock(SocketAddress.class); String localHost = "testHost"; param.setRoutingContext(context); Mockito.when(context.request()).thenReturn(request); Mockito.when(request.localAddress()).thenReturn(localAddress); Mockito.when(localAddress.host()).thenReturn(localHost); String result = ELEMENT.getFormattedElement(param); assertEquals(localHost, result); }
@Test public void getFormattedElementOnHostIsNull() { AccessLogParam param = new AccessLogParam(); RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); SocketAddress localAddress = Mockito.mock(SocketAddress.class); param.setRoutingContext(context); Mockito.when(context.request()).thenReturn(request); Mockito.when(request.localAddress()).thenReturn(localAddress); Mockito.when(localAddress.host()).thenReturn(null); String result = ELEMENT.getFormattedElement(param); assertEquals("-", result); }
@Test public void getFormattedElementIsEmpty() { AccessLogParam param = new AccessLogParam(); RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); SocketAddress localAddress = Mockito.mock(SocketAddress.class); String localHost = ""; param.setRoutingContext(context); Mockito.when(context.request()).thenReturn(request); Mockito.when(request.localAddress()).thenReturn(localAddress); Mockito.when(localAddress.host()).thenReturn(localHost); String result = ELEMENT.getFormattedElement(param); assertEquals("-", result); }
@Test public void getFormattedElement() { AccessLogParam param = new AccessLogParam(); RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); SocketAddress address = Mockito.mock(SocketAddress.class); String remoteHost = "remoteHost"; param.setRoutingContext(context); Mockito.when(context.request()).thenReturn(request); Mockito.when(request.remoteAddress()).thenReturn(address); Mockito.when(address.host()).thenReturn(remoteHost); String result = ELEMENT.getFormattedElement(param); assertEquals(remoteHost, result); }
@Test public void getFormattedElementOnHostIsNull() { AccessLogParam param = new AccessLogParam(); RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); SocketAddress address = Mockito.mock(SocketAddress.class); param.setRoutingContext(context); Mockito.when(context.request()).thenReturn(request); Mockito.when(request.remoteAddress()).thenReturn(address); Mockito.when(address.host()).thenReturn(null); String result = ELEMENT.getFormattedElement(param); assertEquals("-", result); }
@Test public void getFormattedElementOnHostIsEmpty() { AccessLogParam param = new AccessLogParam(); RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); SocketAddress address = Mockito.mock(SocketAddress.class); String remoteHost = ""; param.setRoutingContext(context); Mockito.when(context.request()).thenReturn(request); Mockito.when(request.remoteAddress()).thenReturn(address); Mockito.when(address.host()).thenReturn(remoteHost); String result = ELEMENT.getFormattedElement(param); assertEquals("-", result); }
@Override public Map<HttpClientMetrics, ?> requestBegin(Map<HttpClientMetrics, ?> endpointMetric, Map<HttpClientMetrics, ?> socketMetric, SocketAddress localAddress, SocketAddress remoteAddress, HttpClientRequest request) { return null; }
@Override public FdfsClientOptions fromJson(JsonObject json) { super.fromJson(json); JsonArray array = json.getJsonArray(TRACKERS); if (array != null && array.size() > 0) { array.forEach(object -> { if (object instanceof JsonObject) { JsonObject tracker = (JsonObject) object; String host = tracker.getString(HOST, ""); int port = tracker.getInteger(PORT, -1); if (!host.isEmpty() && port != -1) { trackers.add(SocketAddress.inetSocketAddress(port, host)); } } }); } return this; }
private Future<FdfsStorageOptions> parseStorage(Buffer bodyBuffer, String charset, boolean hasPathIndex) { try { FdfsStorageOptions storageOptions = new FdfsStorageOptions(options); String group = FdfsUtils .fdfsTrim(bodyBuffer.getString(0, FdfsProtocol.FDFS_GROUP_NAME_MAX_LEN, options.getCharset())); String ip = FdfsUtils.fdfsTrim(bodyBuffer.getString(FdfsProtocol.FDFS_GROUP_NAME_MAX_LEN, FdfsProtocol.FDFS_GROUP_NAME_MAX_LEN + FdfsProtocol.FDFS_IPADDR_SIZE - 1, options.getCharset())); long port = bodyBuffer.getLong(FdfsProtocol.FDFS_GROUP_NAME_MAX_LEN + FdfsProtocol.FDFS_IPADDR_SIZE - 1); storageOptions.setGroup(group).setAddress(SocketAddress.inetSocketAddress((int) port, ip)); if (hasPathIndex && bodyBuffer.length() > FdfsProtocol.TRACKER_QUERY_STORAGE_FETCH_BODY_LEN) { byte storePathIndex = bodyBuffer.getByte(FdfsProtocol.TRACKER_QUERY_STORAGE_FETCH_BODY_LEN); storageOptions.setStorePathIndex(storePathIndex); } return Future.succeededFuture(storageOptions); } catch (Exception e) { return Future.failedFuture(e); } }
/** * Only requests that contain a tracking tag will be tracked */ @Override @Nullable public HttpRequestMetrics requestBegin(final Void endpointMetric, final SocketAddress socketMetric, final SocketAddress localAddress, final SocketAddress remoteAddress, final HttpClientRequest request) { // extract request tag to identify the metric and confirm that we want to track it String requestTag = request.headers().get(Tags.TRACK_HEADER.toString()); HttpRequestMetrics metric = null; if (requestTag != null) { // Remove tracking header to avoid it propagating to clients request.headers().remove(Tags.TRACK_HEADER.toString()); // Create client request metric metric = new HttpRequestMetrics(requestTag, remoteAddress, request.method()); metric.start(); } return metric; }
@Test public void testUntaggedRequest() { SocketAddress socketMetric = mock(SocketAddress.class); SocketAddress localAddress = mock(SocketAddress.class); SocketAddress remoteAddress = mock(SocketAddress.class); HttpClientRequest request = mock(HttpClientRequest.class); MultiMap headers = mock(MultiMap.class); when(headers.get(eq(Tags.TRACK_HEADER.toString()))).thenReturn(null); when(request.headers()).thenReturn(headers); HttpRequestMetrics metrics = victim.requestBegin(null, socketMetric, localAddress, remoteAddress, request); assertNull(metrics); }
@Test public void testRequestBegin() { SocketAddress socketMetric = mock(SocketAddress.class); SocketAddress localAddress = mock(SocketAddress.class); SocketAddress remoteAddress = mock(SocketAddress.class); HttpClientRequest request = mock(HttpClientRequest.class); MultiMap headers = mock(MultiMap.class); when(headers.get(eq(Tags.TRACK_HEADER.toString()))).thenReturn("tag"); when(request.headers()).thenReturn(headers); HttpRequestMetrics metrics = victim.requestBegin(null, socketMetric, localAddress, remoteAddress, request); assertNotNull(metrics); assertEquals(remoteAddress, metrics.getAddress()); }
@Override public List<DataPoint> collect() { long timestamp = System.currentTimeMillis(); Map<SocketAddress, Long> connections = new HashMap<>(); Map<SocketAddress, Long> bytesReceived = new HashMap<>(); Map<SocketAddress, Long> bytesSent = new HashMap<>(); Map<SocketAddress, Long> errorCount = new HashMap<>(); for (NetServerMetricsImpl netServerMetrics : metricsSet) { SocketAddress serverAddress = netServerMetrics.getServerAddress(); merge(connections, serverAddress, netServerMetrics.getConnections()); merge(bytesReceived, serverAddress, netServerMetrics.getBytesReceived()); merge(bytesSent, serverAddress, netServerMetrics.getBytesSent()); merge(errorCount, serverAddress, netServerMetrics.getErrorCount()); } List<DataPoint> res = new ArrayList<>(); res.addAll(gauges("connections", timestamp, connections)); res.addAll(counters("bytesReceived", timestamp, bytesReceived)); res.addAll(counters("bytesSent", timestamp, bytesSent)); res.addAll(counters("errorCount", timestamp, errorCount)); return res; }
@Override public List<DataPoint> collect() { long timestamp = System.currentTimeMillis(); Map<SocketAddress, Snapshot> values = new HashMap<>(); for (NetClientMetricsImpl netClientMetrics : metricsSet) { netClientMetrics.getMeasurementsSnapshot().forEach((address, snapshot) -> { values.merge(address, snapshot, Snapshot::merge); }); } List<DataPoint> res = new ArrayList<>(); values.forEach((address, snapshot) -> { String addressId = address.host() + ":" + address.port(); res.add(new GaugePoint(baseName + addressId + ".connections", timestamp, snapshot.getConnections())); res.add(new CounterPoint(baseName + addressId + ".bytesReceived", timestamp, snapshot.getBytesReceived())); res.add(new CounterPoint(baseName + addressId + ".bytesSent", timestamp, snapshot.getBytesSent())); res.add(new CounterPoint(baseName + addressId + ".errorCount", timestamp, snapshot.getErrorCount())); }); return res; }
public HttpMetricsImpl(MetricRegistry registry, String baseName, SocketAddress localAddress) { super(registry, baseName); openWebSockets = counter("open-websockets"); requests = throughputTimer("requests"); responses = new ThroughputMeter[]{ throughputMeter("responses-1xx"), throughputMeter("responses-2xx"), throughputMeter("responses-3xx"), throughputMeter("responses-4xx"), throughputMeter("responses-5xx") }; methodRequests = new EnumMap<>(HttpMethod.class); for (HttpMethod method : HttpMethod.values()) { methodRequests.put(method, throughputTimer(method.toString().toLowerCase() + "-requests")); } }
@Override public Long connected(SocketAddress remoteAddress, String remoteName) { // Connection metrics openConnections.inc(); // On network outage the remoteAddress can be null. // Do not report the open-connections when it's null if (remoteAddress != null) { // Remote address connection metrics counter("open-connections", remoteAddress.host()).inc(); } // A little clunky, but it's possible we got here after closed has been called if (closed) { removeAll(); } return System.nanoTime(); }
@Override public void disconnected(Long ctx, SocketAddress remoteAddress) { openConnections.dec(); connections.update(System.nanoTime() - ctx, TimeUnit.NANOSECONDS); // On network outage the remoteAddress can be null. // Do not report the open-connections when it's null if (remoteAddress != null) { // Remote address connection metrics Counter counter = counter("open-connections", remoteAddress.host()); counter.dec(); if (counter.getCount() == 0) { remove("open-connections", remoteAddress.host()); } } // A little clunky, but it's possible we got here after closed has been called if (closed) { removeAll(); } }
@Test public void testGetRemoteAddr(@Mocked SocketAddress sa) { new Expectations() { { sa.host(); result = "host"; vertxRequest.remoteAddress(); result = sa; } }; Assert.assertEquals("host", request.getRemoteAddr()); }
@Test public void testGetRemoteHost(@Mocked SocketAddress sa) { new Expectations() { { sa.host(); result = "host"; vertxRequest.remoteAddress(); result = sa; } }; Assert.assertEquals("host", request.getRemoteHost()); }
@Test public void testGetRemotePort(@Mocked SocketAddress sa) { new Expectations() { { sa.port(); result = 1234; vertxRequest.remoteAddress(); result = sa; } }; Assert.assertEquals(1234, request.getRemotePort()); }
@Test public void testGetgetLocalAddr(@Mocked SocketAddress sa) { new Expectations() { { sa.host(); result = "host"; vertxRequest.localAddress(); result = sa; } }; Assert.assertEquals("host", request.getLocalAddr()); }
@Test public void testGetLocalPort(@Mocked SocketAddress sa) { new Expectations() { { sa.port(); result = 1234; vertxRequest.localAddress(); result = sa; } }; Assert.assertEquals(1234, request.getLocalPort()); }
@Override public String getFormattedElement(AccessLogParam accessLogParam) { HttpServerRequest request = accessLogParam.getRoutingContext().request(); if (null == request) { return EMPTY_RESULT; } SocketAddress localAddress = request.localAddress(); if (null == localAddress) { return EMPTY_RESULT; } return String.valueOf(localAddress.port()); }
@Before public void setup() { unitTestMeta = new UnitTestMeta(); socketAddress = new MockUp<SocketAddress>() { @Mock public String host() { return "127.0.0.1"; } @Mock public int port() { return 8080; } }.getMockInstance(); netSocket = new MockUp<NetSocket>() { @Mock public SocketAddress remoteAddress() { return socketAddress; } }.getMockInstance(); connection = new MockUp<TcpConnection>() { @Mock public void write(ByteBuf data) { netSocketBuffer = data; } @Mock public NetSocket getNetSocket() { return netSocket; } }.getMockInstance(); }
/** * 调用微信统一下单接口 * * @param product 充值设备描述 * @param price 充值设备价格 * @param ip 充值端Ip * @param openId 充值的微信openId * @param acc 账户对象 * 异步返回 微信统一下单接口返回的xml数据(String) * * @author Leibniz */ private void unifyPay(String orderId, String product, int price, SocketAddress ip, String openId, String attach, String notUrl, JsonObject acc, Handler<String> callback) { Map<String, Object> map = new TreeMap<>(); map.put("appid", acc.getString(WXAPPID)); map.put("mch_id", acc.getString(MCHID)); map.put("nonce_str", CommonUtils.getRandomID()); map.put("body", product); map.put("out_trade_no", orderId); map.put("total_fee", price); map.put("spbill_create_ip", ip.host()); map.put("notify_url", notUrl); map.put("trade_type", "JSAPI"); map.put("openid", openId); if (null != attach) { map.put("attach", attach); } map.put("sign", WechatPay.getWeixinPaySign(map, acc.getString(MCHKEY))); String xmlStr = null; String encode = "ISO8859-1"; try { xmlStr = XmlUtils.simpleMapToXml(map, encode); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } log.debug("下单请求数据:" + xmlStr); NetworkUtils.asyncPostStringWithData(WECHAT_UNIFY_PAY, xmlStr, XML, encode, callback); }
@Override public Map<HttpClientMetrics, ?> responsePushed(Map<HttpClientMetrics, ?> endpointMetric, Map<HttpClientMetrics, ?> socketMetric, SocketAddress localAddress, SocketAddress remoteAddress, HttpClientRequest request) { return unmap2WithResult(endpointMetric, socketMetric, (m, ec, sc) -> m.responsePushed(ec, sc, localAddress, remoteAddress, request)); }
@Override public StopWatch connected(SocketAddress remoteAddress, String remoteName) { counterService.increment("socket.numConnected"); StopWatch stopWatch = new StopWatch(); stopWatch.start(); return stopWatch; }
@Override public StopWatch requestBegin(StopWatch endpointWatch, StopWatch socketMetric, SocketAddress localAddress, SocketAddress remoteAddress, HttpClientRequest request) { counterService.increment("requests.sent"); StopWatch requestWatch = new StopWatch(); requestWatch.start(); return requestWatch; }
@Override public FdfsStorageOptions fromJson(JsonObject json) { super.fromJson(json); String host = json.getString(HOST, ""); int port = json.getInteger(PORT, -1); if (!host.isEmpty() && port != -1) { this.address = SocketAddress.inetSocketAddress(port, host); } return this; }
@Override public FdfsTrackerOptions fromJson(JsonObject json) { super.fromJson(json); String host = json.getString(HOST, ""); int port = json.getInteger(PORT, -1); if (!host.isEmpty() && port != -1) { this.address = SocketAddress.inetSocketAddress(port, host); } return this; }
public synchronized Future<FdfsConnection> get(SocketAddress address) { if (pools.containsKey(address)) { return pools.get(address).next().get(); } else { CircularConnectionPool pool = new CircularConnectionPool(client, address, poolSize); pools.put(address, pool); return pool.next().get(); } }
public CircularConnectionPool(NetClient client, SocketAddress address, int capacity) { this.current = new AtomicInteger(0); this.connections = new FdfsConnection[capacity]; for (int i=0; i<capacity; ++i) { this.connections[i] = new FdfsConnection(client, address); } this.capacity = connections.length; }
@Override public HttpRequestMetrics responsePushed(final Void endpointMetric, final SocketAddress socketMetric, final SocketAddress localAddress, final SocketAddress remoteAddress, final HttpClientRequest request) { return null; }
@Override public HttpClientMetrics<HttpRequestMetrics, SocketAddress, SocketAddress, Void, Void> createMetrics(final HttpClient client, final HttpClientOptions options) { HttpClientMetricsImpl httpClientMetricsImpl = new HttpClientMetricsImpl(statfulMetricsOptions); httpClientMetricsImpl.setSender(this.getOrCreateSender()); this.poolMetricsCollectors.forEach(collector -> collector.setSender(this.getOrCreateSender())); return httpClientMetricsImpl; }
@Override public HttpServerMetrics createMetrics(final HttpServer server, final SocketAddress localAddress, final HttpServerOptions options) { HttpServerMetricsImpl httpServerMetricsImpl = new HttpServerMetricsImpl(statfulMetricsOptions); httpServerMetricsImpl.setSender(this.getOrCreateSender()); this.poolMetricsCollectors.forEach(collector -> collector.setSender(this.getOrCreateSender())); return httpServerMetricsImpl; }
@Test public void testRequestEnd() throws InterruptedException { SocketAddress remoteAddress = mock(SocketAddress.class); HttpClientResponse response = mock(HttpClientResponse.class); HttpRequestMetrics metrics = new HttpRequestMetrics("tag", remoteAddress, HttpMethod.GET); when(remoteAddress.host()).thenReturn("host"); victim.responseEnd(metrics, response); ArgumentCaptor<HttpClientDataPoint> captor = ArgumentCaptor.forClass(HttpClientDataPoint.class); verify(sender,times(1)).addMetric(captor.capture()); assertNotNull(captor.getValue()); }
@Override public SocketAddress connected(SocketAddress remoteAddress, String remoteName) { long value = connections.incrementAndGet(); incrementMetric(SENSISION_CLASS_CONNECTED_COUNT, defaultLabels); setMetric(SENSISION_CLASS_CONNECTIONS, defaultLabels, value); return null; }