diff options
19 files changed, 1135 insertions, 134 deletions
diff --git a/cmso-database/src/main/resources/optimizer-dbchanges/onap-optimizer-v1-schema.sql b/cmso-database/src/main/resources/optimizer-dbchanges/onap-optimizer-v1-schema.sql index 02daa60..d91a17e 100644 --- a/cmso-database/src/main/resources/optimizer-dbchanges/onap-optimizer-v1-schema.sql +++ b/cmso-database/src/main/resources/optimizer-dbchanges/onap-optimizer-v1-schema.sql @@ -7,6 +7,7 @@ CREATE TABLE IF NOT EXISTS `optimizer`.`request` ( request_start BIGINT(20) NULL DEFAULT NULL, request_end BIGINT(20) NULL DEFAULT NULL, status VARCHAR(45) NULL DEFAULT NULL, + message MEDIUMTEXT NULL DEFAULT NULL, PRIMARY KEY (`uuid`)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; diff --git a/cmso-optimizer/data/policies/EveryDay_00_06.json b/cmso-optimizer/data/policies/EveryDay_00_06.json new file mode 100644 index 0000000..53350ff --- /dev/null +++ b/cmso-optimizer/data/policies/EveryDay_00_06.json @@ -0,0 +1,47 @@ +{ + "service": "TimeLimitAndVerticalTopology", + "policyName": "CMSO.Weekday_00_06", + "description": "dev instance", + "templateVersion": "Dublin", + "version": "0001", + "priority": "4", + "riskType": "test", + "riskLevel": "3", + "guard": "False", + "content": { + "serviceType": "networkOnDemand", + "identity": "vnf_upgrade_policy", + "policyScope": { + "serviceType": ["networkOnDemand"], + "aicZone": [ + " " + ], + "entityType": ["vnf"] + }, + "timeSchedule": { + "allowedPeriodicTime": [ + { + "day": "weekday", + "timeRange": [ + { + "start_time": "00:00:00+00:00", + "end_time": "06:00:00+00:00" + } + ] + }, + { + "day": "weekend", + "timeRange": [ + { + "start_time": "00:00:00+00:00", + "end_time": "06:00:00+00:00" + } + ] + } + ] + }, + "nodeType": ["vnf"], + "type": "timeLimitAndVerticalTopology", + "conflictScope": "vnf_pserver" + } +}
\ No newline at end of file diff --git a/cmso-optimizer/data/policies/Weekend_00_06.json b/cmso-optimizer/data/policies/Weekend_00_06.json new file mode 100644 index 0000000..5e26cb4 --- /dev/null +++ b/cmso-optimizer/data/policies/Weekend_00_06.json @@ -0,0 +1,38 @@ +{ + "service": "TimeLimitAndVerticalTopology", + "policyName": "CMSO.Weekday_00_06", + "description": "dev instance", + "templateVersion": "Dublin", + "version": "0001", + "priority": "4", + "riskType": "test", + "riskLevel": "3", + "guard": "False", + "content": { + "serviceType": "networkOnDemand", + "identity": "vnf_upgrade_policy", + "policyScope": { + "serviceType": ["networkOnDemand"], + "aicZone": [ + " " + ], + "entityType": ["vnf"] + }, + "timeSchedule": { + "allowedPeriodicTime": [ + { + "day": "weekend", + "timeRange": [ + { + "start_time": "00:00:00+00:00", + "end_time": "06:00:00+00:00" + } + ] + } + ] + }, + "nodeType": ["vnf"], + "type": "timeLimitAndVerticalTopology", + "conflictScope": "vnf_pserver" + } +}
\ No newline at end of file diff --git a/cmso-optimizer/etc/config/optimizer.properties b/cmso-optimizer/etc/config/optimizer.properties index 8b8c6a1..ac39ec8 100644 --- a/cmso-optimizer/etc/config/optimizer.properties +++ b/cmso-optimizer/etc/config/optimizer.properties @@ -45,5 +45,5 @@ logging.level.org.hibernate=TRACE cmso.topology.create.request.url=http://127.0.0.1:7998/topology/v1/current - +cmso.ticket.create.request.url=http://127.0.0.1:7999/ticketmgt/v1/activetickets cmso.local.policy.folder=data/policies
\ No newline at end of file diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/PolicyManager.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/PolicyManager.java index d6ae196..d82932b 100644 --- a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/PolicyManager.java +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/PolicyManager.java @@ -44,12 +44,9 @@ public class PolicyManager { TimeLimitAndVerticalTopology returnPolicy = null; if (policy != null) { ObjectMapper om = new ObjectMapper(); - try - { + try { returnPolicy = om.convertValue(policy.getContent(), TimeLimitAndVerticalTopology.class); - } - catch (Exception e) - { + } catch (Exception e) { Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); } } diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/AllowedPeriodicTime.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/AllowedPeriodicTime.java index 4bc0f71..abdb5f8 100644 --- a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/AllowedPeriodicTime.java +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/AllowedPeriodicTime.java @@ -36,28 +36,35 @@ import java.util.List; */ public class AllowedPeriodicTime { - public enum Day - { - weekday("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"), - weekend("RRULE:FREQ=WEEKLY;BYDAY=SA,SU"), - ; + public enum Day { + weekday("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"), weekend("RRULE:FREQ=WEEKLY;BYDAY=SA,SU"),; private String rrule; - private Day(String rrule) {this.rrule = rrule;} - public String getRrule() {return rrule;} + + private Day(String rrule) { + this.rrule = rrule; + } + + public String getRrule() { + return rrule; + } } private Day day; private List<TimeRange> timeRange; + public Day getDay() { return day; } + public void setDay(Day day) { this.day = day; } + public List<TimeRange> getTimeRange() { return timeRange; } + public void setTimeRange(List<TimeRange> timeRange) { this.timeRange = timeRange; } diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/Policy.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/Policy.java index 50acd9b..f6bdf74 100644 --- a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/Policy.java +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/Policy.java @@ -71,63 +71,83 @@ public class Policy { private String riskLevel; private String guard; private Object content; + public String getService() { return service; } + public void setService(String service) { this.service = service; } + public String getPolicyName() { return policyName; } + public void setPolicyName(String policyName) { this.policyName = policyName; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public String getTemplateVersion() { return templateVersion; } + public void setTemplateVersion(String templateVersion) { this.templateVersion = templateVersion; } + public String getVersion() { return version; } + public void setVersion(String version) { this.version = version; } + public String getPriority() { return priority; } + public void setPriority(String priority) { this.priority = priority; } + public String getRiskType() { return riskType; } + public void setRiskType(String riskType) { this.riskType = riskType; } + public String getRiskLevel() { return riskLevel; } + public void setRiskLevel(String riskLevel) { this.riskLevel = riskLevel; } + public String getGuard() { return guard; } + public void setGuard(String guard) { this.guard = guard; } + public Object getContent() { return content; } + public void setContent(Object content) { this.content = content; } diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/TimeLimitAndVerticalTopology.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/TimeLimitAndVerticalTopology.java index 58846f4..7af22e3 100644 --- a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/TimeLimitAndVerticalTopology.java +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/TimeLimitAndVerticalTopology.java @@ -51,8 +51,7 @@ import java.util.List; } */ -public class TimeLimitAndVerticalTopology -{ +public class TimeLimitAndVerticalTopology { public enum ConflictScope { timeLimitAndVerticalTopology, @@ -72,42 +71,55 @@ public class TimeLimitAndVerticalTopology public String getServiceType() { return serviceType; } + public void setServiceType(String serviceType) { this.serviceType = serviceType; } + public String getIdentity() { return identity; } + public void setIdentity(String identity) { this.identity = identity; } + public PolicyScope getPolicyScope() { return policyScope; } + public void setPolicyScope(PolicyScope policyScope) { this.policyScope = policyScope; } + public TimeSchedule getTimeSchedule() { return timeSchedule; } + public void setTimeSchedule(TimeSchedule timeSchedule) { this.timeSchedule = timeSchedule; } + public List<String> getNodeType() { return nodeType; } + public void setNodeType(List<String> nodeType) { this.nodeType = nodeType; } + public String getType() { return type; } + public void setType(String type) { this.type = type; } + public String getConflictScope() { return conflictScope; } + public void setConflictScope(String conflictScope) { this.conflictScope = conflictScope; } diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/TimeRange.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/TimeRange.java index 6b6ba0b..0f8f851 100644 --- a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/TimeRange.java +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/policies/model/TimeRange.java @@ -27,20 +27,22 @@ package org.onap.optf.cmso.optimizer.availability.policies.model; } */ -public class TimeRange -{ +public class TimeRange { private String start_time; private String end_time; public String getStart_time() { return start_time; } + public void setStart_time(String start_time) { this.start_time = start_time; } + public String getEnd_time() { return end_time; } + public void setEnd_time(String end_time) { this.end_time = end_time; } diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/timewindows/RecurringWindows.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/timewindows/RecurringWindows.java index f9704ff..dce64b4 100644 --- a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/timewindows/RecurringWindows.java +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/availability/timewindows/RecurringWindows.java @@ -19,10 +19,25 @@ package org.onap.optf.cmso.optimizer.availability.timewindows; +import com.google.ical.compat.jodatime.DateTimeIterator; +import com.google.ical.compat.jodatime.DateTimeIteratorFactory; +import java.text.ParseException; import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.OffsetTime; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Date; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; import org.onap.observations.Observation; import org.onap.optf.cmso.optimizer.availability.policies.model.AllowedPeriodicTime; import org.onap.optf.cmso.optimizer.availability.policies.model.TimeLimitAndVerticalTopology; @@ -30,8 +45,18 @@ import org.onap.optf.cmso.optimizer.availability.policies.model.TimeRange; import org.onap.optf.cmso.optimizer.common.LogMessages; import org.onap.optf.cmso.optimizer.service.rs.models.ChangeWindow; +/** + * The Class RecurringWindows. + */ public class RecurringWindows { + /** + * Gets the availability windows for policies. + * + * @param policies the policies + * @param changeWindow the change window + * @return the availability windows for policies + */ public static List<ChangeWindow> getAvailabilityWindowsForPolicies(List<TimeLimitAndVerticalTopology> policies, ChangeWindow changeWindow) { List<ChangeWindow> availableList = new ArrayList<>(); @@ -42,19 +67,46 @@ public class RecurringWindows { } } } + // Collapse all duplicate and overlapping availabity windows into minimum + // number of windows + availableList = collapseWindows(availableList); return availableList; } + private static List<ChangeWindow> collapseWindows(List<ChangeWindow> availableList) { + List<ChangeWindow> collapsed = new ArrayList<>(); + Set<ChangeWindow> consumed = new HashSet<>(); + for (ChangeWindow win : availableList) { + if (!consumed.contains(win)) { + // Find all windows that can collapse into this one + consumed.add(win); + boolean allUnique = false; + while (!allUnique) { + allUnique = true; + for (ChangeWindow test : availableList) { + // if availability windows overlap + if (!consumed.contains(test)) { + if (win.absorbIfOverlapping(test)) { + consumed.add(test); + allUnique = false; + } + } + } + } + collapsed.add(win); + } + } + return collapsed; + } + // "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR", private static void getAvailableWindowsForApt(AllowedPeriodicTime available, ChangeWindow changeWindow, List<ChangeWindow> availableList) { - if (available.getDay() != null) - { - switch (available.getDay()) - { + if (available.getDay() != null) { + switch (available.getDay()) { case weekday: case weekend: getAvailableWindowsForAptDay(available, changeWindow, availableList); @@ -63,46 +115,102 @@ public class RecurringWindows { } } + availableList.add(changeWindow); Observation.report(LogMessages.UNSUPPORTED_PERIODIC_TIME, available.toString()); } + // "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR", + private static void getAvailableWindowsForAptDay(AllowedPeriodicTime available, ChangeWindow changeWindow, List<ChangeWindow> availableList) { - try - { + try { List<TimeRange> ranges = available.getTimeRange(); - if (ranges.size() == 0) - { + if (ranges.size() == 0) { TimeRange range = new TimeRange(); range.setStart_time("00:00:00+00:00"); range.setStart_time("23:59:59+00:00"); ranges.add(range); } - String rrule = available.getDay().getRrule(); - for (TimeRange range : ranges) - { - - Date cwStartDate =changeWindow.getStartTime(); - Date cwEndDate =changeWindow.getEndTime(); - - Instant cwStartInstant = Instant.ofEpochMilli(cwStartDate.getTime()); - Instant cwEndInstant = Instant.ofEpochMilli(cwEndDate.getTime()); - Instant startInstant = Instant.parse(range.getStart_time()); - Instant endInstant = Instant.parse(range.getEnd_time()); - if (cwStartInstant.isAfter(startInstant)) - { - // We expect this since startInstant has no date (1/1/1970) - // + StringBuilder rdata = new StringBuilder(); + rdata.append(available.getDay().getRrule()).append("\n"); + for (TimeRange range : ranges) { + processRange(range, changeWindow, availableList, rdata); + } + } catch (Exception e) { + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + } + + + private static void processRange(TimeRange range, ChangeWindow changeWindow, List<ChangeWindow> availableList, + StringBuilder rdata) throws ParseException { + + Instant cwStartInstant = changeWindow.getStartTime().toInstant(); + Instant cwEndInstant = changeWindow.getEndTime().toInstant(); + + List<DateTime> startList = getRecurringList(range.getStart_time(), cwStartInstant, rdata, cwEndInstant); + List<DateTime> endList = getRecurringList(range.getEnd_time(), cwStartInstant, rdata, cwEndInstant); + // Pair them up to make change windows + // Everything should be UTC time + for (int i = 0; i < startList.size(); i++) { + DateTime startDt = startList.get(i); + if (i < endList.size()) { + DateTime endDt = endList.get(i); + if (endDt.isAfter(startDt)) { + ChangeWindow cw = new ChangeWindow(); + cw.setStartTime(startDt.toDate()); + cw.setEndTime(endDt.toDate()); + availableList.add(cw); } + } + } + + } + + private static List<DateTime> getRecurringList(String rangeTime, Instant cwStartInstant, StringBuilder rdata, + Instant cwEndInstant) throws ParseException { + + Instant startInstant = getInstanceFromTime(rangeTime, cwStartInstant); + DateTime start = new DateTime(startInstant.toEpochMilli()); + DateTimeIterator recur = + DateTimeIteratorFactory.createDateTimeIterator(rdata.toString(), start, DateTimeZone.UTC, true); + List<DateTime> list = new ArrayList<>(); + while (recur.hasNext()) { + DateTime next = recur.next(); + // System.out.println(next.toString()); + if (next.isAfter(cwEndInstant.toEpochMilli())) { + break; } + list.add(next); } - catch (Exception e) - { - Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + return list; + } + + + // + // The policies with 'Day' enumeration only have time with no day so we add the + // date portion of the change window to the dtstart + // + private static Instant getInstanceFromTime(String timeIn, Instant cwStartInstant) { + Instant instant = null; + Instant date = cwStartInstant.truncatedTo(ChronoUnit.DAYS); + LocalDate epoch = LocalDate.ofEpochDay(0); + try { + OffsetTime offset = OffsetTime.parse(timeIn); + OffsetDateTime odt = offset.atDate(epoch); + ZonedDateTime startTime = odt.atZoneSameInstant(ZoneOffset.UTC.normalized()); + instant = Instant.from(startTime); + } catch (Exception e) { + LocalTime local = LocalTime.parse(timeIn); + LocalDateTime ldt = local.atDate(epoch); + ZonedDateTime startTime = ldt.atZone(ZoneOffset.UTC.normalized()); + instant = Instant.from(startTime); } + return instant.plus(date.toEpochMilli(), ChronoUnit.MILLIS); } + } diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/common/models/ElementCriteria.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/common/models/ElementCriteria.java new file mode 100644 index 0000000..7b16a2f --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/common/models/ElementCriteria.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * + * Copyright © 2019 AT&T Intellectual Property. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed under the Creative + * Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except + * in compliance with the License. You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation 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.optf.cmso.optimizer.clients.common.models; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import org.onap.optf.cmso.optimizer.service.rs.models.NameValue; + +@ApiModel(value = "Element Critera", description = "Element criteria for retrieving topology.") +public class ElementCriteria implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "Element id unique to the request.") + private String elementId; + + @ApiModelProperty(value = "Implementation specific element data.") + public List<NameValue> elementData = new ArrayList<>(); + + public String getElementId() { + return elementId; + } + + public void setElementId(String elementId) { + this.elementId = elementId; + } + + public List<NameValue> getElementData() { + return elementData; + } + + public void setElementData(List<NameValue> elementData) { + this.elementData = elementData; + } + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/TicketMgtClient.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/TicketMgtClient.java new file mode 100644 index 0000000..21f0d76 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/TicketMgtClient.java @@ -0,0 +1,231 @@ +/* + * ============LICENSE_START============================================== + * Copyright (c) 2019 AT&T Intellectual Property. + * ======================================================================= + * 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.optf.cmso.optimizer.clients.ticketmgt; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import org.onap.observations.Observation; +import org.onap.optf.cmso.common.BasicAuthenticatorFilter; +import org.onap.optf.cmso.common.PropertiesManagement; +import org.onap.optf.cmso.common.exceptions.CmsoException; +import org.onap.optf.cmso.optimizer.clients.common.models.ElementCriteria; +import org.onap.optf.cmso.optimizer.clients.ticketmgt.models.ActiveTicketsRequest; +import org.onap.optf.cmso.optimizer.clients.ticketmgt.models.ActiveTicketsResponse; +import org.onap.optf.cmso.optimizer.clients.ticketmgt.models.ActiveTicketsResponse.ActiveTicketResponseStatus; +import org.onap.optf.cmso.optimizer.clients.topology.TopologyRequestManager; +import org.onap.optf.cmso.optimizer.clients.topology.models.ConstraintElements; +import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyElementInfo; +import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyPolicyInfo; +import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyResponse; +import org.onap.optf.cmso.optimizer.common.LogMessages; +import org.onap.optf.cmso.optimizer.filters.CmsoClientFilters; +import org.onap.optf.cmso.optimizer.model.Request; +import org.onap.optf.cmso.optimizer.model.Ticket; +import org.onap.optf.cmso.optimizer.model.Topology; +import org.onap.optf.cmso.optimizer.model.dao.RequestDao; +import org.onap.optf.cmso.optimizer.model.dao.TicketDao; +import org.onap.optf.cmso.optimizer.service.rs.models.ElementInfo; +import org.onap.optf.cmso.optimizer.service.rs.models.OptimizerRequest; +import org.onap.optf.cmso.optimizer.service.rs.models.PolicyInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** + * The Class TicketMgtClient. + */ +@Component +public class TicketMgtClient { + private static EELFLogger debug = EELFManager.getInstance().getDebugLogger(); + + @Autowired + Environment env; + + @Autowired + PropertiesManagement pm; + + @Autowired + RequestDao requestDao; + + @Autowired + TicketDao ticketDao; + + @Autowired + TopologyRequestManager topologyRequestManager; + + /** + * Make request of ticket mgt system. + * + * @param requestRow the request row + * @param ticketRow the ticket row + * @return the active tickets response + */ + public ActiveTicketsResponse makeRequest(Request requestRow, Ticket ticketRow) { + ActiveTicketsResponse ticketResponse = new ActiveTicketsResponse(); + Integer maxAttempts = env.getProperty("cmso.optimizer.maxAttempts", Integer.class, 20); + if (ticketRow.getTicketsRetries() >= maxAttempts) { + ticketResponse.setStatus(ActiveTicketResponseStatus.FAILED); + ticketResponse.setErrorMessage(LogMessages.EXCEEDED_RETRY_LIMIT.format("Topology", maxAttempts.toString())); + Observation.report(LogMessages.EXCEEDED_RETRY_LIMIT, "TicketMgt", maxAttempts.toString()); + return ticketResponse; + } + ObjectMapper om = new ObjectMapper(); + String originalRequest = requestRow.getRequest(); + OptimizerRequest optimizerRequest = null;; + try { + optimizerRequest = om.readValue(originalRequest, OptimizerRequest.class); + ActiveTicketsRequest apiRequest = buildRequest(optimizerRequest); + ticketResponse = initiateApiRequest(apiRequest, ticketRow, requestRow); + } catch (Exception e) { + ticketResponse.setStatus(ActiveTicketResponseStatus.FAILED); + ticketResponse.setErrorMessage(LogMessages.UNEXPECTED_EXCEPTION.format(e.getMessage())); + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + return ticketResponse; + } + + private ActiveTicketsRequest buildRequest(OptimizerRequest optimizerRequest) + throws JsonParseException, JsonMappingException, IOException { + UUID uuid = UUID.fromString(optimizerRequest.getRequestId()); + Topology topologyRow = topologyRequestManager.getExistingTopology(uuid); + String topologyString = topologyRow.getTopology(); + TopologyResponse topologyResponse = new ObjectMapper().readValue(topologyString, TopologyResponse.class); + ActiveTicketsRequest apiRequest = new ActiveTicketsRequest(); + apiRequest.setRequestId(optimizerRequest.getRequestId()); + apiRequest.setCommonData(optimizerRequest.getCommonData()); + apiRequest.setChangeWindows(optimizerRequest.getChangeWindows()); + apiRequest.setElements(getElementCriteria(topologyResponse)); + return apiRequest; + } + + private List<TopologyPolicyInfo> getPolicies(OptimizerRequest optimizerRequest) { + List<TopologyPolicyInfo> list = new ArrayList<>(); + for (PolicyInfo optInfo : optimizerRequest.getPolicies()) { + TopologyPolicyInfo topInfo = new TopologyPolicyInfo(); + topInfo.setPolicyDescription(optInfo.getPolicyDescription()); + topInfo.setPolicyName(optInfo.getPolicyName()); + topInfo.setPolicyModifiers(optInfo.getPolicyModifiers()); + list.add(topInfo); + } + return list; + } + + private List<ElementCriteria> getElementCriteria(TopologyResponse topologyResponse) { + Map<String, ElementCriteria> map = new HashMap<>(); + for (TopologyElementInfo info : topologyResponse.getElements()) { + ElementCriteria criteria = new ElementCriteria(); + criteria.setElementId(info.getElementId()); + criteria.setElementData(info.getElementData()); + map.put(criteria.getElementId(), criteria); + if (info.getRequiredElements() != null) { + for (String required : info.getRequiredElements()) { + if (!map.containsKey(required)) { + ElementCriteria crit = new ElementCriteria(); + crit.setElementId(required); + map.put(crit.getElementId(), crit); + } + } + } + if (info.getConstraintElements() != null) { + for (ConstraintElements constraint : info.getConstraintElements()) { + if (!map.containsKey(constraint.getElementId())) { + ElementCriteria crit = new ElementCriteria(); + crit.setElementId(constraint.getElementId()); + map.put(crit.getElementId(), crit); + } + } + } + + } + List<ElementCriteria> list = new ArrayList<>(); + list.addAll(map.values()); + return list; + } + + + private ActiveTicketsResponse initiateApiRequest(ActiveTicketsRequest apiRequest, Ticket ticketRow, + Request requestRow) throws CmsoException, JsonProcessingException { + String url = env.getProperty("cmso.ticket.create.request.url"); + String username = env.getProperty("mechid.user"); + String password = pm.getProperty("mechid.pass", ""); + Client client = ClientBuilder.newClient(); + client.register(new BasicAuthenticatorFilter(username, password)); + client.register(new CmsoClientFilters()); + debug.debug("topology url / user: " + url + " / " + username); + debug.debug("topology Request: " + new ObjectMapper().writeValueAsString(apiRequest)); + Observation.report(LogMessages.TOPOLOGY_REQUEST, "Begin", apiRequest.getRequestId(), url); + ticketRow.setTicketsStart(System.currentTimeMillis()); + + WebTarget webTarget = client.target(url); + Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); + Response response = invocationBuilder.post(Entity.json(apiRequest)); + Observation.report(LogMessages.TOPOLOGY_REQUEST, "End", apiRequest.getRequestId(), url); + ActiveTicketsResponse apiResponse = null; + switch (response.getStatus()) { + case 202: + debug.debug("Successfully scheduled asynchronous ticket request: " + apiRequest.getRequestId()); + break; + case 200: + debug.debug("Successfully retrieved tickets: " + apiRequest.getRequestId()); + apiResponse = processApiResponse(apiRequest, response, ticketRow, requestRow); + break; + default: + throw new CmsoException(Status.INTERNAL_SERVER_ERROR, LogMessages.UNEXPECTED_RESPONSE, url, + response.getStatusInfo().toString()); + } + return apiResponse; + } + + private ActiveTicketsResponse processApiResponse(ActiveTicketsRequest apiRequest, Response response, + Ticket ticketRow, Request requestRow) { + String responseString = response.readEntity(String.class); + ActiveTicketsResponse apiResponse = null; + try { + apiResponse = new ObjectMapper().readValue(responseString, ActiveTicketsResponse.class); + ticketRow.setTickets(responseString); + } catch (Exception e) { + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + apiResponse = new ActiveTicketsResponse(); + apiResponse.setRequestId(apiRequest.getRequestId()); + apiResponse.setStatus(ActiveTicketResponseStatus.FAILED); + apiResponse.setErrorMessage(e.getMessage()); + } + return apiResponse; + } + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/TicketMgtRequestManager.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/TicketMgtRequestManager.java new file mode 100644 index 0000000..8c7dfb6 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/TicketMgtRequestManager.java @@ -0,0 +1,93 @@ +/* + * ============LICENSE_START============================================== + * Copyright (c) 2019 AT&T Intellectual Property. + * ======================================================================= + * 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.optf.cmso.optimizer.clients.ticketmgt; + +import java.util.Optional; +import org.onap.observations.Observation; +import org.onap.optf.cmso.optimizer.clients.ticketmgt.models.ActiveTicketsResponse; +import org.onap.optf.cmso.optimizer.common.LogMessages; +import org.onap.optf.cmso.optimizer.model.Request; +import org.onap.optf.cmso.optimizer.model.Ticket; +import org.onap.optf.cmso.optimizer.model.dao.RequestDao; +import org.onap.optf.cmso.optimizer.model.dao.TicketDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** + * Ticket Mgt request manager. + * + * @author jf9860 + * + */ +@Component +public class TicketMgtRequestManager { + + @Autowired + Environment env; + + @Autowired + RequestDao requestDao; + + @Autowired + TicketDao ticketDao; + + @Autowired + TicketMgtClient ticketmgtClient; + + /** + * Creates the topology request. + * + * @param requestRow the uuid + * @return the active tickets response + */ + public ActiveTicketsResponse createTicketsRequest(Request requestRow) { + try { + Ticket row = null; + Optional<Ticket> rowOpt = ticketDao.findById(requestRow.getUuid()); + if (rowOpt.isPresent()) { + row = rowOpt.get(); + + } + if (row == null) { + row = new Ticket(); + row.setUuid(requestRow.getUuid()); + row.setTicketsRetries(0); + } + ActiveTicketsResponse apiResponse = ticketmgtClient.makeRequest(requestRow, row); + switch (apiResponse.getStatus()) { + case COMPLETED: + break; + case FAILED: + break; + case IN_PROGRESS: + break; + default: + break; + } + return apiResponse; + } catch (Exception e) { + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + return null; + + } + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/ActiveTicketsRequest.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/ActiveTicketsRequest.java new file mode 100644 index 0000000..f03c6f3 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/ActiveTicketsRequest.java @@ -0,0 +1,114 @@ +/* + * Copyright © 2017-2019 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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.optf.cmso.optimizer.clients.ticketmgt.models; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.annotations.ApiModelProperty; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import org.onap.optf.cmso.optimizer.clients.common.models.ElementCriteria; +import org.onap.optf.cmso.optimizer.service.rs.models.ChangeWindow; +import org.onap.optf.cmso.optimizer.service.rs.models.NameValue; + +public class ActiveTicketsRequest implements Serializable { + private static final long serialVersionUID = 1L; + private static EELFLogger log = EELFManager.getInstance().getLogger(ActiveTicketsRequest.class); + + @ApiModelProperty(value = "Unique Id of the request") + private String requestId; + + @ApiModelProperty( + value = "Implementation specific name value pairs provided to be passed to Ticket Management query .") + private List<NameValue> commonData; + + @ApiModelProperty(value = "Lists of desired change windows for which TicketData will be returned.") + private List<ChangeWindow> changeWindows = new ArrayList<>(); + + @ApiModelProperty(value = "List of the elements for which TicketData will be returned.") + private List<ElementCriteria> elements = new ArrayList<>(); + + public String getRequestId() { + return requestId; + } + + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + + public List<NameValue> getCommonData() { + return commonData; + } + + + public void setCommonData(List<NameValue> commonData) { + this.commonData = commonData; + } + + + public List<ChangeWindow> getChangeWindows() { + return changeWindows; + } + + + public void setChangeWindows(List<ChangeWindow> changeWindows) { + this.changeWindows = changeWindows; + } + + + public List<ElementCriteria> getElements() { + return elements; + } + + + public void setElements(List<ElementCriteria> elements) { + this.elements = elements; + } + + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + log.debug("Error in toString()", e); + } + return ""; + } + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/ActiveTicketsResponse.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/ActiveTicketsResponse.java new file mode 100644 index 0000000..9780af6 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/ActiveTicketsResponse.java @@ -0,0 +1,110 @@ +/* + * Copyright © 2017-2019 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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.optf.cmso.optimizer.clients.ticketmgt.models; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class ActiveTicketsResponse implements Serializable { + private static final long serialVersionUID = 1L; + private static EELFLogger log = EELFManager.getInstance().getLogger(ActiveTicketsResponse.class); + + public enum ActiveTicketResponseStatus { + IN_PROGRESS, COMPLETED, FAILED, + } + + private String requestId; + + private List<TicketData> elements = new ArrayList<>(); + + private ActiveTicketResponseStatus status; + + private Integer pollingSeconds; + private String errorMessage; + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public List<TicketData> getElements() { + return elements; + } + + public void setElements(List<TicketData> elements) { + this.elements = elements; + } + + public ActiveTicketResponseStatus getStatus() { + return status; + } + + public void setStatus(ActiveTicketResponseStatus status) { + this.status = status; + } + + public Integer getPollingSeconds() { + return pollingSeconds; + } + + public void setPollingSeconds(Integer pollingSeconds) { + this.pollingSeconds = pollingSeconds; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + log.debug("Error in toString()", e); + } + return ""; + } + +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/Availability.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/Availability.java new file mode 100644 index 0000000..37995bb --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/Availability.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * + * Copyright © 2019 AT&T Intellectual Property. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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.optf.cmso.optimizer.clients.ticketmgt.models; + +public enum Availability { + full, partial, unavailable +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/TicketData.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/TicketData.java new file mode 100644 index 0000000..07b9f94 --- /dev/null +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/ticketmgt/models/TicketData.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * + * Copyright © 2019 AT&T Intellectual Property. + * + * 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. + * + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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.optf.cmso.optimizer.clients.ticketmgt.models; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.springframework.format.annotation.DateTimeFormat; + +@ApiModel(value = "Ticket Data", description = "Change Management Ticket Information.") +public class TicketData implements Serializable { + private static final long serialVersionUID = 1L; + private static EELFLogger log = EELFManager.getInstance().getLogger(TicketData.class); + + @ApiModelProperty(value = "Unique ticket identifier") + private String id; + + @ApiModelProperty(value = "Scheduled start time of change.") + @DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm:ss'Z'") + private Date startTime; + + @ApiModelProperty(value = "Scheduled end time of change.") + @DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm:ss'Z'") + private Date endTime; + + @ApiModelProperty(value = "Availability of element(s) during change window") + private Availability availability; + + @ApiModelProperty( + value = "List elementIds of elements being changed. At least one maps to elementId in the request") + private List<String> elementIds = new ArrayList<>(); + + @ApiModelProperty(value = "Details of the change.") + private String changeDetails; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + public Availability getAvailability() { + return availability; + } + + public void setAvailability(Availability availability) { + this.availability = availability; + } + + public List<String> getElementIds() { + return elementIds; + } + + public void setElementIds(List<String> elementIds) { + this.elementIds = elementIds; + } + + public String getChangeDetails() { + return changeDetails; + } + + public void setChangeDetails(String changeDetails) { + this.changeDetails = changeDetails; + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + log.debug("Error in toString()", e); + } + return ""; + } +} diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyClient.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyClient.java index 7674f43..c333651 100644 --- a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyClient.java +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyClient.java @@ -21,11 +21,9 @@ package org.onap.optf.cmso.optimizer.clients.topology; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.JsonParseException; +import com.att.eelf.i18n.EELFResourceManager; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.ws.rs.client.Client; @@ -40,7 +38,7 @@ import org.onap.observations.Observation; import org.onap.optf.cmso.common.BasicAuthenticatorFilter; import org.onap.optf.cmso.common.PropertiesManagement; import org.onap.optf.cmso.common.exceptions.CmsoException; -import org.onap.optf.cmso.optimizer.clients.topology.models.ElementCriteria; +import org.onap.optf.cmso.optimizer.clients.common.models.ElementCriteria; import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyPolicyInfo; import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyRequest; import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyResponse; @@ -53,12 +51,14 @@ import org.onap.optf.cmso.optimizer.model.dao.RequestDao; import org.onap.optf.cmso.optimizer.model.dao.TopologyDao; import org.onap.optf.cmso.optimizer.service.rs.models.ElementInfo; import org.onap.optf.cmso.optimizer.service.rs.models.OptimizerRequest; -import org.onap.optf.cmso.optimizer.service.rs.models.OptimizerResponse.OptimizeScheduleStatus; import org.onap.optf.cmso.optimizer.service.rs.models.PolicyInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +/** + * The Class TopologyClient. + */ @Component public class TopologyClient { private static EELFLogger debug = EELFManager.getInstance().getDebugLogger(); @@ -75,37 +75,47 @@ public class TopologyClient { @Autowired TopologyDao topologyDao; + /** + * Make request. + * + * @param request the request + * @param topology the topology + * @return the topology response + */ public TopologyResponse makeRequest(Request request, Topology topology) { - Integer maxAttempts = env.getProperty("cmso.optimizer.maxAttempts", Integer.class, 20); - if (topology.getTopologyRetries() >= maxAttempts) { - request.setStatus(OptimizeScheduleStatus.FAILED.toString()); - request.setRequestEnd(System.currentTimeMillis()); - requestDao.save(request); - return null; - } - TopologyRequest topologyRequest = new TopologyRequest(); - ObjectMapper om = new ObjectMapper(); - String originalRequest = request.getRequest(); - TopologyResponse topologyResponse = new TopologyResponse(); - OptimizerRequest optimizerRequest = null;; - try { - optimizerRequest = om.readValue(originalRequest, OptimizerRequest.class); - } catch (Exception e) { - topologyResponse.setStatus(TopologyRequestStatus.FAILED); - Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); - } - topologyRequest = new TopologyRequest(); - topologyRequest.setRequestId(optimizerRequest.getRequestId()); - topologyRequest.setCommonData(optimizerRequest.getCommonData()); - topologyRequest.setElements(getElementCriteria(optimizerRequest)); - topologyRequest.setPolicies(getPolicies(optimizerRequest)); - try { - topologyResponse = initiateTopology(topologyRequest, topology, request); - } catch (Exception e) { - topologyResponse.setStatus(TopologyRequestStatus.FAILED); - Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); - } + Integer maxAttempts = env.getProperty("cmso.optimizer.maxAttempts", Integer.class, 20); + TopologyResponse topologyResponse = new TopologyResponse(); + if (topology.getTopologyRetries() >= maxAttempts) { + topologyResponse.setStatus(TopologyRequestStatus.FAILED); + topologyResponse.setErrorMessage(LogMessages.EXCEEDED_RETRY_LIMIT.format( + "Topology", maxAttempts.toString())); + Observation.report(LogMessages.EXCEEDED_RETRY_LIMIT, "Topology", maxAttempts.toString()); return topologyResponse; + } + TopologyRequest topologyRequest = new TopologyRequest(); + ObjectMapper om = new ObjectMapper(); + String originalRequest = request.getRequest(); + OptimizerRequest optimizerRequest = null;; + try { + optimizerRequest = om.readValue(originalRequest, OptimizerRequest.class); + } catch (Exception e) { + topologyResponse.setStatus(TopologyRequestStatus.FAILED); + topologyResponse.setErrorMessage(LogMessages.UNEXPECTED_EXCEPTION.format(e.getMessage())); + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + topologyRequest = new TopologyRequest(); + topologyRequest.setRequestId(optimizerRequest.getRequestId()); + topologyRequest.setCommonData(optimizerRequest.getCommonData()); + topologyRequest.setElements(getElementCriteria(optimizerRequest)); + topologyRequest.setPolicies(getPolicies(optimizerRequest)); + try { + topologyResponse = initiateTopology(topologyRequest, topology, request); + } catch (Exception e) { + topologyResponse.setStatus(TopologyRequestStatus.FAILED); + topologyResponse.setErrorMessage(LogMessages.UNEXPECTED_EXCEPTION.format(e.getMessage())); + Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); + } + return topologyResponse; } private List<TopologyPolicyInfo> getPolicies(OptimizerRequest optimizerRequest) { @@ -131,19 +141,20 @@ public class TopologyClient { return list; } - private TopologyResponse initiateTopology(TopologyRequest request, Topology topology, Request requestRow) throws CmsoException, JsonProcessingException { + private TopologyResponse initiateTopology(TopologyRequest request, Topology topology, Request requestRow) + throws CmsoException, JsonProcessingException { String url = env.getProperty("cmso.topology.create.request.url"); String username = env.getProperty("mechid.user"); String password = pm.getProperty("mechid.pass", ""); Client client = ClientBuilder.newClient(); client.register(new BasicAuthenticatorFilter(username, password)); client.register(new CmsoClientFilters()); - WebTarget webTarget = client.target(url); - Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); debug.debug("topology url / user: " + url + " / " + username); debug.debug("topology Request: " + new ObjectMapper().writeValueAsString(request)); Observation.report(LogMessages.TOPOLOGY_REQUEST, "Begin", request.getRequestId(), url); topology.setTopologyStart(System.currentTimeMillis()); + WebTarget webTarget = client.target(url); + Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.post(Entity.json(request)); Observation.report(LogMessages.TOPOLOGY_REQUEST, "End", request.getRequestId(), url); TopologyResponse topologyResponse = null; @@ -153,11 +164,11 @@ public class TopologyClient { break; case 200: debug.debug("Successfully retrieved topology: " + request.getRequestId()); - topologyResponse = processTopologyResponse(request, response, topology, requestRow); + topologyResponse = processTopologyResponse(request, response, topology, requestRow); break; default: - throw new CmsoException(Status.INTERNAL_SERVER_ERROR, LogMessages.UNEXPECTED_RESPONSE, - url, response.getStatusInfo().toString()); + throw new CmsoException(Status.INTERNAL_SERVER_ERROR, LogMessages.UNEXPECTED_RESPONSE, url, + response.getStatusInfo().toString()); } return topologyResponse; } @@ -168,9 +179,8 @@ public class TopologyClient { TopologyResponse topologyResponse = null; try { topologyResponse = new ObjectMapper().readValue(responseString, TopologyResponse.class); - } - catch (Exception e) - { + topology.setTopology(responseString); + } catch (Exception e) { Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); topologyResponse = new TopologyResponse(); topologyResponse.setRequestId(request.getRequestId()); diff --git a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyRequestManager.java b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyRequestManager.java index 3120e0d..ce0d583 100644 --- a/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyRequestManager.java +++ b/cmso-optimizer/src/main/java/org/onap/optf/cmso/optimizer/clients/topology/TopologyRequestManager.java @@ -21,11 +21,7 @@ package org.onap.optf.cmso.optimizer.clients.topology; import java.util.Optional; import java.util.UUID; -import javax.ws.rs.core.Response.Status; -import org.onap.observations.Observation; -import org.onap.optf.cmso.common.exceptions.CmsoException; import org.onap.optf.cmso.optimizer.clients.topology.models.TopologyResponse; -import org.onap.optf.cmso.optimizer.common.LogMessages; import org.onap.optf.cmso.optimizer.model.Request; import org.onap.optf.cmso.optimizer.model.Topology; import org.onap.optf.cmso.optimizer.model.dao.RequestDao; @@ -34,6 +30,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +/** + * The Class TopologyRequestManager. + */ @Component public class TopologyRequestManager { @@ -49,52 +48,37 @@ public class TopologyRequestManager { @Autowired TopologyClient topologyClient; - public TopologyResponse createTopologyRequest(UUID uuid) - { - try - { - Request request = null; - Optional<Request> requestOptional = requestDao.findById(uuid); - if (requestOptional.isPresent()) - { - request = requestOptional.get(); - } - if (request == null) - { - throw new CmsoException(Status.INTERNAL_SERVER_ERROR, LogMessages.EXPECTED_DATA_NOT_FOUND, - uuid.toString(), "Request table"); - } - Topology topology = null; - Optional<Topology> topologyOpt = topologyDao.findById(uuid); - if (topologyOpt.isPresent()) - { - topology = topologyOpt.get(); - - } - if (topology == null) - { - topology = new Topology(); - topology.setUuid(uuid); - topology.setTopologyRetries(0); - } - TopologyResponse topologyResponse = topologyClient.makeRequest(request, topology); - switch(topologyResponse.getStatus()) - { - case COMPLETED: - break; - case FAILED: - break; - case IN_PROGRESS: - break; - } - return topologyResponse; + /** + * Creates the topology request. + * + * @param requestRow the request row + * @return the topology response + */ + public TopologyResponse createTopologyRequest(Request requestRow) { + Topology topology = getExistingTopology(requestRow.getUuid()); + if (topology == null) { + topology = new Topology(); + topology.setUuid(requestRow.getUuid()); + topology.setTopologyRetries(0); } - catch (Exception e) - { - Observation.report(LogMessages.UNEXPECTED_EXCEPTION, e, e.getMessage()); - } - return null; + TopologyResponse topologyResponse = topologyClient.makeRequest(requestRow, topology); + topologyDao.save(topology); + return topologyResponse; } + + /** + * Gets the existing topology. + * + * @param uuid the uuid + * @return the existing topology + */ + public Topology getExistingTopology(UUID uuid) { + Optional<Topology> topologyOpt = topologyDao.findById(uuid); + if (topologyOpt.isPresent()) { + return topologyOpt.get(); + } + return null; + } } |