2  * ============LICENSE_START=======================================================
 
   3  * BBS-RELOCATION-CPE-AUTHENTICATION-HANDLER
 
   4  * ================================================================================
 
   5  * Copyright (C) 2019 NOKIA Intellectual Property. All rights reserved.
 
   6  * ================================================================================
 
   7  * Licensed under the Apache License, Version 2.0 (the "License");
 
   8  * you may not use this file except in compliance with the License.
 
   9  * You may obtain a copy of the License at
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  13  * Unless required by applicable law or agreed to in writing, software
 
  14  * distributed under the License is distributed on an "AS IS" BASIS,
 
  15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  * See the License for the specific language governing permissions and
 
  17  * limitations under the License.
 
  18  * ============LICENSE_END=========================================================
 
  21 package org.onap.bbs.event.processor.pipelines;
 
  23 import static org.onap.bbs.event.processor.config.ApplicationConstants.CONSUME_CPE_AUTHENTICATION_TASK_NAME;
 
  24 import static org.onap.bbs.event.processor.config.ApplicationConstants.RETRIEVE_HSI_CFS_SERVICE_INSTANCE_TASK_NAME;
 
  25 import static org.onap.bbs.event.processor.config.ApplicationConstants.RETRIEVE_PNF_TASK_NAME;
 
  26 import static org.onap.dcaegen2.services.sdk.rest.services.model.logging.MdcVariables.INSTANCE_UUID;
 
  27 import static org.onap.dcaegen2.services.sdk.rest.services.model.logging.MdcVariables.RESPONSE_CODE;
 
  29 import java.time.Duration;
 
  30 import java.time.Instant;
 
  31 import java.util.HashMap;
 
  33 import java.util.Optional;
 
  34 import java.util.UUID;
 
  35 import java.util.concurrent.TimeoutException;
 
  37 import javax.net.ssl.SSLException;
 
  39 import org.onap.bbs.event.processor.config.ApplicationConfiguration;
 
  40 import org.onap.bbs.event.processor.exceptions.AaiTaskException;
 
  41 import org.onap.bbs.event.processor.exceptions.DmaapException;
 
  42 import org.onap.bbs.event.processor.exceptions.EmptyDmaapResponseException;
 
  43 import org.onap.bbs.event.processor.model.ControlLoopPublisherDmaapModel;
 
  44 import org.onap.bbs.event.processor.model.CpeAuthenticationConsumerDmaapModel;
 
  45 import org.onap.bbs.event.processor.model.ImmutableControlLoopPublisherDmaapModel;
 
  46 import org.onap.bbs.event.processor.model.MetadataListAaiObject;
 
  47 import org.onap.bbs.event.processor.model.PnfAaiObject;
 
  48 import org.onap.bbs.event.processor.model.RelationshipListAaiObject;
 
  49 import org.onap.bbs.event.processor.model.ServiceInstanceAaiObject;
 
  50 import org.onap.bbs.event.processor.tasks.AaiClientTask;
 
  51 import org.onap.bbs.event.processor.tasks.DmaapCpeAuthenticationConsumerTask;
 
  52 import org.onap.bbs.event.processor.tasks.DmaapPublisherTask;
 
  53 import org.slf4j.Logger;
 
  54 import org.slf4j.LoggerFactory;
 
  56 import org.springframework.beans.factory.annotation.Autowired;
 
  57 import org.springframework.http.ResponseEntity;
 
  58 import org.springframework.stereotype.Component;
 
  59 import org.springframework.util.StringUtils;
 
  61 import reactor.core.publisher.Flux;
 
  62 import reactor.core.publisher.Mono;
 
  65 public class CpeAuthenticationPipeline {
 
  67     private static final Logger LOGGER = LoggerFactory.getLogger(CpeAuthenticationPipeline.class);
 
  69     private static final String DCAE_BBS_EVENT_PROCESSOR_MS_INSTANCE = "DCAE.BBS_event_processor_mSInstance";
 
  70     private static final String POLICY_VERSION = "1.0.0.5";
 
  71     private static final String POLICY_NAME = "CPE_Authentication";
 
  72     private static final String CLOSE_LOOP_TARGET_TYPE = "VM";
 
  73     private static final String CLOSED_LOOP_EVENT_STATUS = "ONSET";
 
  74     private static final String CLOSE_LOOP_VERSION = "1.0.2";
 
  75     private static final String CLOSE_LOOP_TARGET = "vserver.vserver-name";
 
  76     private static final String FROM = "DCAE";
 
  78     private DmaapCpeAuthenticationConsumerTask consumerTask;
 
  79     private DmaapPublisherTask publisherTask;
 
  80     private AaiClientTask aaiClientTask;
 
  82     private ApplicationConfiguration configuration;
 
  84     private Map<String, String> mdcContextMap;
 
  87     CpeAuthenticationPipeline(ApplicationConfiguration configuration,
 
  88                               DmaapCpeAuthenticationConsumerTask consumerTask,
 
  89                               DmaapPublisherTask publisherTask,
 
  90                               AaiClientTask aaiClientTask,
 
  91                               Map<String, String> mdcContextMap) {
 
  92         this.configuration = configuration;
 
  93         this.consumerTask = consumerTask;
 
  94         this.publisherTask = publisherTask;
 
  95         this.aaiClientTask = aaiClientTask;
 
  96         this.mdcContextMap = mdcContextMap;
 
 100      * PNF CPE Authentication processing pipeline for BBS uS.
 
 102     public void processPnfCpeAuthenticationEvents() {
 
 103         MDC.setContextMap(mdcContextMap);
 
 104         LOGGER.info("Process next CPE Authentication events");
 
 106                 .subscribe(this::onSuccess, this::onError, this::onComplete);
 
 107         LOGGER.trace("Reactive CPE Authentication pipeline subscribed - Execution started");
 
 110     Flux<ResponseEntity<String>> executePipeline() {
 
 112             // Consume CPE Authentication from DMaaP
 
 113             consumeCpeAuthenticationFromDmaap()
 
 114             // Fetch PNF from A&AI
 
 115             .flatMap(this::fetchPnfFromAai)
 
 116             // Fetch related HSI CFS instance from A&AI
 
 117             .flatMap(this::fetchHsiCfsServiceInstanceFromAai)
 
 118             // Trigger Policy for relocation
 
 119             .flatMap(this::triggerPolicy);
 
 122     private void onSuccess(ResponseEntity<String> responseCode) {
 
 123         MDC.put(RESPONSE_CODE, responseCode.getStatusCode().toString());
 
 124         LOGGER.info("CPE Authentication event successfully handled. "
 
 125                         + "Publishing to DMaaP for Policy returned a status code of ({} {})",
 
 126                 responseCode.getStatusCode().value(), responseCode.getStatusCode().getReasonPhrase());
 
 127         MDC.remove(RESPONSE_CODE);
 
 130     private void onError(Throwable throwable) {
 
 131         LOGGER.error("Aborted CPE Authentication events processing. Error: {}", throwable.getMessage());
 
 134     private void onComplete() {
 
 135         LOGGER.info("CPE Authentication processing pipeline has been completed");
 
 138     private Flux<PipelineState> consumeCpeAuthenticationFromDmaap() {
 
 139         return Flux.defer(() -> {
 
 140             MDC.put(INSTANCE_UUID, UUID.randomUUID().toString());
 
 142                 return consumerTask.execute(CONSUME_CPE_AUTHENTICATION_TASK_NAME)
 
 143                         .timeout(Duration.ofSeconds(configuration.getPipelinesTimeoutInSeconds()))
 
 145                             if (e instanceof TimeoutException) {
 
 146                                 LOGGER.warn("Timed out waiting for DMaaP response");
 
 147                             } else if (e instanceof EmptyDmaapResponseException) {
 
 148                                 LOGGER.warn("Nothing to consume from DMaaP");
 
 152                             e -> (e instanceof EmptyDmaapResponseException || e instanceof TimeoutException),
 
 155                             // For each message, we have to keep separate state. This state will be enhanced
 
 156                             // in each step and handed off to the next processing step
 
 157                             PipelineState state = new PipelineState();
 
 158                             state.setCpeAuthenticationEvent(event);
 
 161             } catch (SSLException e) {
 
 162                 return Flux.error(e);
 
 167     private Mono<PipelineState> fetchPnfFromAai(PipelineState state) {
 
 169         CpeAuthenticationConsumerDmaapModel vesEvent = state.getCpeAuthenticationEvent();
 
 170         String pnfName = vesEvent.getCorrelationId();
 
 171         String url = String.format("/aai/v14/network/pnfs/pnf/%s?depth=all", pnfName);
 
 172         LOGGER.debug("Processing Step: Retrieve PNF. Url: ({})", url);
 
 174         return aaiClientTask.executePnfRetrieval(RETRIEVE_PNF_TASK_NAME, url)
 
 175                 .timeout(Duration.ofSeconds(configuration.getPipelinesTimeoutInSeconds()))
 
 176                 .doOnError(TimeoutException.class,
 
 177                         e -> LOGGER.warn("Timed out waiting for A&AI response")
 
 179                 .doOnError(e -> LOGGER.error("Error while retrieving PNF: {}",
 
 183                     e -> e instanceof AaiTaskException || e instanceof TimeoutException,
 
 186                     state.setPnfAaiObject(p);
 
 191     private Mono<PipelineState> fetchHsiCfsServiceInstanceFromAai(PipelineState state) {
 
 193         if (state == null || state.getPnfAaiObject() == null) {
 
 197         PnfAaiObject pnf = state.getPnfAaiObject();
 
 198         // Assuming that the PNF will only have a single service-instance relationship pointing
 
 199         // towards the HSI CFS service
 
 200         String serviceInstanceId = pnf.getRelationshipListAaiObject().getRelationshipEntries()
 
 202                 .filter(e -> e.getRelatedTo().equals("service-instance"))
 
 203                 .flatMap(e -> e.getRelationshipData().stream())
 
 204                 .filter(d -> d.getRelationshipKey().equals("service-instance.service-instance-id"))
 
 205                 .map(RelationshipListAaiObject.RelationshipDataEntryAaiObject::getRelationshipValue)
 
 206                 .findFirst().orElse("");
 
 208         if (StringUtils.isEmpty(serviceInstanceId)) {
 
 209             LOGGER.error("Unable to retrieve HSI CFS service instance from PNF {}",
 
 210                     state.getPnfAaiObject().getPnfName());
 
 214         String url = String.format("/aai/v14/nodes/service-instances/service-instance/%s?depth=all",
 
 216         LOGGER.debug("Processing Step: Retrieve HSI CFS Service. Url: ({})", url);
 
 217         return aaiClientTask.executeServiceInstanceRetrieval(RETRIEVE_HSI_CFS_SERVICE_INSTANCE_TASK_NAME, url)
 
 218                 .timeout(Duration.ofSeconds(configuration.getPipelinesTimeoutInSeconds()))
 
 219                 .doOnError(TimeoutException.class,
 
 220                         e -> LOGGER.warn("Timed out waiting for A&AI response")
 
 222                 .doOnError(e -> LOGGER.error("Error while retrieving HSI CFS Service instance: {}",
 
 226                     e -> e instanceof AaiTaskException || e instanceof TimeoutException,
 
 229                     state.setHsiCfsServiceInstance(s);
 
 234     private Mono<ResponseEntity<String>> triggerPolicy(PipelineState state) {
 
 236         if (state == null || state.getHsiCfsServiceInstance() == null) {
 
 240         // At this point, we must check if the PNF RGW MAC address matches the value extracted from VES event
 
 241         if (!isCorrectMacAddress(state)) {
 
 242             LOGGER.warn("Processing stopped. RGW MAC address taken from event ({}) "
 
 243                             + "does not match with A&AI metadata corresponding value",
 
 244                     state.getCpeAuthenticationEvent().getRgwMacAddress());
 
 248         ControlLoopPublisherDmaapModel event = buildTriggeringPolicyEvent(state);
 
 249         return publisherTask.execute(event)
 
 250                 .timeout(Duration.ofSeconds(configuration.getPipelinesTimeoutInSeconds()))
 
 251                 .doOnError(TimeoutException.class,
 
 252                         e -> LOGGER.warn("Timed out waiting for DMaaP publish confirmation")
 
 254                 .doOnError(e -> LOGGER.error("Error while triggering Policy: {}", e.getMessage()))
 
 256                     e -> e instanceof DmaapException || e instanceof TimeoutException,
 
 261     private boolean isCorrectMacAddress(PipelineState state) {
 
 262         // We need to check if the RGW MAC address received in VES event matches the one found in
 
 263         // HSIA CFS service (in its metadata section)
 
 264         Optional<MetadataListAaiObject> optionalMetadata = state.getHsiCfsServiceInstance()
 
 265                 .getMetadataListAaiObject();
 
 266         String eventRgwMacAddress = state.getCpeAuthenticationEvent().getRgwMacAddress().orElse("");
 
 267         return optionalMetadata
 
 268                 .map(list -> list.getMetadataEntries()
 
 270                 .anyMatch(m -> m.getMetaname().equals("rgw-mac-address")
 
 271                         && m.getMetavalue().equals(eventRgwMacAddress)))
 
 275     private ControlLoopPublisherDmaapModel buildTriggeringPolicyEvent(PipelineState state) {
 
 277         String cfsServiceInstanceId = state.getHsiCfsServiceInstance().getServiceInstanceId();
 
 279         Map<String, String> enrichmentData = new HashMap<>();
 
 280         enrichmentData.put("service-information.hsia-cfs-service-instance-id", cfsServiceInstanceId);
 
 281         enrichmentData.put("cpe.old-authentication-state", state.cpeAuthenticationEvent.getOldAuthenticationState());
 
 282         enrichmentData.put("cpe.new-authentication-state", state.cpeAuthenticationEvent.getNewAuthenticationState());
 
 283         String swVersion = state.getCpeAuthenticationEvent().getSwVersion().orElse("");
 
 284         if (!StringUtils.isEmpty(swVersion)) {
 
 285             enrichmentData.put("cpe.swVersion", swVersion);
 
 288         ControlLoopPublisherDmaapModel triggerEvent = ImmutableControlLoopPublisherDmaapModel.builder()
 
 289                 .closedLoopEventClient(DCAE_BBS_EVENT_PROCESSOR_MS_INSTANCE)
 
 290                 .policyVersion(POLICY_VERSION)
 
 291                 .policyName(POLICY_NAME)
 
 292                 .policyScope(configuration.getCpeAuthenticationCloseLoopPolicyScope())
 
 293                 .targetType(CLOSE_LOOP_TARGET_TYPE)
 
 294                 .aaiEnrichmentData(enrichmentData)
 
 295                 .closedLoopAlarmStart(Instant.now().getEpochSecond())
 
 296                 .closedLoopEventStatus(CLOSED_LOOP_EVENT_STATUS)
 
 297                 .closedLoopControlName(configuration.getCpeAuthenticationCloseLoopControlName())
 
 298                 .version(CLOSE_LOOP_VERSION)
 
 299                 .target(CLOSE_LOOP_TARGET)
 
 300                 .requestId(UUID.randomUUID().toString())
 
 303         LOGGER.debug("Processing Step: Publish for Policy");
 
 304         LOGGER.trace("Trigger Policy event: ({})",triggerEvent);
 
 308     private static class PipelineState {
 
 310         private CpeAuthenticationConsumerDmaapModel cpeAuthenticationEvent;
 
 311         private PnfAaiObject pnfAaiObject;
 
 312         private ServiceInstanceAaiObject hsiCfsServiceInstance;
 
 314         CpeAuthenticationConsumerDmaapModel getCpeAuthenticationEvent() {
 
 315             return cpeAuthenticationEvent;
 
 318         void setCpeAuthenticationEvent(CpeAuthenticationConsumerDmaapModel cpeAuthenticationEvent) {
 
 319             this.cpeAuthenticationEvent = cpeAuthenticationEvent;
 
 322         PnfAaiObject getPnfAaiObject() {
 
 326         void setPnfAaiObject(PnfAaiObject pnfAaiObject) {
 
 327             this.pnfAaiObject = pnfAaiObject;
 
 330         ServiceInstanceAaiObject getHsiCfsServiceInstance() {
 
 331             return hsiCfsServiceInstance;
 
 334         void setHsiCfsServiceInstance(ServiceInstanceAaiObject hsiCfsServiceInstance) {
 
 335             this.hsiCfsServiceInstance = hsiCfsServiceInstance;