2 * Copyright 2017 Huawei Technologies Co., Ltd.
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.
17 package org.onap.vnfsdk.marketplace.wrapper;
19 import java.io.BufferedInputStream;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.concurrent.Callable;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
30 import javax.ws.rs.core.HttpHeaders;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.Response;
33 import javax.ws.rs.core.Response.Status;
35 import org.apache.commons.io.IOUtils;
36 import org.apache.commons.lang3.StringUtils;
37 import org.eclipse.jetty.http.HttpStatus;
38 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
39 import org.onap.vnfsdk.marketplace.common.CommonConstant;
40 import org.onap.vnfsdk.marketplace.common.CommonErrorResponse;
41 import org.onap.vnfsdk.marketplace.common.FileUtil;
42 import org.onap.vnfsdk.marketplace.common.RestUtil;
43 import org.onap.vnfsdk.marketplace.common.ToolUtil;
44 import org.onap.vnfsdk.marketplace.db.entity.PackageData;
45 import org.onap.vnfsdk.marketplace.db.exception.ErrorCodeException;
46 import org.onap.vnfsdk.marketplace.db.exception.MarketplaceResourceException;
47 import org.onap.vnfsdk.marketplace.db.resource.PackageManager;
48 import org.onap.vnfsdk.marketplace.db.util.MarketplaceDbUtil;
49 import org.onap.vnfsdk.marketplace.entity.request.PackageBasicInfo;
50 import org.onap.vnfsdk.marketplace.entity.response.PackageMeta;
51 import org.onap.vnfsdk.marketplace.entity.response.UploadPackageResponse;
52 import org.onap.vnfsdk.marketplace.filemanage.FileManagerFactory;
53 import org.onap.vnfsdk.marketplace.onboarding.entity.OnBoardingOperResult;
54 import org.onap.vnfsdk.marketplace.onboarding.entity.OnBoardingResult;
55 import org.onap.vnfsdk.marketplace.onboarding.entity.OnBoardingSteps;
56 import org.onap.vnfsdk.marketplace.onboarding.entity.OnBoradingRequest;
57 import org.onap.vnfsdk.marketplace.onboarding.hooks.functiontest.FunctionTestExceutor;
58 import org.onap.vnfsdk.marketplace.onboarding.hooks.functiontest.FunctionTestHook;
59 import org.onap.vnfsdk.marketplace.onboarding.hooks.validatelifecycle.ValidateLifecycleTestResponse;
60 import org.onap.vnfsdk.marketplace.onboarding.onboardmanager.OnBoardingHandler;
61 import org.open.infc.grpc.Result;
62 import org.open.infc.grpc.client.OpenRemoteCli;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 public class PackageWrapper {
68 private static PackageWrapper packageWrapper;
70 private static final Logger LOG = LoggerFactory.getLogger(PackageWrapper.class);
73 * get PackageWrapper instance.
75 * @return package wrapper instance
77 public static PackageWrapper getInstance() {
78 if(packageWrapper == null) {
79 packageWrapper = new PackageWrapper();
81 return packageWrapper;
84 public Response updateValidateStatus(InputStream inputStream) throws IOException {
85 String reqParam = IOUtils.toString(inputStream);
86 LOG.info("updateValidateStatus request param:" + reqParam);
87 if(StringUtils.isBlank(reqParam)) {
88 LOG.error("The updateValidateStatus request params can't be null");
89 return Response.status(Status.EXPECTATION_FAILED).build();
92 ValidateLifecycleTestResponse lyfValidateResp = null; // TBD - Use Gson - jackson has
94 // JsonUtil.fromJson(reqParam, ValidateLifecycleTestResponse.class);
95 if(!checkOperationSucess(lyfValidateResp)) {
96 return Response.status(Status.EXPECTATION_FAILED).build();
99 String funcTestResponse = FunctionTestExceutor.executeFunctionTest(reqParam);
100 if(null == funcTestResponse) {
101 return Response.status(Status.EXPECTATION_FAILED).build();
104 if(!funcTestResponse.contains(CommonConstant.SUCCESS_STR)) {
105 return Response.status(Status.EXPECTATION_FAILED).build();
108 return Response.ok().build();
111 private boolean checkOperationSucess(ValidateLifecycleTestResponse lyfValidateResp) {
112 boolean bOperStatus = false;
113 if(null == lyfValidateResp) {
114 LOG.error("ValidateLifecycleTestResponse is NUll !!!");
117 if(lyfValidateResp.getLifecycle_status().equalsIgnoreCase(CommonConstant.SUCCESS_STR)
118 && lyfValidateResp.getValidate_status().equalsIgnoreCase(CommonConstant.SUCCESS_STR)) {
119 LOG.error("Lifecycle/Validation Response failed :" + lyfValidateResp.getLifecycle_status() + File.separator
120 + lyfValidateResp.getValidate_status());
127 * query package list by condition.
129 * @param name package name
130 * @param provider package provider
131 * @param version package version
132 * @param deletionPending package deletionPending
133 * @param type package type
136 public Response queryPackageListByCond(String name, String provider, String version, String deletionPending,
138 List<PackageData> dbresult = new ArrayList<>();
139 List<PackageMeta> result = new ArrayList<>();
140 LOG.info("query package info.name:" + name + " provider:" + provider + " version" + version + " deletionPending"
141 + deletionPending + " type:" + type);
143 dbresult = PackageManager.getInstance().queryPackage(name, provider, version, deletionPending, type);
144 result = PackageWrapperUtil.packageDataList2PackageMetaList(dbresult);
145 return Response.ok(ToolUtil.objectToString(result)).build();
146 } catch(MarketplaceResourceException e1) {
147 LOG.error("query package by csarId from db error ! ", e1);
148 return RestUtil.getRestException(e1.getMessage());
153 * query package by id.
155 * @param csarId package id
158 public Response queryPackageById(String csarId) {
159 PackageData dbResult = PackageWrapperUtil.getPackageInfoById(csarId);
160 PackageMeta result = PackageWrapperUtil.packageData2PackageMeta(dbResult);
161 return Response.ok(ToolUtil.objectToString(result)).build();
167 * @param uploadedInputStream inputStream
168 * @param fileDetail package detail
169 * @param head http header
171 * @throws Exception e
173 public Response uploadPackage(InputStream uploadedInputStream, FormDataContentDisposition fileDetail,
174 String details, HttpHeaders head) {
175 LOG.info("Upload/Reupload request Received !!!!");
177 String packageId = MarketplaceDbUtil.generateId();
178 return handlePackageUpload(packageId, uploadedInputStream, fileDetail, details, head);
179 } catch(IOException e) {
180 LOG.error("can't get package id", e);
182 return Response.status(Status.INTERNAL_SERVER_ERROR).build();
185 private UploadPackageResponse manageUpload(String packageId, String fileName, String fileLocation, String details,
186 String contentRange) throws IOException, ErrorCodeException {
187 String localDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName);
188 PackageBasicInfo basicInfo = PackageWrapperUtil.getPacageBasicInfo(fileLocation);
189 UploadPackageResponse result = new UploadPackageResponse();
190 Boolean isEnd = PackageWrapperUtil.isUploadEnd(contentRange);
192 PackageMeta packageMeta =
193 PackageWrapperUtil.getPackageMeta(packageId, fileName, fileLocation, basicInfo, details);
195 String path = basicInfo.getType().toString() + File.separator + basicInfo.getProvider() + File.separator
196 + packageMeta.getCsarId() + File.separator + fileName.replace(".csar", "") + File.separator
197 + basicInfo.getVersion();
199 String dowloadUri = File.separator + path + File.separator;
200 packageMeta.setDownloadUri(dowloadUri);
202 LOG.info("dest path is : " + path);
203 LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta));
205 PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta);
207 List<PackageData> lstPkgData =
208 PackageManager.getInstance().queryPackage(packageMeta.getName(), "", "", "", "");
209 if(!lstPkgData.isEmpty()) {
210 LOG.error("Package name is not unique");
211 throw new ErrorCodeException(HttpStatus.INTERNAL_SERVER_ERROR_500, "Package name already exists");
214 String destPath = File.separator + path + File.separator + File.separator;
215 boolean uploadResult = FileManagerFactory.createFileManager().upload(localDirName, destPath);
217 OnBoradingRequest oOnboradingRequest = new OnBoradingRequest();
218 oOnboradingRequest.setCsarId(packageId);
219 oOnboradingRequest.setPackageName(fileName);
220 oOnboradingRequest.setPackagePath(localDirName);
222 packageData.setCsarId(packageId);
223 packageData.setDownloadCount(-1);
224 PackageData packateDbData = PackageManager.getInstance().addPackage(packageData);
226 LOG.info("Store package data to database succed ! packateDbData = "
227 + ToolUtil.objectToString(packateDbData));
228 LOG.info("upload package file end, fileName:" + fileName);
230 result.setCsarId(packateDbData.getCsarId());
232 addOnBoardingRequest(oOnboradingRequest);
234 LOG.info("OnboradingRequest Data : " + ToolUtil.objectToString(oOnboradingRequest));
236 } catch(NullPointerException e) {
237 LOG.error("Package basicInfo is incorrect ! basicIonfo = " + ToolUtil.objectToString(basicInfo), e);
245 * Interface for Uploading package
248 * @param uploadedInputStream
253 * @throws IOException
254 * @throws MarketplaceResourceException
256 private Response handlePackageUpload(String packageId, InputStream uploadedInputStream,
257 FormDataContentDisposition fileDetail, String details, HttpHeaders head) throws IOException {
258 boolean bResult = handleDataValidate(packageId, uploadedInputStream, fileDetail);
260 LOG.error("Validation of Input received for Package Upload failed !!!");
261 return Response.status(Status.EXPECTATION_FAILED)
262 .entity(new CommonErrorResponse("Input package is empty or exception happened during validation"))
266 String fileName = "temp_" + packageId + ".csar";
267 if(null != fileDetail) {
268 LOG.info("the fileDetail = " + ToolUtil.objectToString(fileDetail));
270 fileName = ToolUtil.processFileName(fileDetail.getFileName());
273 String localDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName);
275 String contentRange = null;
277 contentRange = head.getHeaderString(CommonConstant.HTTP_HEADER_CONTENT_RANGE);
279 LOG.info("store package chunk file, fileName:" + fileName + ",contentRange:" + contentRange);
280 if(ToolUtil.isEmptyString(contentRange)) {
281 int fileSize = uploadedInputStream.available();
282 contentRange = "0-" + fileSize + "/" + fileSize;
285 String fileLocation = ToolUtil.storeChunkFileInLocal(localDirName, fileName, uploadedInputStream);
286 LOG.info("the fileLocation when upload package is :" + fileLocation);
288 uploadedInputStream.close();
291 Result result = OpenRemoteCli.run(new String[] { "-P", "onap-vtp", "csar-validate", "--csar", fileLocation, "--format", "json" });
292 LOG.info("CSAR validation is successful" + result.getOutput());
294 int exitCode = result.getExitCode();
295 String output = result.getOutput();
297 if((exitCode != 0) || !output.contains("\"error\":\"SUCCESS\"")) {
298 LOG.error("Could not validate failed");
299 return Response.status(Status.EXPECTATION_FAILED).entity(new CommonErrorResponse(output))
302 } catch (Exception e) {
303 LOG.error("CSAR validation panicked", e);
304 return Response.status(Status.EXPECTATION_FAILED).entity(
305 new CommonErrorResponse("Exception occurred while validating csar package:" + e.getMessage()))
309 UploadPackageResponse result = null;
311 result = manageUpload(packageId, fileName, fileLocation, details, contentRange);
312 } catch(ErrorCodeException e) {
313 return Response.status(Status.EXPECTATION_FAILED)
314 .entity(new CommonErrorResponse("Package Name already exists")).build();
317 return Response.ok(ToolUtil.objectToString(result), MediaType.APPLICATION_JSON).build();
319 return Response.serverError().build();
324 * Execute OnBarding request
326 * @param oOnboradingRequest
328 private void addOnBoardingRequest(final OnBoradingRequest oOnboradingRequest) {
329 ExecutorService es = Executors.newFixedThreadPool(CommonConstant.ONBOARDING_THREAD_COUNT);
330 Callable<Integer> callableInteger = () -> {
331 new OnBoardingHandler().handleOnBoardingReq(oOnboradingRequest);
332 return CommonConstant.SUCESS;
334 es.submit(callableInteger);
338 * delete package by package id.
340 * @param csarId package id
343 public Response delPackage(String csarId) {
344 LOG.info("delete package info.csarId:" + csarId);
345 if(ToolUtil.isEmptyString(csarId)) {
346 LOG.error("delete package fail, csarid is null");
347 return Response.serverError().build();
349 deletePackageDataById(csarId);
350 return Response.ok().build();
354 * Delete Package by CSAR ID
358 private void deletePackageDataById(String csarId) {
359 String packagePath = PackageWrapperUtil.getPackagePath(csarId);
360 if(packagePath == null) {
361 LOG.error("package path is null! ");
365 FileManagerFactory.createFileManager().delete(packagePath);
366 // Delete Results Data
367 FileManagerFactory.createFileManager().delete(File.separator + csarId);
369 // delete package data from database
371 PackageManager.getInstance().deletePackage(csarId);
372 } catch(MarketplaceResourceException e1) {
373 LOG.error("delete package by csarId from db error ! " + e1.getMessage(), e1);
378 * download package by package id.
380 * @param csarId package id
383 public Response downloadCsarPackagesById(String csarId) {
384 PackageData packageData = PackageWrapperUtil.getPackageInfoById(csarId);
386 String packageName = packageData.getName();
387 String path = org.onap.vnfsdk.marketplace.filemanage.http.ToolUtil.getHttpServerAbsolutePath()
388 + File.separatorChar + packageData.getType() + File.separatorChar + packageData.getProvider()
389 + File.separatorChar + packageData.getCsarId() + File.separator + packageName + File.separatorChar
390 + packageData.getVersion() + File.separator + packageName + ".csar";
392 LOG.info("downloadCsarPackagesById path is : " + path);
394 File csarFile = new File(path);
395 if(!csarFile.exists()) {
396 return Response.status(Status.INTERNAL_SERVER_ERROR).build();
399 LOG.info("downloadCsarPackagesById ABS path is : " + csarFile.getAbsolutePath());
402 InputStream fis = new BufferedInputStream(new FileInputStream(csarFile.getAbsolutePath()));
403 return Response.ok(fis).header("Content-Disposition", "attachment; filename=\"" + csarFile.getName() + "\"")
405 } catch(Exception e1) {
406 LOG.error("download vnf package fail.", e1);
407 return RestUtil.getRestException(e1.getMessage());
412 * get package file uri.
414 * @param csarId package id
415 * @param relativePath file relative path
418 public Response getCsarFileUri(String csarId) {
419 return downloadCsarPackagesById(csarId);
423 * Interface to Update Download count for CSAR ID
428 public Response updateDwonloadCount(String csarId) {
429 return handleDownladCountUpdate(csarId) ? Response.ok().build()
430 : Response.status(Status.EXPECTATION_FAILED).build();
434 * Handle downlowa count update
439 private boolean handleDownladCountUpdate(String csarId) {
440 boolean bupdateSucess = false;
442 PackageManager.getInstance().updateDownloadCount(csarId);
443 bupdateSucess = true;
444 } catch(Exception exp) {
445 LOG.error("Updating Donwload count failed for Package with ID !!! : " + exp.getMessage(), exp);
447 return bupdateSucess;
451 * Interface to Re upload Package
454 * @param uploadedInputStream
461 public Response reUploadPackage(String csarId, InputStream uploadedInputStream,
462 FormDataContentDisposition fileDetail, String details, HttpHeaders head)
463 throws MarketplaceResourceException {
464 LOG.info("Reupload request Received !!!!");
466 // STEP 1: Validate Input Data
467 // ----------------------------
468 boolean bResult = handleDataValidate(csarId, uploadedInputStream, fileDetail);
470 LOG.error("Validation of Input received for Package Upload failed during Reload!!!");
471 return Response.status(Status.EXPECTATION_FAILED).build();
475 // STEP 2: Delete All Package Data based on package id
476 // ----------------------------------------------------
477 deletePackageDataById(csarId);
479 // STEP 3: upload package with same package id
480 // -------------------------------------------
481 return handlePackageUpload(csarId, uploadedInputStream, fileDetail, details, head);
482 } catch(IOException e) {
483 LOG.error("delete package failed", e);
485 return Response.status(Status.INTERNAL_SERVER_ERROR).build();
489 * Interface to get OnBoarding Result by Operation Type
496 public Response getOnBoardingResult(String csarId, String operTypeId, String operId) {
497 LOG.info("getOnBoardingResult request : csarId:" + csarId + " operTypeId:" + operTypeId + " operId:" + operId);
499 PackageData packageData = PackageWrapperUtil.getPackageInfoById(csarId);
500 if(null == packageData) {
501 return Response.status(Response.Status.PRECONDITION_FAILED).build();
504 handleDelayExec(operId);
506 OnBoardingResult oOnBoardingResult = FunctionTestHook.getOnBoardingResult(packageData);
507 if(null == oOnBoardingResult) {
508 return Response.status(Response.Status.PRECONDITION_FAILED).build();
510 filterOnBoardingResultByOperId(oOnBoardingResult, operId);
512 String strResult = ToolUtil.objectToString(oOnBoardingResult);
513 LOG.info("getOnBoardingResult response : " + strResult);
514 return Response.ok(strResult, "application/json").build();
515 } catch(NullPointerException e) {
516 LOG.error("Null param in getOnBoardingResult", e);
517 return Response.status(Response.Status.BAD_REQUEST).build();
521 private void filterOnBoardingResultByOperId(OnBoardingResult oOnBoardingResult, String operId) {
522 if(0 == operId.compareToIgnoreCase("all")) {
525 if(0 == operId.compareToIgnoreCase("download")) {
526 List<OnBoardingOperResult> operResultListTemp = new ArrayList<>();
527 OnBoardingOperResult operResultListTmp = new OnBoardingOperResult();
528 operResultListTmp.setOperId("download");
529 operResultListTmp.setStatus(0);
530 operResultListTemp.add(operResultListTmp);
531 oOnBoardingResult.setOperResult(operResultListTemp);
534 List<OnBoardingOperResult> operResultListOut = new ArrayList<>();
535 List<OnBoardingOperResult> operResultList = oOnBoardingResult.getOperResult();
536 for(OnBoardingOperResult operResult : operResultList) {
537 if(0 == operResult.getOperId().compareToIgnoreCase(operId)) {
538 operResultListOut.add(operResult);
541 oOnBoardingResult.setOperResult(operResultListOut);
545 * Interface to get OnBoarding Status by Operation ID
551 public Response getOperResultByOperTypeId(String csarId, String operTypeId) {
552 LOG.error("getOnBoardingResult request : csarId:" + csarId + " operTypeId:" + operTypeId);
553 if(null == csarId || null == operTypeId || csarId.isEmpty() || operTypeId.isEmpty()) {
554 return Response.status(Status.BAD_REQUEST).build();
557 PackageData packageData = PackageWrapperUtil.getPackageInfoById(csarId);
558 if(null == packageData) {
559 LOG.error("Failed to find package for PackageID:" + csarId);
560 return Response.status(Status.PRECONDITION_FAILED).build();
563 // Get result key to fetch Function Test Results
564 // ---------------------------------------------
565 String strResult = FunctionTestHook.getFuncTestResults(packageData);
566 if(null == strResult) {
567 LOG.error("NULL reponse for getOperResultByOperTypeId response :" + strResult);
568 return Response.status(Status.INTERNAL_SERVER_ERROR).build();
570 LOG.info("getOperResultByOperTypeId response :" + strResult);
571 return Response.ok(strResult, MediaType.APPLICATION_JSON).build();
574 private boolean handleDataValidate(String packageId, InputStream uploadedInputStream,
575 FormDataContentDisposition fileDetail) {
576 boolean bvalidateOk = false;
577 if((null != uploadedInputStream) && (fileDetail != null) && !ToolUtil.isEmptyString(packageId)) {
584 * Interface to get OnBoarding Steps
588 public Response getOnBoardingSteps() {
589 LOG.info("Get OnBoarding Steps request Received !!!");
591 String filePath = org.onap.vnfsdk.marketplace.filemanage.http.ToolUtil.getAppDeployPath() + File.separator
592 + "generalconfig/OnBoardingSteps.json";
593 LOG.info("Onboarding Steps Json file Path :" + filePath);
595 OnBoardingSteps oOnBoardingSteps =
596 (OnBoardingSteps)FileUtil.readJsonDatafFromFile(filePath, OnBoardingSteps.class);
597 if(null == oOnBoardingSteps) {
598 return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
600 String strResult = ToolUtil.objectToString(oOnBoardingSteps);
601 LOG.info("getOnBoardingSteps response :" + strResult);
602 return Response.ok(strResult, MediaType.APPLICATION_JSON).build();
605 private void handleDelayExec(String operId) {
606 if(0 == operId.compareToIgnoreCase(CommonConstant.functionTest.FUNCTEST_EXEC)) {
609 } catch(InterruptedException e) {
610 LOG.info("handleDelayExex response : ", e);
611 Thread.currentThread().interrupt();