From: Eylon Malin Date: Thu, 10 Oct 2019 12:22:07 +0000 (+0300) Subject: use logging interceptor in SDC client X-Git-Tag: 6.0.1~245 X-Git-Url: https://gerrit.onap.org/r/gitweb?a=commitdiff_plain;h=e8d29ab5e3775472f59a4997fa3a5df9319de306;p=vid.git use logging interceptor in SDC client Issue-ID: VID-253 Change-Id: I67947886fd8945a224ee81d5eb0a8fedf1f7317c Signed-off-by: Eylon Malin --- diff --git a/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java b/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java index ca317dde2..2c6fcea9d 100644 --- a/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java +++ b/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java @@ -59,6 +59,12 @@ public class ExternalAppInitializer extends AppInitializer { public void onStartup(ServletContext servletContext) throws ServletException { super.onStartup(servletContext); setDefaultTimeZoneToUTC(); + setPartnerName(); + } + + private void setPartnerName() { + //org.onap.logging.filter.base.AbstractMetricLogFilter read this system property + System.setProperty("partnerName", "VID.VID"); } //set time zone to UTC so Dates would be written to DB in UTC timezone diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java index 96be59123..9efb3893a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java @@ -29,8 +29,6 @@ import static org.onap.vid.client.SyncRestClientInterface.HEADERS.AUTHORIZATION; import static org.onap.vid.client.SyncRestClientInterface.HEADERS.CONTENT_TYPE; import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID; import static org.onap.vid.client.UnirestPatchKt.extractRawAsString; -import static org.onap.vid.logging.Headers.PARTNER_NAME; -import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; import com.att.eelf.configuration.EELFLogger; import com.google.common.collect.ImmutableMap; @@ -153,9 +151,7 @@ public class SdcRestClient implements AsdcClient { private Map prepareHeaders(String auth, String contentType) { return ImmutableMap.of( X_ECOMP_INSTANCE_ID, SystemProperties.getProperty(APP_DISPLAY_NAME), - PARTNER_NAME.getHeaderName(), PARTNER_NAME.getHeaderValue(), AUTHORIZATION, auth, - REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId(), CONTENT_TYPE, contentType ); } diff --git a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java index 5c65c8af4..0883b3084 100644 --- a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java @@ -49,10 +49,13 @@ import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.eclipse.jetty.util.security.Password; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.logging.ApacheClientMetricRequestInterceptor; +import org.onap.vid.logging.ApacheClientMetricResponseInterceptor; import org.onap.vid.properties.VidProperties; import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; @@ -68,22 +71,29 @@ public class SyncRestClient implements SyncRestClientInterface { private RestClient restClient; public SyncRestClient(Logging loggingService) { - this(null, null, loggingService); + this(null, null, loggingService, false); + } + + public SyncRestClient(Logging loggingService, boolean useLoggingInterceptor) { + this(null, null, loggingService, useLoggingInterceptor); } public SyncRestClient(ObjectMapper objectMapper, Logging loggingService) { - this(null, objectMapper, loggingService); + this(null, objectMapper, loggingService, false); } public SyncRestClient(CloseableHttpClient httpClient, Logging loggingService) { - this(httpClient, null, loggingService); + this(httpClient, null, loggingService, false); } - public SyncRestClient(CloseableHttpClient httpClient, ObjectMapper objectMapper, Logging loggingService) { + public SyncRestClient(CloseableHttpClient httpClient, + ObjectMapper objectMapper, + Logging loggingService, + boolean useLoggingInterceptor) { restClient = RestClient .newClient() .objectMapper(ObjectUtils.defaultIfNull(objectMapper, defaultObjectMapper())) - .httpClient(ObjectUtils.defaultIfNull(httpClient , defaultHttpClient())) + .httpClient(ObjectUtils.defaultIfNull(httpClient , defaultHttpClient(useLoggingInterceptor))) .build(); this.loggingService = loggingService; this.outgoingRequestsLogger = Logging.getRequestsLogger("syncRestClient"); @@ -253,7 +263,7 @@ public class SyncRestClient implements SyncRestClientInterface { return JOSHWORKS_JACKSON_OBJECT_MAPPER; } - private CloseableHttpClient defaultHttpClient() { + private CloseableHttpClient defaultHttpClient(boolean useLoggingInterceptor) { try { String trustStorePath = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_FILENAME); String trustStorePass = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_PASSWD_X); @@ -263,7 +273,13 @@ public class SyncRestClient implements SyncRestClientInterface { SSLContext sslContext = trustOwnCACerts(decryptedTrustStorePass, trustStore); SSLConnectionSocketFactory sslSf = allowTLSProtocols(sslContext); - return HttpClients.custom().setSSLSocketFactory(sslSf).build(); + HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(sslSf); + if (useLoggingInterceptor) { + httpClientBuilder + .addInterceptorFirst(new ApacheClientMetricRequestInterceptor()) + .addInterceptorLast(new ApacheClientMetricResponseInterceptor()); + } + return httpClientBuilder.build(); } catch (IOException | CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { logger.warn("Cannot initialize custom http client from current configuration. Using default one.", e); return HttpClients.createDefault(); diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java b/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java index 928e19357..48677120d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java @@ -65,7 +65,7 @@ public class LoggerController extends RestrictedBaseController { this.logfilePathCreator = logfilePathCreator; } - @GetMapping(value = "/{loggerName:audit|audit2019|error|metrics}") + @GetMapping(value = "/{loggerName:audit|audit2019|error|metrics|metrics2019}") public String getLog(@PathVariable String loggerName, HttpServletRequest request, @RequestParam(value="limit", defaultValue = "5000") Integer limit) throws IOException { diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java b/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java index 9faa7ade5..6936d0a71 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java @@ -160,7 +160,9 @@ public class WebConfig { String protocol = asdcClientConfiguration.getAsdcClientProtocol(); int port = asdcClientConfiguration.getAsdcClientPort(); - return new SdcRestClient(protocol + "://" + host + ":" + port + "/", auth, new SyncRestClient(loggingService), loggingService); + return new SdcRestClient(protocol + "://" + host + ":" + port + "/", auth, + new SyncRestClient( loggingService, true), + loggingService); } @Bean diff --git a/vid-app-common/src/main/java/org/onap/vid/logging/ApacheClientMetricRequestInterceptor.java b/vid-app-common/src/main/java/org/onap/vid/logging/ApacheClientMetricRequestInterceptor.java new file mode 100644 index 000000000..0cc5a2aaa --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/logging/ApacheClientMetricRequestInterceptor.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.logging; + +import org.apache.http.HttpRequest; +import org.apache.http.HttpRequestInterceptor; +import org.apache.http.protocol.HttpContext; + +public class ApacheClientMetricRequestInterceptor extends ApacheClientMetricInterceptor implements HttpRequestInterceptor { + + @Override + public void process(HttpRequest request, HttpContext context) { + this.pre(request, request); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/logging/ApacheClientMetricResponseInterceptor.java b/vid-app-common/src/main/java/org/onap/vid/logging/ApacheClientMetricResponseInterceptor.java new file mode 100644 index 000000000..72b54e7a5 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/logging/ApacheClientMetricResponseInterceptor.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.logging; + +import org.apache.http.HttpResponse; +import org.apache.http.HttpResponseInterceptor; +import org.apache.http.protocol.HttpContext; + +public class ApacheClientMetricResponseInterceptor extends ApacheClientMetricInterceptor implements HttpResponseInterceptor { + + @Override + public void process(HttpResponse response, HttpContext context) { + this.post(null, response); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/logging/VidLoggerAspect.java b/vid-app-common/src/main/java/org/onap/vid/logging/VidLoggerAspect.java index 309ead40c..f87297c37 100644 --- a/vid-app-common/src/main/java/org/onap/vid/logging/VidLoggerAspect.java +++ b/vid-app-common/src/main/java/org/onap/vid/logging/VidLoggerAspect.java @@ -32,6 +32,7 @@ import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.portalsdk.core.logging.aspect.EELFLoggerAdvice; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.service.AppService; @@ -39,6 +40,7 @@ import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.UserUtils; import org.onap.vid.controller.ControllersUtils; import org.onap.vid.utils.SystemPropertiesWrapper; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @@ -87,9 +89,10 @@ public class VidLoggerAspect { Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(),joinPoint.getSignature().getName()}; Object[] returnArgs = advice.before(securityEventType, fabricateArgsWithNull(), passOnArgs); - fixSetRequestBasedDefaultsIntoGlobalLoggingContext(httpServletRequestOrNull(joinPoint), + HttpServletRequest httpServletRequest = httpServletRequestOrNull(joinPoint); + fixSetRequestBasedDefaultsIntoGlobalLoggingContext(httpServletRequest, joinPoint.getSignature().getDeclaringType().getName()); - + addRequestIdToMdcForMetricFilter(httpServletRequest); fixServerFqdnInMDC(); //Execute the actual method @@ -108,6 +111,14 @@ public class VidLoggerAspect { return result; } + //prepare MDC for org.onap.logging.filter.base.AbstractMetricLogFilter + private void addRequestIdToMdcForMetricFilter(HttpServletRequest httpServletRequest) { + if (httpServletRequest!=null) { + String requestId = UserUtils.getRequestId(httpServletRequest); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + } + } + // Set the status code into MDC *before* the metrics log is written by advice.after() private void fixStatusCodeInMDC(String restStatus) { EELFLoggerDelegate.mdcPut(SystemProperties.STATUS_CODE, restStatus); @@ -155,6 +166,7 @@ public class VidLoggerAspect { String loginId = controllersUtils.extractUserId(httpServletRequest); logger.setRequestBasedDefaultsIntoGlobalLoggingContext(httpServletRequest, appName, requestId, loginId); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java index 7cbf0805b..3a76a33e2 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java @@ -24,18 +24,13 @@ import static com.xebialabs.restito.semantics.Action.ok; import static com.xebialabs.restito.semantics.Action.stringContent; import static org.apache.http.client.config.RequestConfig.custom; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapContaining.hasKey; -import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID; -import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; import com.fasterxml.jackson.core.JsonProcessingException; import com.xebialabs.restito.semantics.Call; @@ -129,12 +124,7 @@ public class SdcRestClientITTest { assertTrue(first.isPresent()); - assertThat(first.get().getHeaders(), - allOf( - hasEntry(equalToIgnoringCase(REQUEST_ID_HEADER_KEY), contains(matchesPattern(UUID_REGEX))), - hasKey(equalToIgnoringCase(X_ECOMP_INSTANCE_ID)), - hasEntry(equalToIgnoringCase("x-onap-partnerName"), contains(equalTo("VID.VID"))) - )); + assertThat(first.get().getHeaders(), hasKey(equalToIgnoringCase(X_ECOMP_INSTANCE_ID))); } private Service getExpectedService(String stringId) { diff --git a/vid-automation/src/main/java/org/onap/simulator/presetGenerator/presets/BasePresets/BaseSDCPreset.java b/vid-automation/src/main/java/org/onap/simulator/presetGenerator/presets/BasePresets/BaseSDCPreset.java index ad8dfb3ac..ba35299a8 100644 --- a/vid-automation/src/main/java/org/onap/simulator/presetGenerator/presets/BasePresets/BaseSDCPreset.java +++ b/vid-automation/src/main/java/org/onap/simulator/presetGenerator/presets/BasePresets/BaseSDCPreset.java @@ -4,15 +4,19 @@ import java.util.Map; public abstract class BaseSDCPreset extends BasePreset { + public static final String SDC_ROOT_PATH = "/sdc/v1/catalog/services"; + @Override protected String getRootPath() { - return "/sdc/v1/catalog/services"; + return SDC_ROOT_PATH; } @Override public Map getRequestHeaders() { Map map = super.getRequestHeaders(); map.put("X-ONAP-PartnerName", "VID.VID"); + map.put("X-ONAP-InvocationID", "[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}"); + map.put("X-ONAP-RequestID", "[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}"); return map; } diff --git a/vid-automation/src/main/java/vid/automation/test/services/SimulatorApi.java b/vid-automation/src/main/java/vid/automation/test/services/SimulatorApi.java index fd7033c6e..6e15b7b52 100644 --- a/vid-automation/src/main/java/vid/automation/test/services/SimulatorApi.java +++ b/vid-automation/src/main/java/vid/automation/test/services/SimulatorApi.java @@ -1,5 +1,6 @@ package vid.automation.test.services; +import static java.util.stream.Collectors.toList; import static org.testng.Assert.assertEquals; import static vid.automation.test.services.DropTestApiField.dropFieldCloudOwnerFromString; import static vid.automation.test.services.DropTestApiField.dropTestApiFieldFromString; @@ -55,11 +56,24 @@ public class SimulatorApi { public List values; } - public static class HttpRequest{ + public static class HttpRequest { public StringWrapper path; public List headers; } + public static class RecordedRequests { + public String path; + public Map> headers; + + public RecordedRequests(String path, Map> headers) { + this.path = path; + this.headers = headers; + } + + public RecordedRequests() { + } + } + private static final URI uri; //uri for registration private static final URI simulationUri; //uri for getting simulated responses private static final Client client; @@ -125,7 +139,7 @@ public class SimulatorApi { public static void registerExpectationFromPresetsCollections(Collection> presets, RegistrationStrategy registrationStrategy) { registerExpectationFromPresets(presets.stream() .flatMap(Collection::stream) - .collect(Collectors.toList()), registrationStrategy); + .collect(toList()), registrationStrategy); } public static void registerExpectationFromPresets(Collection presets, RegistrationStrategy registrationStrategy) { @@ -152,16 +166,27 @@ public class SimulatorApi { The key of the map is a path, and the value is counter */ public static Map retrieveRecordedRequestsPathCounter() { - List httpRequests = retrieveRecordedRequests(); + List httpRequests = retrieveRecordedHttpRequests(); return httpRequests.stream().map(x->x.path.value).collect( Collectors.groupingBy(Function.identity(), Collectors.counting())); } - public static List retrieveRecordedRequests() { + private static List retrieveRecordedHttpRequests() { Response response = client.target(uri).path("retrieveRecordedRequests").request().get(); return response.readEntity(new GenericType>(){}); } + public static List retrieveRecordedRequests() { + List rawRequests = retrieveRecordedHttpRequests(); + return rawRequests.stream().map(request->new RecordedRequests( + request.path.value, + request.headers.stream().collect( + Collectors.toMap( + x->x.name.value, + x->x.values.stream().map(y->y.value).collect(toList()))) + )).collect(toList()); + } + private static void registerToSimulatorAndAssertSuccess(String name, Object content, RegistrationStrategy registrationStrategy) { if (registrationStrategy == RegistrationStrategy.CLEAR_THEN_SET) { clearRegistrations(); diff --git a/vid-automation/src/test/java/org/onap/vid/api/SdcApiTest.java b/vid-automation/src/test/java/org/onap/vid/api/SdcApiTest.java index 04dbbc0c5..95fb68a10 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/SdcApiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/SdcApiTest.java @@ -24,28 +24,39 @@ import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; import static net.javacrumbs.jsonunit.JsonMatchers.jsonStringEquals; import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; +import static org.onap.simulator.presetGenerator.presets.BasePresets.BaseSDCPreset.SDC_ROOT_PATH; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static vid.automation.test.services.SimulatorApi.RegistrationStrategy.APPEND; import static vid.automation.test.services.SimulatorApi.RegistrationStrategy.CLEAR_THEN_SET; import static vid.automation.test.services.SimulatorApi.registerExpectation; import static vid.automation.test.services.SimulatorApi.registerExpectationFromPresets; +import static vid.automation.test.services.SimulatorApi.retrieveRecordedRequests; import static vid.automation.test.utils.ReadFile.loadResourceAsString; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.onap.simulator.presetGenerator.presets.BasePresets.BasePreset; +import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubscribersGet; import org.onap.simulator.presetGenerator.presets.sdc.PresetSDCGetServiceMetadataGet; import org.onap.simulator.presetGenerator.presets.sdc.PresetSDCGetServiceToscaModelGet; +import org.onap.vid.more.LoggerFormatTest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import vid.automation.test.infra.FeatureTogglingTest; import vid.automation.test.infra.Features; +import vid.automation.test.infra.ModelInfo; +import vid.automation.test.services.SimulatorApi.RecordedRequests; public class SdcApiTest extends BaseApiTest { @@ -99,7 +110,7 @@ public class SdcApiTest extends BaseApiTest { public void getServiceModelALaCarteInstantiation() { registerToSimulatorWithPresets(A_LA_CARTE_INSTANTIATION_TYPE_UUID, A_LA_CARTE_INSTANTIATION_TYPE_INVARIANT_UUID, A_LA_CARTE_INSTANTIATION_TYPE_FILE_PATH); ResponseEntity response = restTemplate.getForEntity(buildUri(SDC_GET_SERVICE_MODEL + A_LA_CARTE_INSTANTIATION_TYPE_UUID), String.class); - Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); + assertEquals(response.getStatusCode(), HttpStatus.OK); String aLaCarteInstantiationTypeExpectedResponse = loadResourceAsString(A_LA_CARTE_INSTANTIATION_TYPE_EXPECTED_RESPONSE); assertThat(response.getBody(), jsonEquals(aLaCarteInstantiationTypeExpectedResponse) .when(IGNORING_ARRAY_ORDER) @@ -111,7 +122,7 @@ public class SdcApiTest extends BaseApiTest { public void getServiceModelMacroInstantiation() { registerToSimulatorWithPresets(MACRO_INSTANTIATION_TYPE_UUID, MACRO_INSTANTIATION_TYPE_INVARIANT_UUID, MACRO_INSTANTIATION_TYPE_FILE_PATH); ResponseEntity response = restTemplate.getForEntity(buildUri(SDC_GET_SERVICE_MODEL + MACRO_INSTANTIATION_TYPE_UUID), String.class); - Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); + assertEquals(response.getStatusCode(), HttpStatus.OK); String macroInstantiationTypeExpectedResponse = loadResourceAsString(MACRO_INSTANTIATION_TYPE_EXPECTED_RESPONSE); assertThat(response.getBody(), jsonEquals(macroInstantiationTypeExpectedResponse) .when(IGNORING_ARRAY_ORDER) @@ -123,7 +134,7 @@ public class SdcApiTest extends BaseApiTest { public void getServiceModelWithoutInstantiationType(){ registerToSimulatorWithPresets(MACRO_INSTANTIATION_TYPE_UUID, MACRO_INSTANTIATION_TYPE_INVARIANT_UUID, EMPTY_INSTANTIATION_TYPE_FILE_PATH); ResponseEntity response = restTemplate.getForEntity(buildUri(SDC_GET_SERVICE_MODEL + MACRO_INSTANTIATION_TYPE_UUID), String.class); - Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); + assertEquals(response.getStatusCode(), HttpStatus.OK); String emptyInstantiationTypeExpectedResponse = loadResourceAsString(EMPTY_INSTANTIATION_TYPE_EXPECTED_RESPONSE); assertThat("The response is in the format of JSON", response.getBody(), is(jsonStringEquals(turnOffInstantiationUI(emptyInstantiationTypeExpectedResponse)))); } @@ -132,7 +143,7 @@ public class SdcApiTest extends BaseApiTest { public void getServiceModelBothInstantiationType(){ registerToSimulatorWithPresets(MACRO_INSTANTIATION_TYPE_UUID, MACRO_INSTANTIATION_TYPE_INVARIANT_UUID, BOTH_INSTANTIATION_TYPE_FILE_PATH); ResponseEntity response = restTemplate.getForEntity(buildUri(SDC_GET_SERVICE_MODEL + MACRO_INSTANTIATION_TYPE_UUID), String.class); - Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); + assertEquals(response.getStatusCode(), HttpStatus.OK); String macroInstantiationTypeExpectedResponse = loadResourceAsString(MACRO_INSTANTIATION_TYPE_EXPECTED_RESPONSE); assertThat(response.getBody(), jsonEquals(macroInstantiationTypeExpectedResponse) .when(IGNORING_ARRAY_ORDER) @@ -143,7 +154,7 @@ public class SdcApiTest extends BaseApiTest { public void getServiceModelWithGroupsAndCheckMinMaxInitialParams(){ registerToSimulatorWithPresets(MIN_MAX_INITIAL_UUID, MIN_MAX_INITIAL_INVARIANT_UUID, MIN_MAX_INITIAL_FILE_PATH); ResponseEntity response = restTemplate.getForEntity(buildUri(SDC_GET_SERVICE_MODEL + MIN_MAX_INITIAL_UUID), String.class); - Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); + assertEquals(response.getStatusCode(), HttpStatus.OK); String minMaxInitialExpectedResponse = loadResourceAsString("sdcApiTest/minMaxInitialExpectedResponse.json"); assertThat("The response is in the format of JSON", response.getBody(), is(jsonStringEquals(turnOffInstantiationUI(minMaxInitialExpectedResponse)))); } @@ -152,7 +163,7 @@ public class SdcApiTest extends BaseApiTest { public void getServiceModelWithGroupsAndCheckMinMaxInitialParamsOldCsar(){ registerToSimulatorWithPresets(MIN_MAX_INITIAL_UUID_OLD_CSAR, MIN_MAX_INITIAL_INVARIANT_UUID_OLD_CSAR, MIN_MAX_INITIAL_FILE_PATH_OLD_CSAR); ResponseEntity response = restTemplate.getForEntity(buildUri(SDC_GET_SERVICE_MODEL + MIN_MAX_INITIAL_UUID_OLD_CSAR), String.class); - Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); + assertEquals(response.getStatusCode(), HttpStatus.OK); String minMaxInitialExpectedResponseOldCsar = loadResourceAsString("sdcApiTest/minMaxInitialExpectedResponseOldCsar.json"); assertThat("The response is in the format of JSON", response.getBody(), is(jsonStringEquals(minMaxInitialExpectedResponseOldCsar))); } @@ -162,7 +173,7 @@ public class SdcApiTest extends BaseApiTest { public void getServiceModelWithServiceRoleGrouping(){ registerToSimulatorWithPresets(GROUPING_SERVICE_ROLE_UUID, GROUPING_SERVICE_ROLE_INVARIANT_UUID, GROUPING_SERVICE_ROLE_FILE_PATH); ResponseEntity response = restTemplate.getForEntity(buildUri(SDC_GET_SERVICE_MODEL + GROUPING_SERVICE_ROLE_UUID), String.class); - Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); + assertEquals(response.getStatusCode(), HttpStatus.OK); String groupingServiceRoleExpectedResponse = loadResourceAsString(GROUPING_SERVICE_ROLE_EXPECTED_RESPONSE); assertThat("The response is in the format of JSON", response.getBody(), is(jsonStringEquals(groupingServiceRoleExpectedResponse))); } @@ -211,4 +222,41 @@ public class SdcApiTest extends BaseApiTest { response.at(base + "/volumeGroups").size(), is(not(0))); } + + @Test + public void whenCallSdc_thenRequestRecordedInMetricsLog() { + + ModelInfo modelInfo = ModelInfo.transportWithPnfsService; + + registerExpectationFromPresets(ImmutableList.of( + new PresetSDCGetServiceToscaModelGet(modelInfo), + new PresetSDCGetServiceMetadataGet(modelInfo), + new PresetAAIGetSubscribersGet() //for read logs permissions + ), CLEAR_THEN_SET); + //registerExpectationFromPresets(getEcompPortalPresets(), APPEND); + + ResponseEntity response = restTemplate.getForEntity( + buildUri(SDC_GET_SERVICE_MODEL + modelInfo.modelVersionId), String.class); + + String logLines = LoggerFormatTest.getLogLines("metrics2019", 15, 0, restTemplate, uri); + + final String requestId = response.getHeaders().getFirst("X-ECOMP-RequestID-echo"); + + List requests = retrieveRecordedRequests(); + List sdcRequests = requests.stream().filter(x->x.path.startsWith(SDC_ROOT_PATH)).collect(Collectors.toList()); + assertEquals(sdcRequests.size(), 2); + sdcRequests.forEach(request->{ + assertThat("X-ONAP-RequestID", request.headers.get("X-ONAP-RequestID"), contains(requestId)); + assertThat("X-ECOMP-RequestID", request.headers.get("X-ECOMP-RequestID"), contains(requestId)); + assertThat("X-ONAP-PartnerName", request.headers.get("X-ONAP-PartnerName"), contains("VID.VID")); + List invocationIds = request.headers.get("X-ONAP-InvocationID"); + assertEquals(invocationIds.size(), 1); + List sdcMetricsLogLines = + Stream.of(logLines.split("\n")) + .filter(x->x.contains(SDC_ROOT_PATH) && x.contains(requestId) && x.contains(invocationIds.get(0))) + .collect(Collectors.toList()); + assertThat("not found sdc call in metrics log with requestId and invocationId" + requestId, + sdcMetricsLogLines.size(), is(equalTo(2))); + }); + } }