diff options
Diffstat (limited to 'src/main/java/org/onap/a1pesimulator/service/ves')
11 files changed, 1029 insertions, 0 deletions
diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/OnEventAction.java b/src/main/java/org/onap/a1pesimulator/service/ves/OnEventAction.java new file mode 100644 index 0000000..b34594a --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/OnEventAction.java @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import org.onap.a1pesimulator.data.ves.Event; + +@FunctionalInterface +public interface OnEventAction { + + void onEvent(Event event); +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanCellEventCustomizer.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanCellEventCustomizer.java new file mode 100644 index 0000000..9922329 --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanCellEventCustomizer.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import java.util.List; +import java.util.Optional; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.data.ves.MeasurementFields.AdditionalMeasurement; +import org.onap.a1pesimulator.service.ue.RanUeHolder; +import org.onap.a1pesimulator.service.ves.RanSendVesRunnable.EventCustomizer; +import org.onap.a1pesimulator.util.Constants; +import org.onap.a1pesimulator.util.JsonUtils; +import org.onap.a1pesimulator.util.RanVesUtils; +import org.springframework.stereotype.Service; + +@Service +public class RanCellEventCustomizer implements EventCustomizer { + + private static final String UE_PARAM_TRAFFIC_MODEL_RANGE = "[[20-50]]"; + private final RanUeHolder ranUeHolder; + + public RanCellEventCustomizer(RanUeHolder ueHolder) { + this.ranUeHolder = ueHolder; + } + + @Override + public Event apply(Event t) { + Event event = JsonUtils.INSTANCE.clone(t); + return customizeEvent(event); + } + + private Event customizeEvent(Event event) { + RanVesUtils.updateHeader(event); + enrichWithUeData(event); + randomizeEvent(event); + return event; + } + + private void randomizeEvent(Event event) { + List<AdditionalMeasurement> additionalMeasurementsToRandomize = + event.getMeasurementFields().getAdditionalMeasurements(); + event.getMeasurementFields().setAdditionalMeasurements( + RanVesUtils.randomizeAdditionalMeasurements(additionalMeasurementsToRandomize)); + } + + private void enrichWithUeData(Event event) { + + Optional<AdditionalMeasurement> identity = event.getMeasurementFields().getAdditionalMeasurements().stream() + .filter(msrmnt -> Constants.MEASUREMENT_FIELD_IDENTIFIER + .equalsIgnoreCase( + msrmnt.getName())) + .findAny(); + identity.ifPresent(m -> addTrafficModelMeasurement(event, m)); + } + + private void addTrafficModelMeasurement(Event event, AdditionalMeasurement identity) { + AdditionalMeasurement trafficModelMeasurement = + RanVesUtils.buildTrafficModelMeasurement(identity, ranUeHolder, UE_PARAM_TRAFFIC_MODEL_RANGE); + event.getMeasurementFields().getAdditionalMeasurements().add(trafficModelMeasurement); + } +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanCellFailureEventCustomizer.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanCellFailureEventCustomizer.java new file mode 100644 index 0000000..ac2c4fc --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanCellFailureEventCustomizer.java @@ -0,0 +1,225 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import java.text.MessageFormat; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.data.ves.MeasurementFields.AdditionalMeasurement; +import org.onap.a1pesimulator.service.ue.RanUeHolder; +import org.onap.a1pesimulator.service.ves.RanSendVesRunnable.EventCustomizer; +import org.onap.a1pesimulator.util.Constants; +import org.onap.a1pesimulator.util.JsonUtils; +import org.onap.a1pesimulator.util.RanVesUtils; + +public class RanCellFailureEventCustomizer implements EventCustomizer { + + private static final String UE_PARAM_TRAFFIC_MODEL_RANGE = "[[50->10]]"; + private final RanUeHolder ranUeHolder; + private final Event event; + + private final Map<Key, Value> additionalMeasurementsValues = new HashMap<>(); + private final ValueFactory valueFactory; + + public RanCellFailureEventCustomizer(Event event, RanUeHolder ranUeHolder) { + this.ranUeHolder = ranUeHolder; + this.event = event; + valueFactory = new ValueFactory(); + collectAdditionalMeasurementValues(event); + } + + @Override + public Event apply(Event t) { + return customizeEvent(JsonUtils.INSTANCE.clone(this.event)); + } + + private void collectAdditionalMeasurementValues(Event event) { + Collection<AdditionalMeasurement> additionalMeasurementsToResolve = + event.getMeasurementFields().getAdditionalMeasurements(); + additionalMeasurementsToResolve.forEach(this::collectAdditionalMeasurementValue); + } + + private void collectAdditionalMeasurementValue(AdditionalMeasurement m) { + for (Entry<String, String> entry : m.getHashMap().entrySet()) { + if (!RanVesUtils.isRange(entry.getValue())) { + continue; + } + additionalMeasurementsValues + .putIfAbsent(new Key(m.getName(), entry.getKey()), valueFactory.getInstance(entry.getValue())); + } + } + + private Event customizeEvent(Event event) { + RanVesUtils.updateHeader(event); + enrichWithUeData(event); + resolveRanges(event); + return event; + } + + private void resolveRanges(Event event) { + List<AdditionalMeasurement> additionalMeasurementsToResolve = + event.getMeasurementFields().getAdditionalMeasurements(); + + additionalMeasurementsToResolve.forEach(this::resolveRanges); + event.getMeasurementFields().setAdditionalMeasurements(additionalMeasurementsToResolve); + } + + private void resolveRanges(AdditionalMeasurement m) { + for (Entry<String, String> entry : m.getHashMap().entrySet()) { + Key key = new Key(m.getName(), entry.getKey()); + if (!additionalMeasurementsValues.containsKey(key)) { + continue; + } + Value value = additionalMeasurementsValues.get(key); + value.current = value.calculateCurrentValue(); + entry.setValue(value.current.toString()); + } + } + + private void enrichWithUeData(Event event) { + + Optional<AdditionalMeasurement> identity = event.getMeasurementFields().getAdditionalMeasurements().stream() + .filter(msrmnt -> Constants.MEASUREMENT_FIELD_IDENTIFIER + .equalsIgnoreCase( + msrmnt.getName())) + .findAny(); + identity.ifPresent(m -> addTrafficModelMeasurement(event, m)); + } + + private void addTrafficModelMeasurement(Event event, AdditionalMeasurement identity) { + AdditionalMeasurement trafficModelMeasurement = + RanVesUtils.buildTrafficModelMeasurement(identity, ranUeHolder, UE_PARAM_TRAFFIC_MODEL_RANGE); + event.getMeasurementFields().getAdditionalMeasurements().add(trafficModelMeasurement); + + collectAdditionalMeasurementValue(trafficModelMeasurement); + } + + // -----------helper classes + + private static class ValueFactory { + + public Value getInstance(String value) { + String[] split; + if (RanVesUtils.isRandomRange(value)) { + split = RanVesUtils.splitRandomRange(value); + return new RandomValue(Integer.valueOf(split[0]), Integer.valueOf(split[1])); + } + if (RanVesUtils.isTrandingRange(value)) { + split = RanVesUtils.splitTrendingRange(value); + Integer start = Integer.valueOf(split[0]); + Integer end = Integer.valueOf(split[1]); + if (start < end) { + return new RaisingValue(start, end); + } else if (start > end) { + return new DecreasingValue(start, end); + } + } + throw new RuntimeException(MessageFormat.format("Cannot instantiate Value from string: {0}", value)); + } + } + + private abstract static class Value { + + protected Integer start; + protected Integer end; + protected Integer current; + + public Value(Integer start, Integer end) { + this.start = start; + this.end = end; + } + + public abstract Integer calculateCurrentValue(); + } + + private static class RaisingValue extends Value { + + private int increment; + + public RaisingValue(Integer start, Integer end) { + super(start, end); + } + + @Override + public Integer calculateCurrentValue() { + if (current == null) { + return start; + } + if (increment == 0) { + increment = 1; + } else { + increment = increment * 2; + } + Integer result = start + increment; + if (result > end) { + increment = 1; + return end; + } + return result; + } + } + + private static class DecreasingValue extends Value { + + private int decrement; + + public DecreasingValue(Integer start, Integer end) { + super(start, end); + } + + @Override + public Integer calculateCurrentValue() { + if (current == null) { + return start; + } + if (decrement == 0) { + decrement = 1; + } else { + decrement = decrement * 2; + } + Integer result = start - decrement; + if (result < end) { + return end; + } + return result; + } + } + + private static class RandomValue extends Value { + + public RandomValue(Integer start, Integer end) { + super(start, end); + } + + @Override + public Integer calculateCurrentValue() { + return RanVesUtils.getRandomNumber(start, end); + } + } + + @AllArgsConstructor + @EqualsAndHashCode + private static class Key { + + private String paramName; + private String mapKey; + } +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanCheckCellIsDeadOnEvent.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanCheckCellIsDeadOnEvent.java new file mode 100644 index 0000000..1330e04 --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanCheckCellIsDeadOnEvent.java @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import static org.onap.a1pesimulator.service.cell.RanCellStateService.TOPIC_CELL; + +import java.util.Optional; +import org.onap.a1pesimulator.data.cell.CellDetails; +import org.onap.a1pesimulator.data.cell.state.CellStateEnum; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.data.ves.MeasurementFields; +import org.onap.a1pesimulator.service.cell.RanCellsHolder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.stereotype.Service; + +@Service +public class RanCheckCellIsDeadOnEvent implements OnEventAction { + + private static final Logger log = LoggerFactory.getLogger(RanCheckCellIsDeadOnEvent.class); + + private final RanCellsHolder ranCellsHolder; + private final SimpMessagingTemplate messagingTemplate; + + private final Integer failingModeThroughputValue; + private final Integer failingModeLatencyValue; + private final Integer failingCheckoutDelayTimeInSec; + + private static final int TO_MICRO_SEC = 1_000_000; + + public RanCheckCellIsDeadOnEvent(RanCellsHolder ranCellsHolder, SimpMessagingTemplate messagingTemplate, + @Value("${ves.failing.throughput}") Integer failingModeThroughputValue, + @Value("${ves.failing.latency}") Integer failingModeLatencyValue, + @Value("${ves.failing.checkout.delay}") Integer failingCheckoutDelayTimeInSec) { + this.ranCellsHolder = ranCellsHolder; + this.messagingTemplate = messagingTemplate; + + this.failingModeThroughputValue = failingModeThroughputValue; + this.failingModeLatencyValue = failingModeLatencyValue; + this.failingCheckoutDelayTimeInSec = failingCheckoutDelayTimeInSec; + } + + @Override + public void onEvent(Event event) { + Optional<String> cellId = getCellIdentifier(event); + Optional<String> throughput = getCellThroughput(event); + Optional<String> latency = getCellLatency(event); + + if (cellId.isPresent() && throughput.isPresent() && latency.isPresent()) { + checkCell(cellId.get(), Integer.parseInt(throughput.get()), Integer.parseInt(latency.get()), + event.getCommonEventHeader().getLastEpochMicrosec()); + } + } + + private void checkCell(String cellId, Integer throughput, Integer latency, Long lastEpochMicrosec) { + if (throughput <= failingModeThroughputValue && latency >= failingModeLatencyValue) { + log.info("Failure mode detected for cell {}", cellId); + processSleepingMode(cellId, lastEpochMicrosec); + } + } + + private void processSleepingMode(String cellId, Long lastEpochMicrosec) { + CellDetails cell = ranCellsHolder.getCellById(cellId); + if (cell.getCellStateMachine().getState() == CellStateEnum.GOING_TO_SLEEP) { + Optional<RanCellsHolder.CellInFailureMode> cellInFailureModeOpt = + ranCellsHolder.getCellsInFailureMode(cellId); + if (cellInFailureModeOpt.isPresent()) { + RanCellsHolder.CellInFailureMode cellInFailureMode = cellInFailureModeOpt.get(); + if (cellInFailureMode.getSleepingModeDetectedTime() == null) { + cellInFailureMode.setSleepingModeDetectedTime(lastEpochMicrosec); + } else { + long waitingEpochMicrosec = addDelayTime(cellInFailureMode.getSleepingModeDetectedTime()); + if (lastEpochMicrosec >= waitingEpochMicrosec) { + log.info("Cell {} is sleeping!", cellId); + cell.nextState(); + messagingTemplate.convertAndSend(TOPIC_CELL, cell); + } + } + } + } + } + + private Optional<String> getCellIdentifier(Event event) { + return getValueFromAdditionalMeasurement(event, "identifier"); + } + + private Optional<String> getCellThroughput(Event event) { + return getValueFromAdditionalMeasurement(event, "throughput"); + } + + private Optional<String> getCellLatency(Event event) { + return getValueFromAdditionalMeasurement(event, "latency"); + } + + private Optional<String> getValueFromAdditionalMeasurement(Event event, String key) { + Optional<MeasurementFields.AdditionalMeasurement> measurement = getAdditionalMeasurement(event, key); + return measurement.map(this::getValueFromAdditionalMeasurement); + } + + private String getValueFromAdditionalMeasurement(MeasurementFields.AdditionalMeasurement measurement) { + return measurement.getHashMap().get("value"); + } + + private Optional<MeasurementFields.AdditionalMeasurement> getAdditionalMeasurement(Event event, + String additionalMeasurement) { + return event.getMeasurementFields().getAdditionalMeasurements().stream() + .filter(e -> e.getName().equals(additionalMeasurement)).findFirst(); + } + + private long addDelayTime(long epoch) { + return epoch + failingCheckoutDelayTimeInSec * TO_MICRO_SEC; + } +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanEventCustomizerFactory.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanEventCustomizerFactory.java new file mode 100644 index 0000000..3fbeda9 --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanEventCustomizerFactory.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import java.text.MessageFormat; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.service.ue.RanUeHolder; +import org.onap.a1pesimulator.service.ves.RanSendVesRunnable.EventCustomizer; +import org.springframework.stereotype.Component; + +@Component +public class RanEventCustomizerFactory { + + private final EventCustomizer regularEventCustomizer; + private final RanUeHolder ranUeHolder; + + public RanEventCustomizerFactory(EventCustomizer regularEventCustomizer, RanUeHolder ranUeHolder) { + this.ranUeHolder = ranUeHolder; + this.regularEventCustomizer = regularEventCustomizer; + } + + public EventCustomizer getEventCustomizer(Event event, Mode mode) { + switch (mode) { + case REGULAR: + return regularEventCustomizer; + case FAILURE: + return new RanCellFailureEventCustomizer(event, ranUeHolder); + default: + throw new RuntimeException( + MessageFormat.format("Cannot construct event customizer for mode: {0}", mode)); + } + } + + public enum Mode { + REGULAR, FAILURE + } +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanSendVesRunnable.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanSendVesRunnable.java new file mode 100644 index 0000000..7378bc0 --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanSendVesRunnable.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import java.util.Collection; +import java.util.function.Function; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.exception.VesBrokerException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RanSendVesRunnable implements Runnable { + + private static final Logger log = LoggerFactory.getLogger(RanSendVesRunnable.class); + + private final RanVesSender vesSender; + private Event event; + private final EventCustomizer eventCustomizer; + private final Collection<OnEventAction> onEventAction; + + public RanSendVesRunnable(RanVesSender vesSender, Event event, EventCustomizer eventCustomizer, + Collection<OnEventAction> onEventActions) { + this.vesSender = vesSender; + this.event = event; + this.eventCustomizer = eventCustomizer; + this.onEventAction = onEventActions; + } + + @Override + public void run() { + try { + Event customizedEvent = eventCustomizer.apply(event); + onEventAction.forEach(action -> action.onEvent(customizedEvent)); + vesSender.send(customizedEvent); + } catch (VesBrokerException e) { + log.error("Sending scheduled event failed: {}", e.getMessage()); + } + } + + public void updateEvent(Event event) { + this.event = event; + } + + @FunctionalInterface + public interface EventCustomizer extends Function<Event, Event> { } +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanVesBrokerService.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesBrokerService.java new file mode 100644 index 0000000..8a90d46 --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesBrokerService.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.data.ves.RanPeriodicVesEvent; +import org.springframework.http.ResponseEntity; + +public interface RanVesBrokerService { + + ResponseEntity<String> startSendingVesEvents(String identifier, Event vesEvent, Integer interval); + + Optional<RanPeriodicVesEvent> stopSendingVesEvents(String identifier); + + Map<String, RanPeriodicVesEvent> getPeriodicEventsCache(); + + Collection<String> getEnabledEventElementIdentifiers(); + + Event getEventStructure(String identifier); + + Event startSendingFailureVesEvents(String identifier); + + Event getGlobalPmVesStructure(); + + void setGlobalPmVesStructure(Event event); + + Integer getGlobalVesInterval(); + + void setGlobalVesInterval(Integer interval); +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanVesBrokerServiceImpl.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesBrokerServiceImpl.java new file mode 100644 index 0000000..861bd36 --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesBrokerServiceImpl.java @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.data.ves.MeasurementFields.AdditionalMeasurement; +import org.onap.a1pesimulator.data.ves.RanPeriodicVesEvent; +import org.onap.a1pesimulator.util.Constants; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +@Service +public class RanVesBrokerServiceImpl implements RanVesBrokerService { + + private final RanVesDataProvider vesDataProvider; + + private final RanVesHolder vesHolder; + + public RanVesBrokerServiceImpl(RanVesDataProvider vesDataProvider, RanVesHolder vesHolder) { + this.vesDataProvider = vesDataProvider; + this.vesHolder = vesHolder; + } + + @Override + public Map<String, RanPeriodicVesEvent> getPeriodicEventsCache() { + return vesHolder.getPeriodicEventsCache(); + } + + @Override + public ResponseEntity<String> startSendingVesEvents(String identifier, Event vesEvent, Integer interval) { + + enrichWithIdentifier(identifier, vesEvent); + vesHolder.startSendingVesEvents(identifier, vesEvent, interval); + + return ResponseEntity.accepted().body("VES Event sending started"); + } + + @Override + public Event startSendingFailureVesEvents(String identifier) { + + Event vesEvent = vesDataProvider.getFailurePmVesEvent(); + + enrichWithIdentifier(identifier, vesEvent); + vesHolder.startSendingFailureVesEvents(identifier, vesEvent); + return vesEvent; + } + + @Override + public Optional<RanPeriodicVesEvent> stopSendingVesEvents(String identifier) { + return vesHolder.stopSendingVesEvents(identifier); + } + + @Override + public Collection<String> getEnabledEventElementIdentifiers() { + return vesHolder.getEnabledEventElementIdentifiers(); + } + + @Override + public Event getEventStructure(String identifier) { + return vesHolder.getEventStructure(identifier); + } + + @Override + public Event getGlobalPmVesStructure() { + return vesDataProvider.getPmVesEvent(); + } + + @Override + public void setGlobalPmVesStructure(Event event) { + vesDataProvider.setPmVesEvent(event); + } + + @Override + public Integer getGlobalVesInterval() { + return vesDataProvider.getRegularVesInterval(); + } + + @Override + public void setGlobalVesInterval(Integer interval) { + vesDataProvider.setInterval(interval); + } + + private void enrichWithIdentifier(String identifier, Event event) { + if (event.getMeasurementFields() == null || event.getMeasurementFields().getAdditionalMeasurements() == null) { + return; + } + Collection<AdditionalMeasurement> additionalMeasurements = + event.getMeasurementFields().getAdditionalMeasurements(); + Optional<AdditionalMeasurement> identityOpt = additionalMeasurements.stream() + .filter(m -> Constants.MEASUREMENT_FIELD_IDENTIFIER + .equalsIgnoreCase(m.getName())) + .findAny(); + if (identityOpt.isPresent()) { + identityOpt.get().getHashMap().put(Constants.MEASUREMENT_FIELD_IDENTIFIER, identifier); + } else { + AdditionalMeasurement measurement = new AdditionalMeasurement(); + measurement.setName(Constants.MEASUREMENT_FIELD_IDENTIFIER); + measurement.setHashMap(Collections.singletonMap(Constants.MEASUREMENT_FIELD_VALUE, identifier)); + additionalMeasurements.add(measurement); + } + } + +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanVesDataProvider.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesDataProvider.java new file mode 100644 index 0000000..95743f3 --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesDataProvider.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import java.io.IOException; +import java.net.URL; +import lombok.Setter; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.util.JsonUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.stereotype.Service; + +@Service +public class RanVesDataProvider { + + private static final String PM_VES_LOCATION = "classpath:pmVes.json"; + private static final String PM_FAILURE_VES_LOCATION = "classpath:failurePmVes.json"; + + @Setter + private Event pmVesEvent; + @Setter + private Event failurePmVesEvent; + @Setter + private Integer interval; + + private final Integer defaultInterval; + private final ResourceLoader resourceLoader; + + public RanVesDataProvider(@Value("${ves.defaultInterval}") Integer defaultInterval, ResourceLoader resourceLoader) { + this.defaultInterval = defaultInterval; + this.resourceLoader = resourceLoader; + } + + @Cacheable("pmVes") + public Event loadPmVesEvent() { + URL resourceUrl = getResourceURL(resourceLoader.getResource(PM_VES_LOCATION)); + return JsonUtils.INSTANCE.deserializeFromFileUrl(resourceUrl, Event.class); + } + + @Cacheable("failurePmVes") + public Event loadFailurePmVesEvent() { + URL resourceUrl = getResourceURL(resourceLoader.getResource(PM_FAILURE_VES_LOCATION)); + return JsonUtils.INSTANCE.deserializeFromFileUrl(resourceUrl, Event.class); + } + + public Integer getRegularVesInterval() { + if (interval == null) { + return defaultInterval; + } + return interval; + } + + public Integer getFailureVesInterval() { + return defaultInterval; + } + + public Event getPmVesEvent() { + if (pmVesEvent == null) { + return loadPmVesEvent(); + } + return pmVesEvent; + } + + public Event getFailurePmVesEvent() { + if (failurePmVesEvent == null) { + return loadFailurePmVesEvent(); + } + return failurePmVesEvent; + } + + private URL getResourceURL(Resource resource) { + try { + return resource.getURL(); + } catch (IOException e) { + throw new RuntimeException("Cannot get resource URL for: " + resource.getFilename()); + } + } +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanVesHolder.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesHolder.java new file mode 100644 index 0000000..d53d8dd --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesHolder.java @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import java.text.MessageFormat; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledFuture; +import java.util.function.BiFunction; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.data.ves.RanPeriodicVesEvent; +import org.onap.a1pesimulator.service.ves.RanEventCustomizerFactory.Mode; +import org.onap.a1pesimulator.service.ves.RanSendVesRunnable.EventCustomizer; +import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; +import org.springframework.stereotype.Service; + +@Service +public class RanVesHolder { + + private final Map<String, RanPeriodicVesEvent> periodicEventsCache = new ConcurrentHashMap<>(); + + private final RanVesDataProvider vesDataProvider; + private final RanEventCustomizerFactory eventCustomizerFactory; + private final ThreadPoolTaskScheduler vesPmThreadPoolTaskScheduler; + private final Collection<OnEventAction> onEventActions; + private final RanVesSender vesSender; + + public RanVesHolder(ThreadPoolTaskScheduler vesPmThreadPoolTaskScheduler, RanVesSender vesSender, + RanEventCustomizerFactory eventCustomizerFactory, RanVesDataProvider vesDataProvider, + Collection<OnEventAction> onEventActions) { + this.vesPmThreadPoolTaskScheduler = vesPmThreadPoolTaskScheduler; + this.vesSender = vesSender; + this.eventCustomizerFactory = eventCustomizerFactory; + this.vesDataProvider = vesDataProvider; + this.onEventActions = onEventActions; + } + + Map<String, RanPeriodicVesEvent> getPeriodicEventsCache() { + return periodicEventsCache; + } + + ResponseEntity<String> startSendingVesEvents(String identifier, Event vesEvent, Integer interval) { + + periodicEventsCache.compute(identifier, + new ThreadCacheUpdateFunction(vesPmThreadPoolTaskScheduler, vesEvent, interval, + eventCustomizerFactory.getEventCustomizer(vesEvent, Mode.REGULAR), onEventActions, vesSender)); + return ResponseEntity.accepted().body("VES Event sending started"); + } + + ResponseEntity<String> startSendingFailureVesEvents(String identifier, Event vesEvent) { + + periodicEventsCache.compute(identifier, new ThreadCacheUpdateFunction(vesPmThreadPoolTaskScheduler, vesEvent, + vesDataProvider.getFailureVesInterval(), + eventCustomizerFactory.getEventCustomizer(vesEvent, Mode.FAILURE), onEventActions, vesSender)); + return ResponseEntity.accepted().body("Failure VES Event sending started"); + } + + Optional<RanPeriodicVesEvent> stopSendingVesEvents(String identifier) { + RanPeriodicVesEvent periodicEvent = periodicEventsCache.remove(identifier); + if (periodicEvent == null) { + return Optional.empty(); + } + periodicEvent.getScheduledFuture().cancel(false); + return Optional.of(periodicEvent); + } + + Collection<String> getEnabledEventElementIdentifiers() { + return periodicEventsCache.keySet(); + } + + public boolean isEventEnabled(String identifier) { + return periodicEventsCache.containsKey(identifier); + } + + Event getEventStructure(String identifier) { + if (!periodicEventsCache.containsKey(identifier)) { + throw new IllegalArgumentException( + MessageFormat.format("Cannot find event for given source {0}", identifier)); + } + return periodicEventsCache.get(identifier).getEvent(); + } + + private static class ThreadCacheUpdateFunction + implements BiFunction<String, RanPeriodicVesEvent, RanPeriodicVesEvent> { + + private final Integer interval; + private final ThreadPoolTaskScheduler vesPmThreadPoolTaskScheduler; + private final Event vesEvent; + private final EventCustomizer eventCustomizer; + private final Collection<OnEventAction> onEventActions; + private final RanVesSender vesSender; + + public ThreadCacheUpdateFunction(ThreadPoolTaskScheduler vesPmThreadPoolTaskScheduler, Event vesEvent, + Integer interval, EventCustomizer eventCustomizer, Collection<OnEventAction> onEventActions, + RanVesSender vesSender) { + this.vesPmThreadPoolTaskScheduler = vesPmThreadPoolTaskScheduler; + this.vesEvent = vesEvent; + this.interval = interval; + this.eventCustomizer = eventCustomizer; + this.onEventActions = onEventActions; + this.vesSender = vesSender; + } + + @Override + public RanPeriodicVesEvent apply(String key, RanPeriodicVesEvent value) { + if (value != null) { + // if thread is registered then cancel it and schedule a new one + value.getScheduledFuture().cancel(false); + } + RanSendVesRunnable sendVesRunnable = + new RanSendVesRunnable(vesSender, vesEvent, eventCustomizer, onEventActions); + ScheduledFuture<?> scheduledFuture = + vesPmThreadPoolTaskScheduler.scheduleAtFixedRate(sendVesRunnable, interval * 1000L); + return RanPeriodicVesEvent.builder().event(vesEvent).interval(interval).scheduledFuture(scheduledFuture) + .sendVesRunnable(sendVesRunnable).build(); + } + + } +} diff --git a/src/main/java/org/onap/a1pesimulator/service/ves/RanVesSender.java b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesSender.java new file mode 100644 index 0000000..9c50197 --- /dev/null +++ b/src/main/java/org/onap/a1pesimulator/service/ves/RanVesSender.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2021 Samsung Electronics + * 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 org.onap.a1pesimulator.service.ves; + +import org.onap.a1pesimulator.data.VnfConfig; +import org.onap.a1pesimulator.data.ves.CommonEventHeader; +import org.onap.a1pesimulator.data.ves.Event; +import org.onap.a1pesimulator.exception.VesBrokerException; +import org.onap.a1pesimulator.util.JsonUtils; +import org.onap.a1pesimulator.util.VnfConfigReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class RanVesSender { + + private static final Logger log = LoggerFactory.getLogger(RanVesSender.class); + + private RestTemplate restTemplate; + + private String vesCollectorProtocol; + + private String vesCollectorPath; + + private VnfConfigReader vnfConfigReader; + + public RanVesSender(RestTemplate restTemplate, VnfConfigReader vnfConfigReader, + @Value("${ves.collector.protocol}") String vesCollectorProtocol, + @Value("${ves.collector.endpoint}") String vesCollectorPath) { + this.restTemplate = restTemplate; + this.vnfConfigReader = vnfConfigReader; + this.vesCollectorProtocol = vesCollectorProtocol; + this.vesCollectorPath = vesCollectorPath; + } + + public ResponseEntity<String> send(Event vesEvent) throws VesBrokerException { + VnfConfig vnfConfig = vnfConfigReader.getVnfConfig(); + String url = getVesCollectorUrl(vnfConfig); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setBasicAuth(vnfConfig.getVesUser(), vnfConfig.getVesPassword()); + + setVnfInfo(vesEvent, vnfConfig); + String event = JsonUtils.INSTANCE.objectToPrettyString(vesEvent); + + log.info("Sending following VES event: {}", event); + + HttpEntity<String> entity = new HttpEntity<>(event, headers); + ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); + + log.debug("Response received: {}", response); + + if (response.getStatusCode() == HttpStatus.OK || response.getStatusCode() == HttpStatus.ACCEPTED) { + return response; + } else { + String errorMsg = + "Failed to send VES event to the collector with response status code:" + response.getStatusCode(); + throw new VesBrokerException(errorMsg); + } + } + + private String getVesCollectorUrl(VnfConfig vnfConfig) { + return vesCollectorProtocol + "://" + vnfConfig.getVesHost() + ":" + vnfConfig.getVesPort() + vesCollectorPath; + } + + private void setVnfInfo(Event vesEvent, VnfConfig vnfConfig) { + CommonEventHeader header = vesEvent.getCommonEventHeader(); + header.setSourceId(vnfConfig.getVnfId()); + header.setSourceName(vnfConfig.getVnfName()); + vesEvent.setCommonEventHeader(header); + } +} |