2 * Copyright 2016-2017, Nokia Corporation
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm;
18 import com.google.common.collect.Ordering;
19 import com.google.common.collect.Sets;
20 import com.google.gson.Gson;
21 import com.google.gson.JsonElement;
22 import com.nokia.cbam.lcm.v32.ApiException;
23 import com.nokia.cbam.lcm.v32.api.OperationExecutionsApi;
24 import com.nokia.cbam.lcm.v32.api.VnfsApi;
25 import com.nokia.cbam.lcm.v32.model.OperationExecution;
26 import com.nokia.cbam.lcm.v32.model.VnfInfo;
27 import org.apache.http.HttpStatus;
28 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.onap.core.SelfRegistrationManager;
29 import org.onap.vnfmdriver.model.JobDetailInfo;
30 import org.onap.vnfmdriver.model.JobDetailInfoResponseDescriptor;
31 import org.onap.vnfmdriver.model.JobResponseInfo;
32 import org.onap.vnfmdriver.model.JobStatus;
33 import org.slf4j.Logger;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.stereotype.Component;
37 import javax.servlet.http.HttpServletResponse;
40 import static com.google.common.base.Splitter.on;
41 import static com.google.common.collect.Iterables.find;
42 import static com.google.common.collect.Iterables.tryFind;
43 import static com.google.common.collect.Lists.newArrayList;
44 import static java.util.Optional.empty;
45 import static java.util.Optional.of;
46 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.SEPARATOR;
47 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.buildFatalFailure;
48 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions.systemFunctions;
49 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
50 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification.LifecycleChangeNotificationManager.NEWEST_OPERATIONS_FIRST;
51 import static org.slf4j.LoggerFactory.getLogger;
52 import static org.springframework.util.StringUtils.isEmpty;
55 * Responsible for providing the status of jobs
56 * The job id is a composite field of the VNF identifier and an UUID.
57 * The second UUID is passed as mandatory parameter to each executed operation.
58 * This UUID is used to locate the operation execution from the ONAP job identifier
61 public class JobManager {
62 public static final String OPERATION_STARTED_DESCRIPTION = "Operation started";
63 private static final Ordering<JobResponseInfo> OLDEST_FIRST = new Ordering<JobResponseInfo>() {
65 public int compare(JobResponseInfo left, JobResponseInfo right) {
66 return Long.valueOf(left.getResponseId()).compareTo(Long.valueOf(right.getResponseId()));
69 private static Logger logger = getLogger(JobManager.class);
70 private final Set<String> ongoingJobs = Sets.newConcurrentHashSet();
71 private final CbamRestApiProvider cbamRestApiProvider;
72 private final SelfRegistrationManager selfRegistrationManager;
73 private volatile boolean preparingForShutDown = false;
76 JobManager(CbamRestApiProvider cbamRestApiProvider, SelfRegistrationManager selfRegistrationManager) {
77 this.cbamRestApiProvider = cbamRestApiProvider;
78 this.selfRegistrationManager = selfRegistrationManager;
82 * @param operationParams the operation execution
83 * @return the ONAP job identifier of belonging to the operation execution
85 public static String extractOnapJobId(Object operationParams) {
86 JsonElement operationParamsAsJson = new Gson().toJsonTree(operationParams);
87 JsonElement additionalParams = operationParamsAsJson.getAsJsonObject().get("additionalParams");
88 if (additionalParams == null) {
89 throw new NoSuchElementException("The operation result " + operationParamsAsJson + " does not contain the mandatory additionalParams structure");
91 JsonElement jobId = additionalParams.getAsJsonObject().get("jobId");
93 throw new NoSuchElementException("The operation result " + operationParamsAsJson + " does not contain the mandatory jobId in the additionalParams structure");
95 return jobId.getAsString();
99 * Throws an exception in case the service is not ready to serve requests due to
100 * not being able to register to MSB or to subscribe to CBAM LCNs
102 * @param vnfId the identifier of the VNF
103 * @param response the HTTP response of the current sVNFM incomming request
104 * @return the identifier of the job
106 public String spawnJob(String vnfId, HttpServletResponse response) {
107 String jobId = vnfId + SEPARATOR + UUID.randomUUID().toString();
108 synchronized (this) {
109 if (preparingForShutDown) {
110 response.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE);
111 throw buildFatalFailure(logger, "The service is preparing to shut down");
113 if (!selfRegistrationManager.isReady()) {
114 response.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE);
115 throw buildFatalFailure(logger, "The service is not yet ready");
118 ongoingJobs.add(jobId);
123 * Signal that a job has finished
125 * @param jobId the identifier of the job
127 public void jobFinished(String jobId) {
128 ongoingJobs.remove(jobId);
132 * @return the system has any ongoing jobs
134 public boolean hasOngoingJobs() {
135 return !ongoingJobs.isEmpty();
140 * Wait for all jobs to be cleared from the system the refuses to let additional request in
142 public void prepareForShutdown() {
143 preparingForShutDown = true;
145 synchronized (this) {
146 if (!hasOngoingJobs()) {
150 systemFunctions().sleep(500L);
155 * @param vnfmId the identifier of the VNFM
156 * @param jobId the identifier of the job
157 * @return detailed information of the job
159 public JobDetailInfo getJob(String vnfmId, String jobId) {
160 logger.debug("Retrieving the details for job with {} identifier", jobId);
161 ArrayList<String> jobParts = newArrayList(on(SEPARATOR).split(jobId));
162 if (jobParts.size() != 2) {
163 throw new IllegalArgumentException("The jobId should be in the <vnfId>" + SEPARATOR + "<UUID> format, but was " + jobId);
165 String vnfId = jobParts.get(0);
166 if (isEmpty(vnfId)) {
167 throw new IllegalArgumentException("The vnfId in the jobId (" + jobId + ") can not be empty");
169 String operationExecutionId = jobParts.get(1);
170 if (isEmpty(operationExecutionId)) {
171 throw new IllegalArgumentException("The UUID in the jobId (" + jobId + ") can not be empty");
173 Optional<VnfInfo> vnf = getVnf(vnfmId, vnfId);
174 if (!vnf.isPresent()) {
175 return getJobDetailInfoForMissingVnf(jobId);
177 return getJobInfoForExistingVnf(vnfmId, jobId, vnfId, vnf.get());
181 private JobDetailInfo getJobDetailInfoForMissingVnf(String jobId) {
182 if (ongoingJobs.contains(jobId)) {
183 return reportOngoing(jobId);
185 return reportFinished(jobId);
189 private JobDetailInfo getJobInfoForExistingVnf(String vnfmId, String jobId, String vnfId, VnfInfo vnf) {
191 OperationExecution operation = findOperationByJobId(vnfmId, vnf, jobId);
192 return getJobDetailInfo(vnfmId, jobId, vnfId, operation);
193 } catch (NoSuchElementException e) {
194 logger.warn("No operation could be identified for job with {} identifier", jobId, e);
195 if (ongoingJobs.contains(jobId)) {
196 return reportOngoing(jobId);
198 return reportFailed(jobId, "The requested operation was not able to start on CBAM");
203 private JobDetailInfo getJobDetailInfo(String vnfmId, String jobId, String vnfId, OperationExecution operation) {
204 switch (operation.getStatus()) {
206 return reportOngoing(jobId);
209 return getJobForTerminalOperationState(vnfmId, jobId, vnfId, operation);
211 default: //all cases handled
212 return reportFailed(jobId, operation.getError().getTitle() + ": " + operation.getError().getDetail());
216 private JobDetailInfo getJobForTerminalOperationState(String vnfmId, String jobId, String vnfId, OperationExecution operation) {
217 //termination includes VNF deletion in ONAP terminology
218 if (operation.getOperationType() == com.nokia.cbam.lcm.v32.model.OperationType.TERMINATE) {
219 if (ongoingJobs.contains(jobId)) {
220 return reportOngoing(jobId);
222 //the VNF must be queried again since it could have been deleted since the VNF has been terminated
223 if (getVnf(vnfmId, vnfId).isPresent()) {
224 return reportFailed(jobId, "unable to delete VNF");
226 return reportFinished(jobId);
230 return reportFinished(jobId);
234 private JobDetailInfo buildJob(String jobId, JobResponseInfo... history) {
235 JobDetailInfo job = new JobDetailInfo();
237 JobDetailInfoResponseDescriptor jobDetailInfoResponseDescriptor = new JobDetailInfoResponseDescriptor();
238 job.setResponseDescriptor(jobDetailInfoResponseDescriptor);
239 List<JobResponseInfo> oldestFirst = OLDEST_FIRST.sortedCopy(newArrayList(history));
240 JobResponseInfo newestJob = oldestFirst.get(oldestFirst.size() - 1);
241 jobDetailInfoResponseDescriptor.setResponseId(newestJob.getResponseId());
242 jobDetailInfoResponseDescriptor.setStatus(JobStatus.valueOf(newestJob.getStatus()));
243 jobDetailInfoResponseDescriptor.setProgress(newestJob.getProgress());
244 jobDetailInfoResponseDescriptor.setStatusDescription(newestJob.getStatusDescription());
245 jobDetailInfoResponseDescriptor.setErrorCode(newestJob.getErrorCode());
246 jobDetailInfoResponseDescriptor.setResponseHistoryList(oldestFirst);
250 private JobResponseInfo buildJobPart(String description, JobStatus status, Integer progress, Integer responseId) {
251 JobResponseInfo currentJob = new JobResponseInfo();
252 currentJob.setProgress(progress.toString());
253 currentJob.setResponseId(responseId.toString());
254 currentJob.setStatus(status.name());
255 currentJob.setStatusDescription(description);
259 private JobDetailInfo reportOngoing(String jobId) {
260 return buildJob(jobId, buildJobPart(OPERATION_STARTED_DESCRIPTION, JobStatus.STARTED, 50, 1));
263 private JobDetailInfo reportFailed(String jobId, String reason) {
264 return buildJob(jobId,
265 buildJobPart(OPERATION_STARTED_DESCRIPTION, JobStatus.STARTED, 50, 1),
266 buildJobPart("Operation failed due to " + reason, JobStatus.ERROR, 100, 2)
270 private JobDetailInfo reportFinished(String jobId) {
271 return buildJob(jobId,
272 buildJobPart(OPERATION_STARTED_DESCRIPTION, JobStatus.STARTED, 50, 1),
273 buildJobPart("Operation finished", JobStatus.FINISHED, 100, 2)
277 private OperationExecution findOperationByJobId(String vnfmId, VnfInfo vnf, String jobId) {
278 OperationExecutionsApi cbamOperationExecutionApi = cbamRestApiProvider.getCbamOperationExecutionApi(vnfmId);
279 //the operations are sorted so that the newest operations are queried first
280 //performance optimization that usually the core system is interested in the operations executed last
281 if (vnf.getOperationExecutions() != null) {
282 List<OperationExecution> sortedOperation = NEWEST_OPERATIONS_FIRST.sortedCopy(vnf.getOperationExecutions());
283 return find(sortedOperation, operation -> isCurrentOperationTriggeredByJob(jobId, cbamOperationExecutionApi, operation));
285 throw new NoSuchElementException();
288 private boolean isCurrentOperationTriggeredByJob(String jobId, OperationExecutionsApi cbamOperationExecutionApi, OperationExecution operationExecution) {
290 Object operationParams = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(operationExecution.getId(), NOKIA_LCM_API_VERSION);
291 if (extractOnapJobId(operationParams).equals(jobId)) {
294 } catch (ApiException e) {
295 throw buildFatalFailure(logger, "Unable to retrieve operation parameters", e);
300 private Optional<VnfInfo> getVnf(String vnfmId, String vnfId) {
302 //test if the VNF exists (required to be able to distingush between failed request )
303 VnfsApi cbamLcmApi = cbamRestApiProvider.getCbamLcmApi(vnfmId);
304 logger.debug("Listing VNFs");
305 List<VnfInfo> vnfs = cbamLcmApi.vnfsGet(NOKIA_LCM_API_VERSION);
306 com.google.common.base.Optional<VnfInfo> vnf = tryFind(vnfs, vnfInfo -> vnfId.equals(vnfInfo.getId()));
307 if (!vnf.isPresent()) {
308 logger.debug("VNF with {} identifier is missing", vnfId);
311 logger.debug("VNF with {} identifier still exists", vnfId);
312 //query the VNF again to get operation execution result
313 return of(cbamLcmApi.vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION));
315 } catch (ApiException e) {
316 throw buildFatalFailure(logger, "Unable to retrieve VNF", e);