From 7c9d941a80634d40d03f38c3f24ea503822d4b79 Mon Sep 17 00:00:00 2001 From: "victor.gao" Date: Mon, 3 Jul 2017 11:44:26 +0800 Subject: Change: add OPEN-O seed code for VF-C Change-Id: Iecacac039e86db2eae006c8947d6dd681e458b83 Signed-off-by: victor.gao --- .../nfvo/vnfmadapter/common/AsyncCallback.java | 44 ++ .../vnfmadapter/common/DownloadCsarManager.java | 212 +++++++ .../vnfmadapter/common/RegisterConfigInfo.java | 96 +++ .../nfvo/vnfmadapter/common/ResultRequestUtil.java | 216 +++++++ .../nfvo/vnfmadapter/common/VnfmException.java | 74 +++ .../nfvo/vnfmadapter/common/VnfmJsonUtil.java | 78 +++ .../openo/nfvo/vnfmadapter/common/VnfmUtil.java | 94 +++ .../common/servicetoken/HttpRestfulHelp.java | 67 +++ .../common/servicetoken/VNFRestfulUtil.java | 460 +++++++++++++++ .../common/servicetoken/VnfmRestfulUtil.java | 404 +++++++++++++ .../activator/RoaVnfmService2DriverMgr.java | 58 ++ .../activator/RoaVnfmServicePostProcessor.java | 58 ++ .../adapter/impl/AdapterResourceManager.java | 644 +++++++++++++++++++++ .../service/adapter/impl/Driver2MSBManager.java | 110 ++++ .../adapter/impl/VnfmAdapter2DriverManager.java | 111 ++++ .../service/adapter/inf/IDriver2MSBManager.java | 55 ++ .../service/adapter/inf/IResourceManager.java | 79 +++ .../adapter/inf/IVnfmAdapter2DriverManager.java | 52 ++ .../impl/VnfmAdapter2DriverMgrService.java | 183 ++++++ .../internalsvc/impl/VnfmAdapterMgrService.java | 181 ++++++ .../inf/IVnfmAdapter2DriverMgrService.java | 42 ++ .../internalsvc/inf/IVnfmAdapterMgrService.java | 39 ++ .../vnfmadapter/service/constant/Constant.java | 136 +++++ .../service/constant/ParamConstants.java | 123 ++++ .../vnfmadapter/service/constant/UrlConstant.java | 53 ++ .../vnfmadapter/service/csm/api/ConnectInfo.java | 137 +++++ .../service/csm/connect/AbstractSslContext.java | 182 ++++++ .../service/csm/connect/ConnectMgrVnfm.java | 174 ++++++ .../service/csm/connect/HttpRequests.java | 375 ++++++++++++ .../service/csm/connect/SslAnonymousSocket.java | 89 +++ .../service/csm/connect/SslCertificateSocket.java | 87 +++ .../csm/connect/SslProtocolSocketFactory.java | 101 ++++ .../service/csm/inf/InterfaceConnectMgr.java | 45 ++ .../service/csm/inf/InterfaceVnfMgr.java | 83 +++ .../vnfmadapter/service/csm/vnf/VnfMgrVnfm.java | 223 +++++++ .../vnfmadapter/service/dao/impl/VnfmDaoImpl.java | 62 ++ .../vnfmadapter/service/dao/inf/AbstractDao.java | 50 ++ .../nfvo/vnfmadapter/service/dao/inf/VnfmDao.java | 87 +++ .../nfvo/vnfmadapter/service/entity/Vnfm.java | 110 ++++ .../vnfmadapter/service/mapper/VnfmMapper.java | 91 +++ .../nfvo/vnfmadapter/service/process/AuthMgr.java | 74 +++ .../vnfmadapter/service/process/RegisterMgr.java | 83 +++ .../nfvo/vnfmadapter/service/process/VnfMgr.java | 296 ++++++++++ .../service/process/VnfResourceMgr.java | 254 ++++++++ .../nfvo/vnfmadapter/service/rest/AuthRoa.java | 151 +++++ .../nfvo/vnfmadapter/service/rest/SwaggerRoa.java | 49 ++ .../service/rest/VnfAdapterResourceRoa.java | 68 +++ .../vnfmadapter/service/rest/VnfResourceRoa.java | 105 ++++ .../nfvo/vnfmadapter/service/rest/VnfRoa.java | 286 +++++++++ .../rest/exceptionmapper/ExceptionMessage.java | 64 ++ .../exceptionmapper/GenericExceptionMapper.java | 41 ++ .../exceptionmapper/ServiceExceptionMapper.java | 45 ++ 52 files changed, 7081 insertions(+) create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/AsyncCallback.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManager.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/RegisterConfigInfo.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtil.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmException.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmJsonUtil.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmUtil.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelp.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtil.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtil.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmService2DriverMgr.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessor.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManager.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManager.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManager.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IDriver2MSBManager.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IResourceManager.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IVnfmAdapter2DriverManager.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapter2DriverMgrService.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapterMgrService.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapter2DriverMgrService.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapterMgrService.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/Constant.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/ParamConstants.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/UrlConstant.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfo.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContext.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/ConnectMgrVnfm.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequests.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocket.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocket.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactory.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceConnectMgr.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceVnfMgr.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfm.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImpl.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/AbstractDao.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/VnfmDao.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/entity/Vnfm.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/mapper/VnfmMapper.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgr.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgr.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgr.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgr.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoa.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoa.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoa.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoa.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoa.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java create mode 100644 huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java (limited to 'huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org') diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/AsyncCallback.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/AsyncCallback.java new file mode 100644 index 00000000..3d2043de --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/AsyncCallback.java @@ -0,0 +1,44 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common; + +import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Async call back. + * .
+ * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class AsyncCallback implements RestfulAsyncCallback { + + private static final Logger LOGGER = LoggerFactory.getLogger(AsyncCallback.class); + + @Override + public void callback(RestfulResponse response) { + LOGGER.warn("function=callback, msg=status={}, content={}.", response.getStatus(), response.getResponseContent()); + } + + @Override + public void handleExcepion(Throwable e) { + LOGGER.error("function=callback, msg= e is {}.", e); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManager.java new file mode 100644 index 00000000..8d512e1a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManager.java @@ -0,0 +1,212 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.apache.http.Header; +import org.apache.http.HeaderElement; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * Utility class to download CSAR + * + * @author + * @version NFVO 0.5 Sep 5, 2016 + * + */ +public class DownloadCsarManager { + + private static final Logger LOG = LoggerFactory.getLogger(DownloadCsarManager.class); + + public static final int CACHE = 100 * 1024; + + private DownloadCsarManager(){ + //private constructor + } + + /** + * Download from given URL. + * @param url String + * @return + */ + public static String download(String url) { + return download(url, null); + } + + /** + * Download from given URL to given file location. + * @param url String + * @param filepath String + * @return + */ + public static String download(String url, String filepath) { + String status = ""; + try { + CloseableHttpClient client = HttpClients.createDefault(); + HttpGet httpget = new HttpGet(url); + CloseableHttpResponse response = client.execute(httpget); + + HttpEntity entity = response.getEntity(); + InputStream is = entity.getContent(); + if (filepath == null){ + filepath = getFilePath(response); //NOSONAR + } + + File file = new File(filepath); + file.getParentFile().mkdirs(); + FileOutputStream fileout = new FileOutputStream(file); + + byte[] buffer = new byte[CACHE]; + int ch; + while ((ch = is.read(buffer)) != -1) { + fileout.write(buffer,0,ch); + } + is.close(); + fileout.flush(); + fileout.close(); + status = Constant.DOWNLOADCSAR_SUCCESS; + + } catch (Exception e) { + status = Constant.DOWNLOADCSAR_FAIL; + LOG.error("Download csar file failed! "+ e.getMessage(), e); + } + return status; + } + + /** + * Retrieve file path from given response. + * @param response HttpResponse + * @return + */ + public static String getFilePath(HttpResponse response) { + String filepath = System.getProperty("java.home"); + String filename = getFileName(response); + + if (filename != null) { + filepath += filename; + } else { + filepath += getRandomFileName(); + } + return filepath; + } + + /** + * Retrieve file name from given response. + * @param response HttpResponse + * @return + */ + public static String getFileName(HttpResponse response) { + Header contentHeader = response.getFirstHeader("Content-Disposition"); + String filename = null; + if (contentHeader != null) { + HeaderElement[] values = contentHeader.getElements(); + if (values.length == 1) { + NameValuePair param = values[0].getParameterByName("filename"); + if (param != null) { + try { + filename = param.getValue(); + } catch (Exception e) { + LOG.error("getting filename failed! "+ e.getMessage(), e); + } + } + } + } + return filename; + } + + /** + * Provides random file name. + * @return + */ + public static String getRandomFileName() { + return String.valueOf(System.currentTimeMillis()); + } + + /** + * unzip CSAR packge + * @param fileName filePath + * @return + */ + public static int unzipCSAR(String fileName,String filePath){ + final int BUFFER = 2048; + int status=0; + + try { + ZipFile zipFile = new ZipFile(fileName); + Enumeration emu = zipFile.entries(); + int i=0; + while(emu.hasMoreElements()){ + ZipEntry entry = (ZipEntry)emu.nextElement(); + //read directory as file first,so only need to create directory + if (entry.isDirectory()) + { + new File(filePath + entry.getName()).mkdirs(); + continue; + } + BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); + File file = new File(filePath + entry.getName()); + //Because that is random to read zipfile,maybe the file is read first + //before the directory is read,so we need to create directory first. + File parent = file.getParentFile(); + if(parent != null && (!parent.exists())){ + parent.mkdirs(); + } + FileOutputStream fos = new FileOutputStream(file); + BufferedOutputStream bos = new BufferedOutputStream(fos,BUFFER); + + int count; + byte data[] = new byte[BUFFER]; + while ((count = bis.read(data, 0, BUFFER)) != -1) + { + bos.write(data, 0, count); + } + bos.flush(); + bos.close(); + bis.close(); + } + status=Constant.UNZIP_SUCCESS; + zipFile.close(); + } catch (Exception e) { + status=Constant.UNZIP_FAIL; + e.printStackTrace(); + } + return status; + } +} \ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/RegisterConfigInfo.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/RegisterConfigInfo.java new file mode 100644 index 00000000..126af305 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/RegisterConfigInfo.java @@ -0,0 +1,96 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common; + +import java.util.Locale; +import java.util.ResourceBundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provide function for reading register parameter. + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public class RegisterConfigInfo { + + private static final Logger LOGGER = LoggerFactory.getLogger(RegisterConfigInfo.class); + + private String serviceName; + + private String version; + + private String url; + + private String protocol; + + private String ip; + + private String port; + + private String ttl; + + private static RegisterConfigInfo regConfig = new RegisterConfigInfo(); + + private RegisterConfigInfo() { + ResourceBundle rb = ResourceBundle.getBundle("registerService", Locale.getDefault()); + serviceName = rb.getString("serviceName"); + version = rb.getString("version"); + url = rb.getString("url"); + protocol = rb.getString("protocol"); + ip = rb.getString("ip"); + port = rb.getString("port"); + ttl = rb.getString("ttl"); + } + + public static RegisterConfigInfo getInstance() { + return regConfig; + } + + public String getServiceName() { + return serviceName; + } + + public String getVersion() { + return version; + } + + public String getUrl() { + return url; + } + + public String getProtocol() { + return protocol; + } + + public String getIp() { + return ip; + } + + public String getPort() { + return port; + } + + public String getTtl() { + return ttl; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtil.java new file mode 100644 index 00000000..c47ad64c --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtil.java @@ -0,0 +1,216 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common; + +import java.io.IOException; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; + +import org.apache.commons.httpclient.HttpMethod; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.openo.nfvo.vnfmadapter.service.csm.connect.ConnectMgrVnfm; +import org.openo.nfvo.vnfmadapter.service.csm.connect.HttpRequests; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public final class ResultRequestUtil { + + private static final Logger LOG = LoggerFactory.getLogger(ResultRequestUtil.class); + + private ResultRequestUtil() throws VnfmException { + throw new VnfmException("can't be instanced."); + } + + /** + * common method + *
+ * + * @param vnfmObject + * @param path + * url defined + * @param methodName + * [get, put, delete, post] + * @param paramsJson + * raw data with json format, if methodName is get + * or delete, fill it with null + * @return + * @since NFVO 0.5 + */ + public static JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + + ConnectMgrVnfm mgrVcmm = new ConnectMgrVnfm(); + + if(Constant.HTTP_OK != mgrVcmm.connect(vnfmObject)) { + resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultJson.put("data", "connect fail."); + return resultJson; + } + + HttpMethod httpMethod = null; + try { + + String result = null; + String vnfPath = path.contains("%s") ? String.format(path, mgrVcmm.getRoaRand()) : path; + LOG.info("function=call, msg=url is {}, session is {}", vnfmObject.getString("url") + vnfPath, + mgrVcmm.getAccessSession()); + HttpRequests.Builder builder = new HttpRequests.Builder(Constant.ANONYMOUS) + .addHeader(Constant.ACCESSSESSION, mgrVcmm.getAccessSession()) + .setUrl(vnfmObject.getString("url"), vnfPath).setParams(paramsJson); + MethodType methodType = MethodType.methodType(HttpRequests.Builder.class, new Class[0]); + MethodHandle mt = + MethodHandles.lookup().findVirtual(builder.getClass(), methodName, methodType).bindTo(builder); + + builder = (HttpRequests.Builder)mt.invoke(); + httpMethod = builder.execute(); + result = httpMethod.getResponseBodyAsString(); + LOG.warn("function=call, msg=response status is {}. result is {}", httpMethod.getStatusCode(), result); + resultJson.put(Constant.RETCODE, httpMethod.getStatusCode()); + resultJson.put("data", result); + } catch(IOException e) { + LOG.info("function=call, msg=IOException, e is {}", e); + } catch(ReflectiveOperationException e) { + LOG.info("function=call, msg=ReflectiveOperationException, e is {}", e); + } catch(Throwable e) { + LOG.info("function=call, msg=Throwable, e is {}", e); + } finally { + if(httpMethod != null) { + httpMethod.releaseConnection(); + } + } + + if(httpMethod == null) { + resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultJson.put("data", "get connection error"); + } + + return resultJson; + } + + /** + * common method + *
+ * + * @param vnfmObject + * @param path + * url defined + * @param methodName + * [get, put, delete, post] + * @param paramsJson + * raw data with json format, if methodName is get + * or delete, fill it with null + * @return + * @since NFVO 0.5 + */ + public static JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson, + String authModel) { + LOG.info("request-param=" + paramsJson + ",authModel=" + authModel + ",path=" + path + ",vnfmInfo=" + + vnfmObject); + JSONObject resultJson = new JSONObject(); + + ConnectMgrVnfm mgrVcmm = new ConnectMgrVnfm(); + + if(Constant.HTTP_OK != mgrVcmm.connect(vnfmObject, authModel)) { + resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultJson.put("data", "connect fail."); + return resultJson; + } + + HttpMethod httpMethod = null; + try { + + String result = null; + String vnfPath = path.contains("%s") ? String.format(path, mgrVcmm.getRoaRand()) : path; + LOG.info("function=call, msg=url is {}, session is {}", vnfmObject.getString("url") + vnfPath, + mgrVcmm.getAccessSession()); + HttpRequests.Builder builder = + new HttpRequests.Builder(authModel).addHeader(Constant.ACCESSSESSION, mgrVcmm.getAccessSession()) + .setUrl(vnfmObject.getString("url"), vnfPath).setParams(paramsJson); + MethodType methodType = MethodType.methodType(HttpRequests.Builder.class, new Class[0]); + MethodHandle mt = + MethodHandles.lookup().findVirtual(builder.getClass(), methodName, methodType).bindTo(builder); + + builder = (HttpRequests.Builder)mt.invoke(); + httpMethod = builder.execute(); + result = httpMethod.getResponseBodyAsString(); + LOG.warn("function=call, msg=response status is {}. result is {}", httpMethod.getStatusCode(), result); + resultJson.put(Constant.RETCODE, httpMethod.getStatusCode()); + resultJson.put("data", result); + + // logout delete tokens + String token = mgrVcmm.getAccessSession(); + String roaRand = mgrVcmm.getRoaRand(); + String vnfmUrl = vnfmObject.getString("url"); + removeTokens(vnfmUrl, token, roaRand); + } catch(IOException e) { + LOG.info("function=call, msg=IOException, e is {}", e); + } catch(ReflectiveOperationException e) { + LOG.info("function=call, msg=ReflectiveOperationException, e is {}", e); + } catch(Throwable e) { + LOG.info("function=call, msg=Throwable, e is {}", e); + } finally { + if(httpMethod != null) { + httpMethod.releaseConnection(); + } + } + + if(httpMethod == null) { + resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultJson.put("data", "get connection error"); + } + + return resultJson; + } + + /** + *
+ * + * @since NFVO 0.5 + */ + private static void removeTokens(String vnfmUrl, String token, String roaRand) { + HttpMethod httpMethodToken = null; + String tokenUrl = String.format(ParamConstants.CSM_AUTH_DISCONNECT, "manoadmin", roaRand); + LOG.info("removeTokens tokenUrl=" + tokenUrl); + try { + httpMethodToken = new HttpRequests.Builder(Constant.CERTIFICATE).setUrl(vnfmUrl.trim(), tokenUrl) + .setParams("").addHeader("X-Auth-Token", token).delete().execute(); + int statusCode = httpMethodToken.getStatusCode(); + String result = httpMethodToken.getResponseBodyAsString(); + LOG.info("removeTokens int=" + statusCode + ", result=" + result); + } catch(IOException e) { + LOG.info("function=call, msg=IOException, e is {}", e); + } catch(Throwable e) { + LOG.info("function=call, msg=Throwable, e is {}", e); + } finally { + if(httpMethodToken != null) { + httpMethodToken.releaseConnection(); + } + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmException.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmException.java new file mode 100644 index 00000000..06517ef3 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmException.java @@ -0,0 +1,74 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common; + +/** + * VNFM exception. + * .
+ * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class VnfmException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * + * Constructor
+ * + * @since NFVO 0.5 + */ + public VnfmException() { + super(); + } + + /** + * + * Constructor
+ * + * @param message + * @param cause + * @since NFVO 0.5 + */ + public VnfmException(String message, Throwable cause) { + super(message, cause); + } + + /** + * + * Constructor
+ * + * @param message + * @since NFVO 0.5 + */ + public VnfmException(String message) { + super(message); + } + + /** + * + * Constructor
+ * + * @param cause + * @since NFVO 0.5 + */ + public VnfmException(Throwable cause) { + super(cause); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmJsonUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmJsonUtil.java new file mode 100644 index 00000000..ab9f7935 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmJsonUtil.java @@ -0,0 +1,78 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common; +import java.io.IOException; +import java.io.InputStream; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import net.sf.json.util.JSONTokener; + +/** + * VNFM JSON utils.
+ * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public final class VnfmJsonUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(VnfmJsonUtil.class); + + private VnfmJsonUtil(){ + //private constructor + } + + /** + * Get the JSON string from input http context. + *
+ * + * @param vnfReq HttpServletRequest + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static T getJsonFromContexts(HttpServletRequest vnfReq) { + try { + InputStream vnfInput = vnfReq.getInputStream(); + String vnfJsonStr = IOUtils.toString(vnfInput); + JSONTokener vnfJsonTokener = new JSONTokener(vnfJsonStr); + + if(vnfJsonTokener.nextClean() == Character.codePointAt("{", 0)) { + return (T)JSONObject.fromObject(vnfJsonStr); + } + + vnfJsonTokener.back(); + + if(vnfJsonTokener.nextClean() == Character.codePointAt("[", 0)) { + return (T)JSONArray.fromObject(vnfJsonStr); + } + } catch(IOException e) { + LOGGER.error("function=getJsonFromContext, msg=IOException occurs, e={}.", e); + } catch(JSONException e) { + LOGGER.error("function=getJsonFromContext, msg=JSONException occurs, e={}.", e); + } + + return null; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmUtil.java new file mode 100644 index 00000000..0da2142b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmUtil.java @@ -0,0 +1,94 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * Provide function of getting vnfmInfo + *
+ * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public final class VnfmUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(VnfmUtil.class); + + private VnfmUtil() { + + } + + /** + * Get vnfmInfo by ip + *
+ * + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public static JSONObject getVnfmById(String vnfmId) { + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(String.format(ParamConstants.ESR_GET_VNFM_URL, vnfmId), + VnfmRestfulUtil.TYPE_GET, null); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + LOGGER.error("funtion=getVnfmById, status={}", rsp.getStatus()); + return null; + } + return JSONObject.fromObject(rsp.getResponseContent()); + } + + public static JSONObject mockForTest(String vnfmId){ + String vInfo = "{\"vnfmId\":\"1234\", \"name\":\"vnfm\", \"type\":\"Tacker\", \"vimId\":\"\", \"vendor\":\"huawei\", \"version\":\"v1.0\", \"description\":\"vnfm\", \"certificateUrl\":\"\", \"url\":\"https://192.168.44.126:30001\", \"userName\":\"manoadmin\", \"password\":\"User@12345\", \"createTime\":\"2016-07-06 15:33:18\"}"; + JSONObject json = JSONObject.fromObject(vInfo); + json.put("vnfmId",vnfmId); + return json; + } + + /** + * Get vnfmInfo by id + *
+ * + * @param ip + * @return + * @since NFVO 0.5 + */ + public static String getVnfmIdByIp(String ip) { + RestfulResponse rsp = + VnfmRestfulUtil.getRemoteResponse(ParamConstants.ESR_GET_VNFMS_URL, VnfmRestfulUtil.TYPE_GET, null); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + return ""; + } + + JSONArray vnfmList = JSONArray.fromObject(rsp.getResponseContent()); + LOGGER.info("vnfm ip: {}, vnfmList: {}", ip, vnfmList); + for(int i = 0; i < vnfmList.size(); i++) { + if(vnfmList.getJSONObject(i).getString("url").contains(ip)) { + return vnfmList.getJSONObject(i).getString("vnfmId"); + } + } + + return ""; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelp.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelp.java new file mode 100644 index 00000000..9efd9a72 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelp.java @@ -0,0 +1,67 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common.servicetoken; + +import java.util.HashMap; +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.HttpRest; +import org.openo.baseservice.roa.util.restclient.Restful; + +/** + * HTTP Restful helper. + * .
+ * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class HttpRestfulHelp { + + public static final String PROTO_HTTPS = "https"; + + public static final String PROTO_HTTP = "http"; + + private static final Map INSTANCES = new HashMap<>(2); + + private HttpRestfulHelp() { + // constructor + } + + /** + * Factory method to create Restful instances. + *
+ * + * @param ssloptionfile + * @param restoptionfile + * @return + * @since NFVO 0.5 + */ + public static synchronized Restful getRestInstance(String ssloptionfile, String restoptionfile) { + Restful rest = INSTANCES.get(PROTO_HTTP); + if(rest != null) { + return rest; + } + rest = createHttpsRest(ssloptionfile, restoptionfile); + INSTANCES.put(PROTO_HTTP, rest); + return rest; + } + + private static Restful createHttpsRest(String ssloptionfile, String restoptionfile) { //NOSONAR + return new HttpRest(); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtil.java new file mode 100644 index 00000000..cf7c986f --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtil.java @@ -0,0 +1,460 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common.servicetoken; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.baseservice.roa.util.restclient.Restful; +import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback; +import org.openo.baseservice.roa.util.restclient.RestfulFactory; +import org.openo.baseservice.roa.util.restclient.RestfulOptions; +import org.openo.baseservice.roa.util.restclient.RestfulParametes; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * Utility class.
+ * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public final class VNFRestfulUtil { + + public static final String TYPE_GET = "get"; + + public static final String TYPE_ADD = "add"; + + public static final String TYPE_POST = "post"; + + public static final String TYPE_PUT = "put"; + + public static final String TYPE_DEL = "delete"; + + public static final int ERROR_STATUS_CODE = -1; + + public static final String CONTENT_TYPE = "Content-type"; + + public static final String APPLICATION = "application/json"; + + private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class); + + private VNFRestfulUtil() { + + } + + /** + * within our module, we support a default method to invoke + * + * @param methodNames String + * @param path + * rest service url + * @param methodName + * [post, delete, put, get, asyncPost, asyncDelete, asyncPut, + * asyncGet] + * @param bodyParam + * rest body msg + * @return + */ + @SuppressWarnings("unchecked") + public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulParametes restParametes = new RestfulParametes(); + Map headerMap = new HashMap<>(2); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restParametes.setHeaderMap(headerMap); + + if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) { + if(null != bodyParam) { + Map vnfParamMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + if(path.contains("?")) { + String[] vnFutlList = path.split("\\?"); + String[] vnFparams = vnFutlList[1].split("&"); + int paramsSize = vnFparams.length; + + for(int i = 0; i < paramsSize; i++) { + vnfParamMap.put(vnFparams[i].split("=")[0], vnFparams[i].split("=")[1]); + } + } + + String vnFparamKey = null; + Iterator nameItr = bodyParam.keys(); + while(nameItr.hasNext()) { + vnFparamKey = nameItr.next(); + vnfParamMap.put(vnFparamKey, bodyParam.get(vnFparamKey).toString()); + + } + LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamMap); + restParametes.setParamMap(vnfParamMap); + } + } else { + restParametes.setRawData(bodyParam == null ? null : bodyParam.toString()); + } + return getRestRes(methodNames, path, restParametes); + } + + + /** + * encapsulate the java reflect exception + * + * @param methodName + * Restful's method + * @param objects + * method param array + * @return + */ + private static boolean isAnyNull(Object... objects) { + for(int i = 0; i < objects.length; i++) { + if(objects[i] == null) { + return true; + } + } + return false; + + } + + private static Class[] formArray(Object[] objects) { + Class[] vnfClasses = new Class[objects.length]; + for(int i = 0; i < objects.length; i++) { + vnfClasses[i] = objects[i].getClass(); + } + return vnfClasses; + + } + + /** + * Helps to invoke methods on Restful. + *
+ * + * @param methodName + * @param objects + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRestRes(String methodName, Object... objects) { + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + if(isAnyNull(objects, rest)) { + return null; + } + + Class[] vnfClasses = formArray(objects); + + if(methodName.startsWith("async")) { + vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class; + } + + Class rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class; + MethodType mt = MethodType.methodType(rtType, vnfClasses); + Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest) + .invokeWithArguments(objects); + if(reuslt != null) { + return (RestfulResponse)reuslt; + } + LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName); + return null; + } catch(ReflectiveOperationException e) { + LOG.error("function=getRestRes, msg=error occurs, e={}.", e); + } catch(ServiceException e) { + + LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode()); + LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage()); + LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e); + RestfulResponse response = new RestfulResponse(); + response.setStatus(e.getHttpCode()); + response.setResponseJson(e.getCause().getMessage()); + return response; + + } catch(Throwable e) { //NOSONAR + try { + throw (VnfmException)new VnfmException().initCause(e.getCause()); + } catch(VnfmException e1) { + LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e); + } + + } + return null; + } + + /** + * Send request to manager. + * @param path + * @param methodName + * @param paraJson + * @return + */ + public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) { + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + String abPath = null; + String vnfmId = null; + if(paraJson != null && paraJson.containsKey("vnfmInfo")) { + JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo"); + vnfmId = vnfmObj.getString("id"); + } else { + abPath = path; + } + LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath); + + RestfulResponse restfulResponse = VNFRestfulUtil.getRestResByDefault(path, methodName, paraJson); + if(restfulResponse == null || abPath == null) { + LOG.error("function=sendReqToApp, msg=data from app is null"); + retJson.put("data", "get null result"); + } else if(restfulResponse.getStatus() == Constant.HTTP_OK) { + JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent()); + if(!abPath.contains("vnfdmgr/v1")) { + LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString()); + } + if(object.getInt("retCode") == Constant.REST_SUCCESS) { + retJson.put("retCode", Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data"))); + return retJson; + } else { + retJson.put("retCode", Constant.REST_FAIL); + if(object.containsKey("msg")) { + retJson.put("data", object.getString("msg")); + return retJson; + } else { + return object; + } + } + } else { + LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus()); + LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent()); + retJson.put("data", "send to app get error status: " + restfulResponse.getStatus()); + } + return retJson; + } + + /** + * append suffix to result with vnfmId + * + * @param vnfmId + * @param dataJson + * @return + */ + private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) { + Object result = new Object(); + if(vnfmId == null) { + return dataJson; + } + + if(dataJson instanceof JSONObject) { + JSONObject jsonObject = (JSONObject)dataJson; + jsonObject.put("vnfmId", vnfmId); + result = jsonObject; + } else if(dataJson instanceof JSONArray) { + JSONArray dataArray = (JSONArray)dataJson; + JSONArray resultArray = new JSONArray(); + + for(Object obj : dataArray) { + JSONObject jsonObject = JSONObject.fromObject(obj); + jsonObject.put("vnfmId", vnfmId); + resultArray.add(jsonObject); + } + result = resultArray; + } + return result; + } + + /** + * Make HTTP method calls
+ * + * @param paramsMap Map + * @param params String + * @param domainTokens String + * @param isNfvoApp Boolean + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map paramsMap, String params, String domainTokens, + boolean isNfvoApp) { + String utilUrl = paramsMap.get("url"); + String utilMethodType = paramsMap.get("methodType"); + String utilPath = paramsMap.get("path"); + String authMode = paramsMap.get("authMode"); + + RestfulResponse rsp = null; + Restful rest = null; + String sslOptionFile = ""; + try { + String restClientFile = "restclient.json"; + + if(isNfvoApp) { + sslOptionFile = "ssl.nfvo.properties"; + } else { + sslOptionFile = "ssl.vcmm.properties"; + } + + LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode); + + rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile); + + RestfulOptions opt = new RestfulOptions(); + String[] strs = utilPath.split("(http(s)?://)|:"); + + opt.setHost(strs[1]); + opt.setPort(Integer.parseInt(strs[2])); + + RestfulParametes restfulParametes = new RestfulParametes(); + Map headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(utilMethodType)) { + rsp = rest.get(utilUrl, restfulParametes, opt); + } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) { + rsp = rest.post(utilUrl, restfulParametes, opt); + } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) { + rsp = rest.put(utilUrl, restfulParametes, opt); + } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) { + rsp = rest.delete(utilUrl, restfulParametes, opt); + } + } + } catch(ServiceException e) { + LOG.error("function=restfulResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * Make HTTP method calls + *
+ * + * @param paramsMap + * @param params + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map paramsMap, String params) { + if(null == paramsMap){ + return null; + } + String url = paramsMap.get("url"); + String methodType = paramsMap.get("methodType"); + + RestfulResponse rsp = null; + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + + RestfulParametes restfulParametes = new RestfulParametes(); + Map headerMap = new HashMap<>(3); + headerMap.put(CONTENT_TYPE, APPLICATION); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if (rest != null) { + if (TYPE_GET.equalsIgnoreCase(methodType)) { + rsp = rest.get(url, restfulParametes); + } else if (TYPE_POST.equalsIgnoreCase(methodType)) { + rsp = rest.post(url, restfulParametes); + } else if (TYPE_PUT.equalsIgnoreCase(methodType)) { + rsp = rest.put(url, restfulParametes); + } else if (TYPE_DEL.equalsIgnoreCase(methodType)) { + rsp = rest.delete(url, restfulParametes); + } + } + } catch (ServiceException e) { + LOG.error("function=getRemoteResponse, get restful response catch exception {}", e); + } + return rsp; + } + + + /** + * Helps to make the parameter map. + *
+ * + * @param url + * @param methodType + * @param path + * @param authMode + * @return + * @since NFVO 0.5 + */ + public static Map generateParamsMap(String url, String methodType, String path, String authMode) { + Map utilParamsMap = new HashMap<>(6); + utilParamsMap.put("url", url); + utilParamsMap.put("methodType", methodType); + utilParamsMap.put("path", path); + utilParamsMap.put("authMode", authMode); + return utilParamsMap; + } + + /** + * Helps to make the parameter map.
+ * + * @param url + * @param methodType + * @param path + * @return + * @since NFVO 0.5 + */ + public static Map generateParamsMap(String url, String methodType, String path) { + Map paramsMap = new HashMap<>(6); + paramsMap.put("url", url); + paramsMap.put("methodType", methodType); + paramsMap.put("path", path); + paramsMap.put("authMode", "Certificate"); + return paramsMap; + } + + /** + * Cookup the response + *
+ * + * @param vnfmInfo + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public static JSONObject getResultToVnfm(JSONObject vnfmInfo, String vnfmId) { + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + if(vnfmInfo == null) { + LOG.error("function=getResultToVnfm, msg=data from vnfm is null"); + retJson.put("data", "get null result"); + return retJson; + } + + if(vnfmInfo.getInt("retCode") == Constant.REST_SUCCESS) { + retJson.put("retCode", Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data"))); + return retJson; + } else { + retJson.put("retCode", Constant.REST_FAIL); + if(vnfmInfo.containsKey("msg")) { + retJson.put("data", vnfmInfo.getString("msg")); + return retJson; + } else { + return vnfmInfo; + } + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtil.java new file mode 100644 index 00000000..7f177773 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtil.java @@ -0,0 +1,404 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.common.servicetoken; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.baseservice.roa.util.restclient.Restful; +import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback; +import org.openo.baseservice.roa.util.restclient.RestfulFactory; +import org.openo.baseservice.roa.util.restclient.RestfulOptions; +import org.openo.baseservice.roa.util.restclient.RestfulParametes; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * VNFM Restful Utility. + * .
+ * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public final class VnfmRestfulUtil { + + public static final String TYPE_GET = "get"; + + public static final String TYPE_ADD = "add"; + + public static final String TYPE_POST = "post"; + + public static final String TYPE_PUT = "put"; + + public static final String TYPE_DEL = "delete"; + + public static final int ERROR_STATUS_CODE = -1; + + private static final Logger LOG = LoggerFactory.getLogger(VnfmRestfulUtil.class); + + private VnfmRestfulUtil() { + + } + + /** + * within our module, we support a default method to invoke + * + * @param path + * rest service url + * @param methodNames + * [post, delete, put, get, asyncPost, asyncDelete, asyncPut, + * asyncGet] + * @param bodyParam + * rest body msg + * @return + */ + @SuppressWarnings("unchecked") + public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulParametes restParametes = new RestfulParametes(); + Map headerMap = new HashMap<>(2); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restParametes.setHeaderMap(headerMap); + + if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) { + if(null != bodyParam) { + Map vnfParamsMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + if(path.contains("?")) { + String[] vnfUtlList = path.split("\\?"); + String[] vnfParams = vnfUtlList[1].split("&"); + int paramsSize = vnfParams.length; + + for(int i = 0; i < paramsSize; i++) { + vnfParamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]); + } + } + + String vnfParamKey = null; + Iterator nameItr = bodyParam.keys(); + while(nameItr.hasNext()) { + vnfParamKey = nameItr.next(); + vnfParamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString()); + + } + LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamsMap); + restParametes.setParamMap(vnfParamsMap); + } + } else { + restParametes.setRawData(bodyParam == null ? null : bodyParam.toString()); + } + return getRestRes(methodNames, path, restParametes); + } + + /** + * encapsulate the java reflect exception + * + * @param methodName + * Restful's method + * @param objects + * method param array + * @return + */ + private static boolean isAnyNull(Object... objects) { + for(int i = 0; i < objects.length; i++) { + if(objects[i] == null) { + return true; + } + } + return false; + + } + + private static Class[] formArray(Object[] objects) { + Class[] vnfClasses = new Class[objects.length]; + for(int i = 0; i < objects.length; i++) { + vnfClasses[i] = objects[i].getClass(); + } + return vnfClasses; + + } + + /** + * Helps to invoke http methods Restful + *
+ * + * @param methodName String + * @param objects String + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRestRes(String methodName, Object... objects) { + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + if(isAnyNull(objects, rest)) { + return null; + } + + Class[] vnfClasses = formArray(objects); + + if(methodName.startsWith("async")) { + vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class; + } + + Class rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class; + MethodType mt = MethodType.methodType(rtType, vnfClasses); + Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest) + .invokeWithArguments(objects); + if(reuslt != null) { + return (RestfulResponse)reuslt; + } + LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName); + return null; + } catch(ReflectiveOperationException e) { + LOG.error("function=getRestRes, msg=error occurs, e={}.", e); + } catch(ServiceException e) { + + LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode()); + LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage()); + LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e); + RestfulResponse response = new RestfulResponse(); + response.setStatus(e.getHttpCode()); + response.setResponseJson(e.getCause().getMessage()); + return response; + + } catch(Throwable e) { //NOSONAR + try { + throw (VnfmException)new VnfmException().initCause(e.getCause()); + } catch(VnfmException e1) { + LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e); + } + + } + return null; + } + + /** + * Helps to send Request to vnfm. + *
+ * + * @param path String + * @param methodName String + * @param paraJson JSONObject + * @return + * @since NFVO 0.5 + */ + public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) { + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + String abPath = null; + String vnfmId = null; + if(paraJson != null && paraJson.containsKey("vnfmInfo")) { + JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo"); + vnfmId = vnfmObj.getString("id"); + } else { + abPath = path; + } + LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath); + + RestfulResponse restfulResponse = VnfmRestfulUtil.getRestResByDefault(path, methodName, paraJson); + if(restfulResponse == null || abPath == null) { + LOG.error("function=sendReqToApp, msg=data from app is null"); + retJson.put("data", "get null result"); + } else if(restfulResponse.getStatus() == Constant.HTTP_OK) { + JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent()); + if(!abPath.contains("vnfdmgr/v1")) { + LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString()); + } + if(object.getInt("retCode") == Constant.REST_SUCCESS) { + retJson.put("retCode", Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data"))); + return retJson; + } else { + retJson.put("retCode", Constant.REST_FAIL); + if(object.containsKey("msg")) { + retJson.put("data", object.getString("msg")); + return retJson; + } else { + return object; + } + } + } else { + LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus()); + LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent()); + retJson.put("data", "send to app get error status: " + restfulResponse.getStatus()); + } + return retJson; + } + + /** + * append suffix to result with vnfmId + * + * @param vnfmId + * @param dataJson + * @return + */ + private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) { + Object result = new Object(); + if(vnfmId == null) { + return dataJson; + } + + if(dataJson instanceof JSONObject) { + JSONObject jsonObject = (JSONObject)dataJson; + jsonObject.put("vnfmId", vnfmId); + result = jsonObject; + } else if(dataJson instanceof JSONArray) { + JSONArray dataArray = (JSONArray)dataJson; + JSONArray resultArray = new JSONArray(); + + for(Object obj : dataArray) { + JSONObject jsonObject = JSONObject.fromObject(obj); + jsonObject.put("vnfmId", vnfmId); + resultArray.add(jsonObject); + } + result = resultArray; + } + return result; + } + + /** + * Make request and get HTTP response + *
+ * + * @param paramsMap Map + * @param params String + * @param domainTokens String + * @param isNfvoApp boolean + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map paramsMap, String params, String domainTokens, + boolean isNfvoApp) { + String utilUrl = paramsMap.get("url"); + String utilMethodType = paramsMap.get("methodType"); + String utilPath = paramsMap.get("path"); + String authMode = paramsMap.get("authMode"); + + RestfulResponse rsp = null; + Restful rest = null; + String sslOptionFile = ""; + try { + String restClientFile = "restclient.json"; + + if(isNfvoApp) { + sslOptionFile = "ssl.nfvo.properties"; + } else { + sslOptionFile = "ssl.vcmm.properties"; + } + + LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode); + + rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile); + + RestfulOptions opt = new RestfulOptions(); + String[] strs = utilPath.split("(http(s)?://)|:"); + + opt.setHost(strs[1]); + opt.setPort(Integer.parseInt(strs[2])); + + RestfulParametes restfulParametes = new RestfulParametes(); + Map headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(utilMethodType)) { + rsp = rest.get(utilUrl, restfulParametes, opt); + } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) { + rsp = rest.post(utilUrl, restfulParametes, opt); + } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) { + rsp = rest.put(utilUrl, restfulParametes, opt); + } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) { + rsp = rest.delete(utilUrl, restfulParametes, opt); + } + } + } catch(ServiceException e) { + LOG.error("function=restfulResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * Make request and get HTTP response + *
+ * + * @param url String + * @param methodType String + * @param params String + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = null; + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + + RestfulParametes restfulParametes = new RestfulParametes(); + Map headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restfulParametes.setHeaderMap(headerMap); + if(params != null) { + restfulParametes.setRawData(params); + } + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(methodType)) { + rsp = rest.get(url, restfulParametes); + } else if(TYPE_POST.equalsIgnoreCase(methodType)) { + rsp = rest.post(url, restfulParametes); + } else if(TYPE_PUT.equalsIgnoreCase(methodType)) { + rsp = rest.put(url, restfulParametes); + } else if(TYPE_DEL.equalsIgnoreCase(methodType)) { + rsp = rest.delete(url, restfulParametes); + } + } + } catch(ServiceException e) { + LOG.error("function=getRemoteResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * Make Params map
+ * + * @param url String + * @param methodType String + * @param path String + * @param authMode String + * @return + * @since NFVO 0.5 + */ + public static Map generateParamsMap(String url, String methodType, String path, String authMode) { + Map utilParamsMap = new HashMap<>(6); + utilParamsMap.put("url", url); + utilParamsMap.put("methodType", methodType); + utilParamsMap.put("path", path); + utilParamsMap.put("authMode", authMode); + return utilParamsMap; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmService2DriverMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmService2DriverMgr.java new file mode 100644 index 00000000..4b67d2a0 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmService2DriverMgr.java @@ -0,0 +1,58 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.activator; + +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf.IVnfmAdapter2DriverMgrService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public class RoaVnfmService2DriverMgr implements DestructionAwareBeanPostProcessor { + + private static final Logger LOG = LoggerFactory.getLogger(RoaVnfmService2DriverMgr.class); + + @Override + public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { + if(bean instanceof IVnfmAdapter2DriverMgrService) { + IVnfmAdapter2DriverMgrService vnfmAdapterSvc = (IVnfmAdapter2DriverMgrService)bean; + vnfmAdapterSvc.register(); + LOG.info("Successfully Registered to Driver Manager!", RoaVnfmService2DriverMgr.class); + } + + return bean; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { + return bean; + } + + @Override + public void postProcessBeforeDestruction(Object bean, String name) throws BeansException { + // post processing + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessor.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessor.java new file mode 100644 index 00000000..b84b42f2 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessor.java @@ -0,0 +1,58 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.activator; + +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf.IVnfmAdapterMgrService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 31, 2016 + */ +public class RoaVnfmServicePostProcessor implements DestructionAwareBeanPostProcessor { + + private static final Logger LOG = LoggerFactory.getLogger(RoaVnfmServicePostProcessor.class); + + @Override + public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { + if(bean instanceof IVnfmAdapterMgrService) { + IVnfmAdapterMgrService vnfmAdapterSvc = (IVnfmAdapterMgrService)bean; + vnfmAdapterSvc.register(); + LOG.info("Successfully Registered to Microservice BUS!", RoaVnfmServicePostProcessor.class); + } + + return bean; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { + return bean; + } + + @Override + public void postProcessBeforeDestruction(Object bean, String name) throws BeansException { + //post processing + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManager.java new file mode 100644 index 00000000..8c731efd --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManager.java @@ -0,0 +1,644 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.adapter.impl; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.HttpStatus; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.vnfmadapter.common.DownloadCsarManager; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IResourceManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.UrlConstant; +import org.openo.nfvo.vnfmadapter.service.csm.connect.ConnectMgrVnfm; +import org.openo.nfvo.vnfmadapter.service.csm.connect.HttpRequests; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Resource Manager adapter class. + * .
+ * + * @author + * @version NFVO 0.5 Sep 13, 2016 + */ +public class AdapterResourceManager implements IResourceManager { + + private static final Logger LOG = LoggerFactory.getLogger(AdapterResourceManager.class); + + @Override + public JSONObject uploadVNFPackage(JSONObject vnfpkg, Map paramsMap) { + JSONObject resultObj = new JSONObject(); + JSONObject csarTempObj = new JSONObject(); + + try { + // if upper layer do not provide vnfpackage info,then get the + // vnfpackage info from JSON file. + if(vnfpkg == null || vnfpkg.isEmpty()) { + String vnfPkgInfo = readVfnPkgInfoFromJson(); + vnfpkg = JSONObject.fromObject(vnfPkgInfo); // NOSONAR + } + } catch(IOException e) { + LOG.error("function=uploadVNFPackage", e); + } + + // check if parameters are null. + if(paramsMap == null || paramsMap.isEmpty()) { + resultObj.put("reason", "csarid and vnfmid are null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + String csarid = paramsMap.get("csarid"); + String vnfmid = paramsMap.get("vnfmid"); + String vnfdid = ""; + String vnfDescriptorId = paramsMap.get("vnfDescriptorId"); + if(null == csarid || "".equals(csarid)) { + resultObj.put("reason", "csarid is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + if(null == vnfmid || "".equals(vnfmid)) { + resultObj.put("reason", "vnfmid is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + // obtain CSAR package info + JSONObject csarobj = getVnfmCsarInfo(csarid); + String downloadUri = ""; + if(Integer.valueOf(csarobj.get("retCode").toString()) == Constant.HTTP_OK) { + LOG.info("get CSAR info successful.", csarobj.get("retCode")); + downloadUri = csarobj.getString("downloadUri"); + } else { + LOG.error("get CSAR info fail.", csarobj.get("retCode")); + resultObj.put("reason", csarobj.get("reason").toString()); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + csarTempObj = vnfpkg.getJSONObject("template"); + String csarfilepath = csarTempObj.getString("csar_file_path"); + String csarfilename = csarTempObj.getString("csar_file_name"); + + // download csar package and save in location. + JSONObject downloadObject = + downloadCsar(downloadUri, csarfilepath + System.getProperty("file.separator") + csarfilename); + + if(Integer.valueOf(downloadObject.get("retCode").toString()) != Constant.REST_SUCCESS) { + LOG.error("download CSAR fail.", downloadObject.get("retCode")); + resultObj.put("reason", downloadObject.get("reason").toString()); + resultObj.put("retCode", downloadObject.get("retCode").toString()); + return resultObj; + } + LOG.info("download CSAR successful.", downloadObject.get("retCode")); + + // unzip csar package to location. + JSONObject unzipObject = + unzipCSAR(csarfilepath + System.getProperty("file.separator") + csarfilename, csarfilepath); + + if(Integer.valueOf(unzipObject.get("retCode").toString()) != Constant.REST_SUCCESS) { + LOG.error("unzip CSAR fail.", unzipObject.get("retCode")); + resultObj.put("reason", unzipObject.get("reason").toString()); + resultObj.put("retCode", unzipObject.get("retCode").toString()); + return resultObj; + } + LOG.info("unzip CSAR successful.", unzipObject.get("retCode")); + + Map vnfmMap = new HashMap<>(); + vnfmMap.put("url", String.format(UrlConstant.REST_VNFMINFO_GET, vnfmid)); + vnfmMap.put("methodType", Constant.GET); + + // get VNFM connection info + JSONObject vnfmObject = getVnfmConnInfo(vnfmMap); + if(Integer.valueOf(vnfmObject.get("retCode").toString()) != Constant.HTTP_OK) { + LOG.error("get Vnfm Connection Info fail.", vnfmObject.get("retCode")); + resultObj.put("reason", vnfmObject.get("reason").toString()); + resultObj.put("retCode", vnfmObject.get("retCode").toString()); + return resultObj; + } + LOG.info("get Vnfm Connection Info successful.", vnfmObject.get("retCode")); + + String vnfmUrl = vnfmObject.getString("url"); + String userName = vnfmObject.getString("userName"); + String password = vnfmObject.getString("password"); + + // build VNFM connection and get token + ConnectMgrVnfm mgrVcmm = new ConnectMgrVnfm(); + + JSONObject connObject = new JSONObject(); + connObject.put("url", vnfmUrl); + connObject.put("userName", userName); + connObject.put("password", password); + if(Constant.HTTP_OK != mgrVcmm.connect(vnfmObject, Constant.CERTIFICATE)) { + LOG.error("get Access Session fail."); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "connect fail."); + return resultObj; + } + LOG.info("get Access Session successful."); + String connToken = mgrVcmm.getAccessSession(); + + // get vim_id + JSONObject cloudObject = getAllCloud(vnfmUrl, connToken); + String vimId = ""; + + if(!cloudObject.isEmpty() && cloudObject.get(Constant.RETCODE).equals(HttpStatus.SC_OK)) { + LOG.info("get all cloud successful.", cloudObject.get(Constant.RETCODE)); + vimId = cloudObject.getString("vim_id"); + } else { + LOG.error("get all cloud fail.", cloudObject.get(Constant.RETCODE)); + return cloudObject; + } + + // upload VNF package + csarTempObj.put("vim_id", vimId); + vnfpkg.put("template", csarTempObj); + + JSONObject uploadPkgObject = upload(vnfpkg, vnfmUrl, connToken); + LOG.info("uploadPkgObject:" + uploadPkgObject); + if(vnfdid == null || "".equals(vnfdid.trim())) { + JSONObject vnfdConf = readVnfdIdInfoFromJson(); + LOG.info("vnfdConf=" + vnfdConf); + if(vnfdConf.containsKey(vnfDescriptorId)) { + vnfdid = vnfdConf.getString(vnfDescriptorId); + } + } + LOG.info("set vnfdId=" + vnfdid); + + // get vnfd version + String vnfdVersion = ""; + + JSONObject vnfdVerObject = + getVnfdVersion(vnfmUrl, String.format(UrlConstant.URL_VNFDINFO_GET, vnfdid), connToken); + LOG.info("vnfdVerObject:" + vnfdVerObject); + if(!vnfdVerObject.isEmpty() && vnfdVerObject.get(Constant.RETCODE).equals(HttpStatus.SC_OK)) { + LOG.info("get vnfd version successful.", vnfdVerObject.get(Constant.RETCODE)); + JSONArray verArr = vnfdVerObject.getJSONArray("templates"); + JSONObject verTmpObj = verArr.getJSONObject(0); + + vnfdVersion = verTmpObj.getString("vnfdVersion"); + } else { + LOG.error("get vnfd version fail.", vnfdVerObject.get(Constant.RETCODE)); + return vnfdVerObject; + } + + // get vnfd plan info + String planName = ""; + String planId = ""; + + JSONObject vnfdPlanInfo = getVNFDPlanInfo(vnfmUrl, vnfdid, connToken); + LOG.info("vnfdPlanInfo:" + vnfdPlanInfo); + JSONObject inputsObj = new JSONObject(); + if(!vnfdPlanInfo.isEmpty() && vnfdPlanInfo.get(Constant.RETCODE).equals(HttpStatus.SC_OK)) { + LOG.info("get vnfd plan info successful.", vnfdPlanInfo.get(Constant.RETCODE)); + JSONObject planTmpObj = vnfdPlanInfo.getJSONObject("template"); + String templateName = planTmpObj.getString("template_name").trim(); + JSONArray topoTmpObj = planTmpObj.getJSONArray("topology_template"); + + JSONObject planObj = topoTmpObj.getJSONObject(0); + if("VNFD_vUGW".equals(templateName)) { + for(int i = 0; i < topoTmpObj.size(); i++) { + String name = topoTmpObj.getJSONObject(i).getString("plan_name").trim(); + if("Normal_E9K".equals(name)) { + planObj = topoTmpObj.getJSONObject(i); + } + } + } + + planName = planObj.getString("plan_name"); + planId = planObj.getString("plan_id"); + if(planObj.containsKey("inputs")) { + JSONArray inputs = planObj.getJSONArray("inputs"); + for(int i = 0; i < inputs.size(); i++) { + JSONObject obj = inputs.getJSONObject(i); + obj.put("value", obj.getString("default")); + } + inputsObj.put("inputs", inputs); + inputsObj.put("External_network", new JSONArray()); + } + } else { + LOG.error("get vnfd plan info fail.", vnfdPlanInfo.get(Constant.RETCODE)); + return vnfdPlanInfo; + } + + // return values + resultObj.put("retCode", Constant.HTTP_OK); + resultObj.put("vnfdId", vnfdid); + resultObj.put("vnfdVersion", vnfdVersion); + resultObj.put("planName", planName); + resultObj.put("planId", planId); + resultObj.put("parameters", inputsObj); + LOG.info("resultObj:" + resultObj.toString()); + + return resultObj; + } + + private JSONObject sendRequest(Map paramsMap) { + JSONObject resultObj = new JSONObject(); + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + if(null == rsp) { + LOG.error("function=sendRequest, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_OK) { + LOG.warn("function=sendRequest, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_OK); + return resultObj; + } else { + LOG.error("function=sendRequest, msg=ESR return fail,status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj.put("reason", "ESR return fail."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + @Override + public JSONObject getVnfmCsarInfo(String csarid) { + JSONObject resultObj = new JSONObject(); + + if(null == csarid || "".equals(csarid)) { + resultObj.put("reason", "csarid is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + Map paramsMap = new HashMap(); + + paramsMap.put("url", String.format(UrlConstant.REST_CSARINFO_GET, csarid)); + paramsMap.put("methodType", Constant.GET); + + return this.sendRequest(paramsMap); + } + + @Override + public JSONObject downloadCsar(String url, String filePath) { + JSONObject resultObj = new JSONObject(); + + if(url == null || "".equals(url)) { + resultObj.put("reason", "url is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + if(filePath == null || "".equals(filePath)) { + resultObj.put("reason", "downloadUrl filePath is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + String status = DownloadCsarManager.download(url, filePath); + + if(Constant.DOWNLOADCSAR_SUCCESS.equals(status)) { + resultObj.put("reason", "download csar file successfully."); + resultObj.put("retCode", Constant.REST_SUCCESS); + } else { + resultObj.put("reason", "download csar file failed."); + resultObj.put("retCode", Constant.REST_FAIL); + } + return resultObj; + } + + @Override + public JSONObject getAllCloud(String url, String conntoken) { + JSONObject resultObj = new JSONObject(); + JSONArray resArray = new JSONArray(); + + if(url == null || url.equals("")) { + url = "http://127.0.0.1:31943"; + } + + // get vim_id + HttpMethod httpMethodCloud = null; + try { + httpMethodCloud = + new HttpRequests.Builder(Constant.CERTIFICATE).setUrl(url.trim(), UrlConstant.URL_ALLCLOUD_NEW_GET) + .addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).setParams("").get().execute(); + + int statusCode = httpMethodCloud.getStatusCode(); + + String result = httpMethodCloud.getResponseBodyAsString(); + LOG.info(result); + if(statusCode == HttpStatus.SC_OK) { + JSONObject vimInfo = JSONObject.fromObject(result); + resArray = vimInfo.getJSONArray("vim_info"); + resultObj = resArray.getJSONObject(0); + resultObj.put(Constant.RETCODE, statusCode); + } else { + LOG.error("uploadVNFPackage get allcloud failed, code:" + statusCode + " re:" + result); + resultObj.put(Constant.RETCODE, statusCode); + resultObj.put("reason", "get allcloud failed. code:" + statusCode + " re:" + result); + return resultObj; + } + } catch(JSONException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get allcloud JSONException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get allcloud failed and JSONException." + e.getMessage()); + return resultObj; + } catch(VnfmException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get allcloud VnfmException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get allcloud failed and VnfmException." + e.getMessage()); + return resultObj; + } catch(IOException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get allcloud IOException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get allcloud failed and IOException." + e.getMessage()); + return resultObj; + } + return resultObj; + } + + /** + * Upload vnfpackage
+ * + * @param vnfpackage + * @param vnfmurl + * @param conntoken + * @return + * @since NFVO 0.5 + */ + public JSONObject upload(JSONObject vnfpackage, String vnfmurl, String conntoken) { + JSONObject resultObj = new JSONObject(); + HttpMethod httpMethodVnf = null; + + try { + httpMethodVnf = new HttpRequests.Builder(Constant.CERTIFICATE) + .setUrl(vnfmurl.trim(), UrlConstant.URL_VNFPACKAGE_POST).setParams(vnfpackage.toString()) + .addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).post().execute(); + + int statusCodeUp = httpMethodVnf.getStatusCode(); + + String resultUp = httpMethodVnf.getResponseBodyAsString(); + + if(statusCodeUp == HttpStatus.SC_CREATED || statusCodeUp == HttpStatus.SC_OK) { + LOG.info("uploadVNFPackage upload VNF package successful, code:" + statusCodeUp + " re:" + resultUp); + resultObj = JSONObject.fromObject(resultUp); + resultObj.put(Constant.RETCODE, statusCodeUp); + } else { + LOG.error("uploadVNFPackage upload VNF package failed, code:" + statusCodeUp + " re:" + resultUp); + resultObj.put(Constant.RETCODE, statusCodeUp); + resultObj.put("data", "upload VNF package failed, code:" + statusCodeUp + " re:" + resultUp); + return resultObj; + } + } catch(JSONException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package JSONException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "upload VNF package failed and JSONException." + e.getMessage()); + return resultObj; + } catch(VnfmException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package VnfmException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "upload VNF package failed and VnfmException." + e.getMessage()); + return resultObj; + } catch(IOException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package IOException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "upload VNF package failed and IOException." + e.getMessage()); + return resultObj; + } + return resultObj; + } + + /** + * Find vnfd version.
+ * + * @param prefixUrl + * @param serviceUrl + * @return + * @since NFVO 0.5 + */ + public JSONObject getVnfdVersion(String prefixUrl, String serviceUrl, String conntoken) { + JSONObject resultObj = new JSONObject(); + HttpMethod httpMethodVnfd = null; + try { + httpMethodVnfd = new HttpRequests.Builder(Constant.CERTIFICATE).setUrl(prefixUrl.trim(), serviceUrl) + .setParams("").addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).get().execute(); + + int statusCodeVnfd = httpMethodVnfd.getStatusCode(); + + String resultVnfd = httpMethodVnfd.getResponseBodyAsString(); + LOG.info("getVnfdVersion result:" + resultVnfd); + if(statusCodeVnfd == HttpStatus.SC_OK) { + resultObj = JSONObject.fromObject(resultVnfd); + resultObj.put(Constant.RETCODE, statusCodeVnfd); + } else { + LOG.error("uploadVNFPackage vnfd version failed, code:" + statusCodeVnfd + " re:" + resultVnfd); + resultObj.put(Constant.RETCODE, statusCodeVnfd); + resultObj.put("data", "get vnfd version failed, code:" + statusCodeVnfd + " re:" + resultVnfd); + return resultObj; + } + } catch(JSONException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get vnfd version JSONException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get vnfd version failed and JSONException." + e.getMessage()); + return resultObj; + } catch(VnfmException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get vnfd version VnfmException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get vnfd version failed and VnfmException." + e.getMessage()); + return resultObj; + } catch(IOException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get vnfd version IOException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get vnfd version failed and IOException." + e.getMessage()); + return resultObj; + } + return resultObj; + } + + /** + * Find VNFM connection information.
+ * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + public JSONObject getVnfmConnInfo(Map paramsMap) { + return this.sendRequest(paramsMap); + } + + @Override + public JSONObject getVNFDPlanInfo(String url, String vnfdid, String conntoken) { + JSONObject resultObj = new JSONObject(); + + HttpMethod httpMethodPlan = null; + try { + httpMethodPlan = new HttpRequests.Builder(Constant.CERTIFICATE) + .setUrl(url.trim(), String.format(UrlConstant.URL_VNFDPLANINFO_GET, vnfdid)).setParams("") + .addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).get().execute(); + + int statusCode = httpMethodPlan.getStatusCode(); + + String result = httpMethodPlan.getResponseBodyAsString(); + LOG.info("getVNFDPlanInfo result=" + result); + if(statusCode == HttpStatus.SC_OK) { + resultObj = JSONObject.fromObject(result); + resultObj.put(Constant.RETCODE, statusCode); + } else { + LOG.error("uploadVNFPackage get VNFDPlanInfo failed, code:" + statusCode + " re:" + result); + resultObj.put(Constant.RETCODE, statusCode); + resultObj.put("reason", "get VNFDPlanInfo failed. code:" + statusCode + " re:" + result); + return resultObj; + } + } catch(JSONException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get VNFDPlanInfo JSONException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get VNFDPlanInfo failed and JSONException." + e.getMessage()); + return resultObj; + } catch(VnfmException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get VNFDPlanInfo VnfmException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get VNFDPlanInfo failed and VnfmException." + e.getMessage()); + return resultObj; + } catch(IOException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get VNFDPlanInfo IOException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get VNFDPlanInfo failed and IOException." + e.getMessage()); + return resultObj; + } + return resultObj; + } + + /** + * Get VNF package information.
+ * + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static String readVfnPkgInfoFromJson() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "vnfpkginfo" + System.getProperty("file.separator") + + Constant.VNFPKGINFO; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } finally { + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } + + return fileContent; + } + + private static JSONObject readVnfdIdInfoFromJson() { + JSONObject jsonObject = new JSONObject(); + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "vnfpkginfo" + System.getProperty("file.separator") + + "vnfd_ids.json"; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + if(fileContent != null) { + jsonObject = JSONObject.fromObject(fileContent).getJSONObject("vnfdIds"); + } + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } catch(Exception e) { + LOG.error(fileName + " read error!", e); + } finally { + + } + + return jsonObject; + } + + /* + * unzip CSAR packge + * @param fileName filePath + * @return + */ + public JSONObject unzipCSAR(String fileName, String filePath) { + JSONObject resultObj = new JSONObject(); + + if(fileName == null || "".equals(fileName)) { + resultObj.put("reason", "fileName is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + if(filePath == null || "".equals(filePath)) { + resultObj.put("reason", "unzipCSAR filePath is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + int status = DownloadCsarManager.unzipCSAR(fileName, filePath); + + if(Constant.UNZIP_SUCCESS == status) { + resultObj.put("reason", "unzip csar file successfully."); + resultObj.put("retCode", Constant.REST_SUCCESS); + } else { + resultObj.put("reason", "unzip csar file failed."); + resultObj.put("retCode", Constant.REST_FAIL); + } + return resultObj; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManager.java new file mode 100644 index 00000000..bd8d3c17 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManager.java @@ -0,0 +1,110 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.adapter.impl; + +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IDriver2MSBManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * + * Driver to MSB Manager Class.
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 29, 2016 + */ +public class Driver2MSBManager implements IDriver2MSBManager { + + private static final Logger LOG = LoggerFactory.getLogger(Driver2MSBManager.class); + + @Override + public JSONObject registerDriver(Map paramsMap, JSONObject driverInfo) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, driverInfo.toString()); + if(null == rsp) { + LOG.error("function=registerDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_CREATED) { + LOG.warn("function=registerDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_CREATED); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { + LOG.error("function=registerDriver, msg=MSB return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error("function=registerDriver, msg=MSB return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + @Override + public JSONObject unregisterDriver(Map paramsMap) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + if(null == rsp) { + LOG.error("function=unregisterDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_NOCONTENT) { + LOG.warn("function=unregisterDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_NOCONTENT); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_NOTFOUND) { + LOG.error( + "function=unregisterDriver, msg=MSB return fail,can't find the service instance.status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,can't find the service instance."); + } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { + LOG.error("function=unregisterDriver, msg=MSB return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error("function=unregisterDriver, msg=MSB return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManager.java new file mode 100644 index 00000000..211536f9 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManager.java @@ -0,0 +1,111 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.adapter.impl; + +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IVnfmAdapter2DriverManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public class VnfmAdapter2DriverManager implements IVnfmAdapter2DriverManager { + + private static final Logger LOG = LoggerFactory.getLogger(VnfmAdapter2DriverManager.class); + + @Override + public JSONObject registerDriver(Map paramsMap, JSONObject driverInfo) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, driverInfo.toString()); + if(null == rsp) { + LOG.error("function=registerDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_CREATED) { + LOG.warn("function=registerDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj.put("retCode", Constant.HTTP_CREATED); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { + LOG.error("function=registerDriver, msg=DriverManager return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error( + "function=registerDriver, msg=DriverManager return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + @Override + public JSONObject unregisterDriver(Map paramsMap) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + if(null == rsp) { + LOG.error("function=unregisterDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_NOCONTENT) { + LOG.warn("function=unregisterDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_NOCONTENT); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_NOTFOUND) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,can't find the service instance.status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,can't find the service instance."); + } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IDriver2MSBManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IDriver2MSBManager.java new file mode 100644 index 00000000..6d2ff9aa --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IDriver2MSBManager.java @@ -0,0 +1,55 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.adapter.inf; + +import java.util.Map; + +import net.sf.json.JSONObject; + +/** + * + * IDriver to MSB Manager Class.
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 29, 2016 + */ +public interface IDriver2MSBManager { + + /** + * + * Method to Register Driver.
+ * + * @param paramsMap + * @param driverInfo + * @return + * @since NFVO 0.5 + */ + JSONObject registerDriver(Map paramsMap, JSONObject driverInfo); + + /** + * + * Method to Unregister Driver.
+ * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + JSONObject unregisterDriver(Map paramsMap); + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IResourceManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IResourceManager.java new file mode 100644 index 00000000..8eb7cbf1 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IResourceManager.java @@ -0,0 +1,79 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.adapter.inf; + +import java.util.Map; + +import net.sf.json.JSONObject; + +/** + * Resource Manager interface.
+ * + * @author + * @version NFVO 0.5 Sep 13, 2016 + */ +public interface IResourceManager { + + /** + * Get VNFM CSAR information
+ * + * @param csarid String + * @return + * @since NFVO 0.5 + */ + JSONObject getVnfmCsarInfo(String csarid); + + /** + * Download CSAR.
+ * + * @param url String + * @param filePath String + * @return + * @since NFVO 0.5 + */ + JSONObject downloadCsar(String url,String filePath); + + /** + * Get all clouds
+ * + * @param url String + * @return + * @since NFVO 0.5 + */ + JSONObject getAllCloud(String url,String connToken); + + + /** + * get VNFD Plan Info.
+ * + * @param url String + * @param vnfdid String + * @return + * @since NFVO 0.5 + */ + JSONObject getVNFDPlanInfo(String url, String vnfdid, String conntoken); + + /** + * Upload VNF package.
+ * + * @param vnfpkg JSONObject + * @param paramsMap Map + * @return + * @since NFVO 0.5 + */ + JSONObject uploadVNFPackage(JSONObject vnfpkg, Map paramsMap); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IVnfmAdapter2DriverManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IVnfmAdapter2DriverManager.java new file mode 100644 index 00000000..10b42429 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IVnfmAdapter2DriverManager.java @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.adapter.inf; + +import java.util.Map; + +import net.sf.json.JSONObject; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public interface IVnfmAdapter2DriverManager { + + /** + * Method to Register Driver.
+ * + * @param paramsMap + * @param driverInfo + * @return + * @since NFVO 0.5 + */ + JSONObject registerDriver(Map paramsMap, JSONObject driverInfo); + + /** + * Method to Unregister Driver.
+ * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + JSONObject unregisterDriver(Map paramsMap); + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapter2DriverMgrService.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapter2DriverMgrService.java new file mode 100644 index 00000000..42cef38a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapter2DriverMgrService.java @@ -0,0 +1,183 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.api.internalsvc.impl; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executors; + +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.vnfmadapter.service.adapter.impl.VnfmAdapter2DriverManager; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IVnfmAdapter2DriverManager; +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf.IVnfmAdapter2DriverMgrService; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.UrlConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public class VnfmAdapter2DriverMgrService implements IVnfmAdapter2DriverMgrService { + + private static final Logger LOG = LoggerFactory.getLogger(VnfmAdapter2DriverMgrService.class); + + public static final String VNFMADAPTER2DRIVERMGR = "vnfmadapter2drivermgr.json"; + + @Override + public void register() { + // set URL and mothedtype + Map paramsMap = new HashMap<>(); + paramsMap.put("url", UrlConstant.REST_DRIVERMGR_REGISTER); + paramsMap.put("methodType", Constant.POST); + + // get vim adapter info and raise registration + try { + String adapterInfo = readVnfmAdapterInfoFromJson(); + if(!"".equals(adapterInfo)) { + JSONObject adapterObject = JSONObject.fromObject(adapterInfo); + RegisterVnfm2DriverMgrThread vnfmAdapterThread = + new RegisterVnfm2DriverMgrThread(paramsMap, adapterObject); + Executors.newSingleThreadExecutor().submit(vnfmAdapterThread); + } else { + LOG.error("vnfmadapter2drivermgr info is null,please check!"); + } + + } catch(IOException e) { + LOG.error("Failed to read vnfmadapter2drivermgr info! " + e.getMessage(), e); + } + + } + + /** + * Retrieve VIM driver information. + * + * @return + * @throws IOException + */ + public static String readVnfmAdapterInfoFromJson() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "adapterInfo" + System.getProperty("file.separator") + + VNFMADAPTER2DRIVERMGR; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } finally { + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } + + return fileContent; + } + + private static class RegisterVnfm2DriverMgrThread implements Runnable { + + // Thread lock Object + private final Object lockObject = new Object(); + + private IVnfmAdapter2DriverManager adapter2DriverMgr = new VnfmAdapter2DriverManager(); + + // url and mothedtype + private Map paramsMap; + + // driver body + private JSONObject adapterInfo; + + public RegisterVnfm2DriverMgrThread(Map paramsMap, JSONObject adapterInfo) { + this.paramsMap = paramsMap; + this.adapterInfo = adapterInfo; + } + + @Override + public void run() { + LOG.info("start register vnfmadapter to Driver Manager", RegisterVnfm2DriverMgrThread.class); + + if(paramsMap == null || adapterInfo == null) { + LOG.error("parameter is null,please check!", RegisterVnfm2DriverMgrThread.class); + return; + } + + // catch Runtime Exception + try { + sendRequest(paramsMap, adapterInfo); + } catch(RuntimeException e) { + LOG.error(e.getMessage(), e); + } + + } + + private void sendRequest(Map paramsMap, JSONObject driverInfo) { + JSONObject resultObj = adapter2DriverMgr.registerDriver(paramsMap, driverInfo); + + if(Integer.valueOf(resultObj.get("retCode").toString()) == Constant.HTTP_CREATED) { + LOG.info("Vnfmadapter has now Successfully Registered to the Driver Manager!"); + } else { + LOG.error("Vnfmadapter failed to Register to the Driver Manager! Reason:" + + resultObj.get("reason").toString() + " retCode:" + resultObj.get("retCode").toString()); + + // if registration fails,wait one minute and try again + try { + synchronized(lockObject) { + lockObject.wait(Constant.REPEAT_REG_TIME); + } + } catch(InterruptedException e) { + LOG.error(e.getMessage(), e); + } + + sendRequest(this.paramsMap, this.adapterInfo); + } + + } + + } + + @Override + public void unregister() { + // unregister + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapterMgrService.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapterMgrService.java new file mode 100644 index 00000000..8991218a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapterMgrService.java @@ -0,0 +1,181 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.api.internalsvc.impl; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executors; + +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.vnfmadapter.service.adapter.impl.Driver2MSBManager; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IDriver2MSBManager; +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf.IVnfmAdapterMgrService; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.UrlConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 31, 2016 + */ +public class VnfmAdapterMgrService implements IVnfmAdapterMgrService { + + private static final Logger LOG = LoggerFactory.getLogger(VnfmAdapterMgrService.class); + + public static final String VNFMADAPTERINFO = "vnfmadapterinfo.json"; + + @Override + public void register() { + // set BUS URL and mothedtype + Map paramsMap = new HashMap<>(); + paramsMap.put("url", UrlConstant.REST_MSB_REGISTER); + paramsMap.put("methodType", Constant.POST); + + // get vim adapter info and raise registration + try { + String adapterInfo = readVnfmAdapterInfoFromJson(); + if(!"".equals(adapterInfo)) { + JSONObject adapterObject = JSONObject.fromObject(adapterInfo); + RegisterVnfmAdapterThread vnfmAdapterThread = new RegisterVnfmAdapterThread(paramsMap, adapterObject); + Executors.newSingleThreadExecutor().submit(vnfmAdapterThread); + } else { + LOG.error("VnfmAdapter info is null,please check!"); + } + + } catch(IOException e) { + LOG.error("Failed to read VnfmAdapter info! " + e.getMessage(), e); + } + + } + + /** + * Retrieve VIM driver information. + * @return + * @throws IOException + */ + public String readVnfmAdapterInfoFromJson() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "adapterInfo" + System.getProperty("file.separator") + + VNFMADAPTERINFO; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } finally { + if (ins != null) { + ins.close(); + } + if (bins != null) { + bins.close(); + } + } + + return fileContent; + } + + private static class RegisterVnfmAdapterThread implements Runnable { + + // Thread lock Object + private final Object lockObject = new Object(); + + private IDriver2MSBManager adapter2MSBMgr = new Driver2MSBManager(); + + // url and mothedtype + private Map paramsMap; + + // driver body + private JSONObject adapterInfo; + + public RegisterVnfmAdapterThread(Map paramsMap, JSONObject adapterInfo) { + this.paramsMap = paramsMap; + this.adapterInfo = adapterInfo; + } + + @Override + public void run() { + LOG.info("start register vnfmadapter", RegisterVnfmAdapterThread.class); + + if(paramsMap == null || adapterInfo == null) { + LOG.error("parameter is null,please check!", RegisterVnfmAdapterThread.class); + return; + } + + // catch Runtime Exception + try { + sendRequest(paramsMap, adapterInfo); + } catch(RuntimeException e) { + LOG.error(e.getMessage(), e); + } + + } + + private void sendRequest(Map paramsMap, JSONObject driverInfo) { + JSONObject resultObj = adapter2MSBMgr.registerDriver(paramsMap, driverInfo); + + if(Integer.valueOf(resultObj.get("retCode").toString()) == Constant.HTTP_CREATED) { + LOG.info("Vnfmadapter has now Successfully Registered to the Microservice BUS!"); + } else { + LOG.error("Vnfmadapter failed to Register to the Microservice BUS! Reason:" + + resultObj.get("reason").toString() + " retCode:" + resultObj.get("retCode").toString()); + + // if registration fails,wait one minute and try again + try { + synchronized(lockObject) { + lockObject.wait(Constant.REPEAT_REG_TIME); + } + } catch(InterruptedException e) { + LOG.error(e.getMessage(), e); + } + + sendRequest(this.paramsMap, this.adapterInfo); + } + + } + + } + + @Override + public void unregister() { + //unregister + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapter2DriverMgrService.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapter2DriverMgrService.java new file mode 100644 index 00000000..7aa7277d --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapter2DriverMgrService.java @@ -0,0 +1,42 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public interface IVnfmAdapter2DriverMgrService { + + /** + * VimAdapter register interface.
+ * + * @since NFVO 0.5 + */ + void register(); + + /** + * VimAdapter unregister interface.
+ * + * @since NFVO 0.5 + */ + void unregister(); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapterMgrService.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapterMgrService.java new file mode 100644 index 00000000..c25a2de1 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapterMgrService.java @@ -0,0 +1,39 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf; + +/** + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 31, 2016 + */ +public interface IVnfmAdapterMgrService { + + /** + * VimAdapter register interface. + */ + void register(); + + /** + * VimAdapter unregister interface. + */ + void unregister(); + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/Constant.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/Constant.java new file mode 100644 index 00000000..e20375f5 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/Constant.java @@ -0,0 +1,136 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.nfvo.vnfmadapter.service.constant; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Provide constant value + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Sep 3, 2016 + */ +public class Constant { + + public static final String POST = "post"; + + public static final String PUT = "put"; + + public static final String DELETE = "delete"; + + public static final String GET = "get"; + + public static final String ASYNCPOST = "asyncPost"; + + public static final String ASYNCGET = "asyncGet"; + + public static final String ASYNCPUT = "asyncPut"; + + public static final String ASYNCDELETE = "asyncDelete"; + + public static final String ENCODEING = "utf-8"; + + public static final String COOKIE = "Cookie"; + + public static final String ACCESSSESSION = "accessSession"; + + public static final String CONTENT_TYPE = "Content-Type"; + + public static final String APPLICATION = "application/json"; + + public static final String HEADER_SUBJECT_TOKEN = "X-Subject-Token"; + + public static final String HEADER_AUTH_TOKEN = "accessSession"; + + public static final String DOWNLOADCSAR_SUCCESS = "Success"; + + public static final int UNZIP_SUCCESS = 0; + + public static final int UNZIP_FAIL = -1; + + public static final String DOWNLOADCSAR_FAIL = "FAIL"; + + public static final int HTTP_OK = 200; + + public static final int HTTP_CREATED = 201; + + public static final int HTTP_ACCEPTED = 202; + + public static final int HTTP_NOCONTENT = 204; + + public static final int HTTP_BAD_REQUEST = 400; + + public static final int HTTP_UNAUTHORIZED = 401; + + public static final int HTTP_NOTFOUND = 404; + + public static final int HTTP_NOT_ACCEPTABLE = 406; + + public static final int HTTP_CONFLICT = 409; + + public static final int HTTP_INVALID_PARAMETERS = 415; + + public static final int HTTP_INNERERROR = 500; + + public static final List AUTHLIST = Collections.unmodifiableList(Arrays.asList(Constant.ANONYMOUS, Constant.CERTIFICATE)); + + public static final int INTERNAL_EXCEPTION = 600; + + public static final int REPEAT_REG_TIME = 60 * 1000; + + public static final int MIN_PWD_LENGTH = 6; + + public static final int MAX_PWD_LENGTH = 160; + + public static final int MIN_URL_LENGTH = 7; + + public static final int MAX_VNFM_NAME_LENGTH = 64; + + public static final int MIN_VNFM_NAME_LENGTH = 1; + + public static final int MAX_URL_LENGTH = 256; + + public static final int REST_SUCCESS = 1; + + public static final int DEFAULT_COLLECTION_SIZE = 10; + + public static final int REST_FAIL = -1; + + public static final String ROARAND = "?roarand=%s"; + + public static final String ANONYMOUS = "Anonymous"; + + public static final String CERTIFICATE = "Certificate"; + + public static final String RETCODE = "retCode"; + + public static final String STATUS = "status"; + + public static final String VNFPKGINFO="vnfpkginfo.json"; + + public static final int ERROR_STATUS_CODE = -1; + + public static final String COLON=":"; + + private Constant() { + //private constructor + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/ParamConstants.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/ParamConstants.java new file mode 100644 index 00000000..5d897871 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/ParamConstants.java @@ -0,0 +1,123 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.constant; + +/** + * + * @author + * + * @version NFVO 0.5 Sep 6, 2016 + */ +public class ParamConstants { + + public static final String GET_TOKENS_V1 = "{\"grantType\": \"password\", \"userName\": \"%s\",\"value\": \"%s\"}"; + + public static final String GET_TOKENS_V2 = + "{\"auth\":{\"identity\": {\"methods\": [\"password\"],\"password\": {\"user\": {\"name\": \"%s\",\"password\": \"%s\"}}}}}"; + + public static final String GET_IAM_TOKENS = + "{\"auth\": {\"identity\": {\"methods\": [\"password\"],\"password\": {\"user\": {\"name\": " + + "\"%s\",\"password\": \"%s\",\"domain\": {\"name\": \"%s\"}}}},\"scope\": {\"domain\": {\"name\": \"%s\"}}}}"; + + public static final String GET_TOKEN_SUC_RESP = + "{\"token\": {\"methods\": [\"password\"],\"expires_at\": \"\",\"user\": {\"id\": \"%s\"," + + "\"name\": \"%s\"},\"roa_rand\": \"%s\"}}"; + + public static final String GET_TOKEN_FAIL_RESP = "{\"Information\": \"%s\"}"; + + public static final String REST_3RD_CONNECTION = "/rest/plat/smapp/v1/oauth/token"; + + public static final String REST_3RD_DISCONNECT = "/rest/plat/smapp/v1/sessions?roarand=%s"; + + public static final String REST_3RD_HANDSHAKE = "/rest/plat/ssm/v1/sessions/verify"; + + public static final String IAM_AUTH = "/v3/auth/tokens"; + + public static final String CSM_AUTH_CONNECT = "/v2/auth/tokens"; + + public static final String CSM_AUTH_DISCONNECT = "/v2/auth/tokens/%s/%s"; + + public static final String CSM_AUTH_HANDSHAKE = "/v2/nfvo/shakehand?roattr=status"; + + public static final String VNFMMED = "/rest/vnfmmed/"; + + public static final String CONNECTMGR_CONNECT = "/connectmgr/v1/connect"; + + public static final String CONNECTMGR_DISCONNECT = "/connectmgr/v1/disconnect"; + + public static final String CONNECTMGR_HANDSHAKE = "/connectmgr/v1/handshake"; + + public static final String CREATE_VNF_PERF = "/staticsmgr/v1/vnfperformance"; + + public static final String VNFMGR_INSTANCE = "/vnfmgr/v1/instances"; + + + public static final String VNFD_FLAVOR = "/vnfdmgr/v1/flavor"; + + public static final String UPDATE_RESOURCE = "/rest/v1/resmanage/resuse/updateres"; + + public static final String VNF_QUERY = "/resmgr/v1/vnfs"; + + public static final String VMS_QUERY = "/resmgr/v1/vms"; + + public static final String VNFMGR_VNFKPI = "/staticsmgr/v1/vnfkpi"; + + public static final String RES_VNF = "/rest/v1/resmanage/vappvm"; + + public static final String NOTIFY_VNF_PERF = "/rest/v1/resmanage/vappvm"; + + public static final String PARAM_MODULE = "VnfmDriver"; + + public static final String GET_ALL_SOS = "/rest/sodriver/v1/sos"; + + public static final String OPERATION_LOG_PATH = "/rest/plat/audit/v1/logs"; + + public static final String SYSTEM_LOG_PATH = "/rest/plat/audit/v1/systemlogs"; + + public static final String SECURITY_LOG_PATH = "/rest/plat/audit/v1/seculogs"; + + public static final String GET_VNFM_VNF = "/rest/v1/resmanage/vapps?vnfmId=%s"; + + public static final String GET_RES_NET = "/rest/v1/resmanage/virtualnetworks?id=%s"; + + public static final String GET_JOB_STATUS = "/vnfmgr/v1/jobs/%s"; + + public static final String VNF_INSTANCE = "/v2/vapps/instances"; + + public static final String VNF_INSTANCE_DEL = "/v2/vapps/instances/%s"; + + public static final String VNF_INSTANCE_GET = "/v2/vapps/instances/%s"; + + public static final String VNF_SCALE = "/v2/vapps/instances/%s/scale"; + + public static final String VNF_GET_VMINFO = "/v2/vapps/instances/%s/vm"; + + + public static final String MSB_REGISTER_URL = "/openoapi/microservices/v1/services"; + + public static final String MSB_UNREGISTER_URL = "/openoapi/microservices/v1/services/hw-vnfm"; + + public static final String ESR_GET_VNFM_URL = "/openoapi/extsys/v1/vnfms/%s"; + + public static final String ESR_GET_VNFMS_URL = "/openoapi/extsys/v1/vnfms"; + + public static final String GRANT_RES_URL = "/openoapi/resmgr/v1/resource/grant"; + + private ParamConstants() { + // private contstructor + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/UrlConstant.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/UrlConstant.java new file mode 100644 index 00000000..10621271 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/UrlConstant.java @@ -0,0 +1,53 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.constant; + +/** + * URL constant + * + * @author + * @version NFVO 0.5 Sep 6, 2016 + */ +public class UrlConstant { + + public static final String REST_MSB_REGISTER = "/openoapi/microservices/v1/services"; + + public static final String REST_DRIVERMGR_REGISTER = "/openoapi/drivermgr/v1/drivers"; + + public static final String REST_CSARINFO_GET = "/openoapi/catalog/v1/csars/%s"; + + public static final String REST_VNFMINFO_GET = "/openoapi/extsys/v1/vnfms/%s"; + + public static final String URL_ALLCLOUD_GET = "/rest/vnfm/vnfmvim/v2/computeservice/getAllCloud"; + + public static final String URL_ALLCLOUD_NEW_GET = "/v2/vnfm/vims"; + + public static final String URL_VNFPACKAGE_POST = "/v2/vapps/templates"; + + public static final String URL_VNFDINFO_GET = "/v2/vapps/templates/%s"; + + public static final String URL_VNFDPLANINFO_GET = "/v2/vapps/templates/%s/plans"; + + public static final String PORT_COMMON = "31943"; + + public static final String PORT_UPLOADVNFPKG = "30001"; + + private UrlConstant() { + // Constructor + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfo.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfo.java new file mode 100644 index 00000000..5c59c013 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfo.java @@ -0,0 +1,137 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.nfvo.vnfmadapter.service.csm.api; + +import org.openo.nfvo.vnfmadapter.service.constant.Constant; + +/** + * Connection Information + * .
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class ConnectInfo { + + private String url; + + private String userName; + + private String userPwd; + + private String authenticateMode; + + /** + * + * Constructor
+ * + * @param url + * @since NFVO 0.5 + */ + public ConnectInfo(String url) { + this.url = url == null ? "" : url; + this.authenticateMode = Constant.ANONYMOUS; + } + + /** + * + * Constructor
+ * + * @param url + * @param userName + * @param userPwd + * @param authenticateMode + * @since NFVO 0.5 + */ + public ConnectInfo(String url, String userName, String userPwd, String authenticateMode) { + this.url = url == null ? "" : url; + this.userName = userName == null ? "" : userName; + this.userPwd = userPwd == null ? "" : userPwd; + this.authenticateMode = authenticateMode == null ? "" : authenticateMode; + } + + public String getUrl() { + return this.url; + } + + public void setUrl(String vnfUrl) { + this.url = vnfUrl; + } + + public String getUserName() { + return this.userName; + } + + public void setUserName(String vnfUserName) { + this.userName = vnfUserName; + } + + public String getUserPwd() { + return this.userPwd; + } + + public void setUserPwd(String vnfUserPwd) { + this.userPwd = vnfUserPwd; + } + + public String getAuthenticateMode() { + return this.authenticateMode; + } + + public void setAuthenticateMode(String vnfAuthenticateMode) { + this.authenticateMode = vnfAuthenticateMode; + } + + @Override + public String toString() { + return "ConnectInfo [AuthenticateMode: " + authenticateMode + ",url=" + url + ", userName=" + userName + ']'; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((url == null) ? 0 : url.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + + if(!(obj instanceof ConnectInfo)) { + return false; + } + + if(getClass() != obj.getClass()) { + return false; + } + ConnectInfo other = (ConnectInfo)obj; + if(url == null) { + if(other.url != null) { + return false; + } + } else if(!url.equals(other.url)) { + return false; + } + return true; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContext.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContext.java new file mode 100644 index 00000000..09f0d2cf --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContext.java @@ -0,0 +1,182 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.csm.connect; + +import net.sf.json.JSONObject; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; + +import java.io.*; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.*; + +/** + * SSL context + * .
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class AbstractSslContext { + private static final Logger LOG = LoggerFactory.getLogger(AbstractSslContext.class); + protected AbstractSslContext(){ + //constructor + } + + private static SSLContext getSSLContext() throws NoSuchAlgorithmException { + return SSLContext.getInstance("TLSv1.2"); + } + + protected static SSLContext getAnonymousSSLContext() throws GeneralSecurityException { + SSLContext sslContext = getSSLContext(); + sslContext.init(null, new TrustManager[] {new TrustAnyTrustManager()}, new SecureRandom()); + return sslContext; + } + protected static SSLContext getCertificateSSLContext() throws GeneralSecurityException { + SSLContext sslContext = getSSLContext(); + JSONObject sslConf = null; + try { + sslConf = readSSLConfToJson(); + } catch (Exception e) { + LOG.error("readSSLConfToJson error",e); + } + sslContext.init(createKeyManager(sslConf), createTrustManager(sslConf), new SecureRandom()); + return sslContext; + } + + protected static KeyManager[] createKeyManager(JSONObject sslConf) { + KeyManager[] kms = null; + try { + String CERT_STORE="etc/conf/server.p12"; + String CERT_STORE_PASSWORD="Changeme_123"; + String KEY_STORE_TYPE = "PKCS12"; + if(sslConf != null){ + CERT_STORE = sslConf.getString("keyStore"); + CERT_STORE_PASSWORD = sslConf.getString("keyStorePass"); + KEY_STORE_TYPE = sslConf.getString("keyStoreType"); + } + // load jks file + FileInputStream f_certStore=new FileInputStream(CERT_STORE); + KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE); + ks.load(f_certStore, CERT_STORE_PASSWORD.toCharArray()); + f_certStore.close(); + + // init and create + String alg= KeyManagerFactory.getDefaultAlgorithm(); + KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg); + kmFact.init(ks, CERT_STORE_PASSWORD.toCharArray()); + + kms = kmFact.getKeyManagers(); + } catch (Exception e) { + LOG.error("create KeyManager fail!",e); + } + return kms; + } + protected static TrustManager[] createTrustManager(JSONObject sslConf){ + TrustManager[] tms = null; + try { + + String TRUST_STORE="etc/conf/trust.jks"; + String TRUST_STORE_PASSWORD="Changeme_123"; + String TRUST_STORE_TYPE = "jks"; + if(sslConf != null){ + TRUST_STORE = sslConf.getString("trustStore"); + TRUST_STORE_PASSWORD = sslConf.getString("trustStorePass"); + TRUST_STORE_TYPE = sslConf.getString("trustStoreType"); + } + FileInputStream f_trustStore=new FileInputStream(TRUST_STORE); + KeyStore ks = KeyStore.getInstance(TRUST_STORE_TYPE); + ks.load(f_trustStore, TRUST_STORE_PASSWORD.toCharArray()); + f_trustStore.close(); + + String alg=TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmFact=TrustManagerFactory.getInstance(alg); + tmFact.init(ks); + tms=tmFact.getTrustManagers(); + + } catch (Exception e){ + LOG.error("create TrustManager fail!",e); + } + return tms; + } + + /**readSSLConfToJson + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static JSONObject readSSLConfToJson() throws IOException { + JSONObject sslJson= null; + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "conf" + System.getProperty("file.separator") + + "sslconf.json"; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + sslJson = JSONObject.fromObject(fileContent); + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } catch (Exception e){ + LOG.error("read sslconf file fail.please check if the 'sslconf.json' is exist."); + }finally { + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } + + return sslJson; + } + private static class TrustAnyTrustManager implements X509TrustManager { + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[] {}; + } + + @Override + public void checkServerTrusted(X509Certificate[] certs, String authType) { + //NOSONAR + } + + @Override + public void checkClientTrusted(X509Certificate[] certs, String authType) { + //NOSONAR + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/ConnectMgrVnfm.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/ConnectMgrVnfm.java new file mode 100644 index 00000000..8775a3d5 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/ConnectMgrVnfm.java @@ -0,0 +1,174 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.csm.connect; + +import java.io.IOException; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.HttpStatus; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.openo.nfvo.vnfmadapter.service.csm.api.ConnectInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * VNFM connection manager + * .
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class ConnectMgrVnfm { + + private static final Logger LOG = LoggerFactory.getLogger(ConnectMgrVnfm.class); + + private String accessSession; + + private String roaRand; + + public String getAccessSession() { + return accessSession; + } + + public void setAccessSession(String accessSession) { + this.accessSession = accessSession; + } + + public String getRoaRand() { + return roaRand; + } + + public void setRoaRand(String roaRand) { + this.roaRand = roaRand; + } + + + /** + * Make connection + *
+ * + * @param vnfmObj + * @return + * @since NFVO 0.5 + */ + public int connect(JSONObject vnfmObj,String authModel) { + LOG.info("function=connect, msg=enter connect function."); + + ConnectInfo info = new ConnectInfo(vnfmObj.getString("url"), vnfmObj.getString("userName"), + vnfmObj.getString("password"), authModel); + HttpMethod httpMethod = null; + int statusCode = Constant.INTERNAL_EXCEPTION; + + try { + httpMethod = new HttpRequests.Builder(info.getAuthenticateMode()) + .setUrl(info.getUrl(), ParamConstants.CSM_AUTH_CONNECT) + .setParams(String.format(ParamConstants.GET_TOKENS_V2, info.getUserName(), info.getUserPwd())) + .post().execute(); + statusCode = httpMethod.getStatusCode(); + + String result = httpMethod.getResponseBodyAsString(); + LOG.info("connect result:"+result); + if(statusCode == HttpStatus.SC_CREATED) { + JSONObject accessObj = JSONObject.fromObject(result); + JSONObject tokenObj = accessObj.getJSONObject("token"); + Header header = httpMethod.getResponseHeader("accessSession"); + setAccessSession(header.getValue()); + setRoaRand(tokenObj.getString("roa_rand")); + statusCode = HttpStatus.SC_OK; + } else { + LOG.error("connect fail, code:" + statusCode + " re:" + result); + } + + } catch(JSONException e) { + LOG.error("function=connect, msg=connect JSONException e={}.", e); + } catch(VnfmException e) { + LOG.error("function=connect, msg=connect VnfmException e={}.", e); + } catch(IOException e) { + LOG.error("function=connect, msg=connect IOException e={}.", e); + } finally { + clearCSMPwd(info); + if(httpMethod != null) { + httpMethod.releaseConnection(); + } + } + return statusCode; + + } + /** + * Make connection + *
+ * + * @param vnfmObj + * @return + * @since NFVO 0.5 + */ + public int connect(JSONObject vnfmObj) { + LOG.info("function=connect, msg=enter connect function."); + + ConnectInfo info = new ConnectInfo(vnfmObj.getString("url"), vnfmObj.getString("userName"), + vnfmObj.getString("password"), Constant.ANONYMOUS); + HttpMethod httpMethod = null; + int statusCode = Constant.INTERNAL_EXCEPTION; + + try { + httpMethod = new HttpRequests.Builder(info.getAuthenticateMode()) + .setUrl(info.getUrl(), ParamConstants.CSM_AUTH_CONNECT) + .setParams(String.format(ParamConstants.GET_TOKENS_V2, info.getUserName(), info.getUserPwd())) + .post().execute(); + statusCode = httpMethod.getStatusCode(); + + String result = httpMethod.getResponseBodyAsString(); + + if(statusCode == HttpStatus.SC_CREATED) { + JSONObject accessObj = JSONObject.fromObject(result); + JSONObject tokenObj = accessObj.getJSONObject("token"); + Header header = httpMethod.getResponseHeader("accessSession"); + setAccessSession(header.getValue()); + setRoaRand(tokenObj.getString("roa_rand")); + statusCode = HttpStatus.SC_OK; + } else { + LOG.error("connect fail, code:" + statusCode + " re:" + result); + } + + } catch(JSONException e) { + LOG.error("function=connect, msg=connect JSONException e={}.", e); + } catch(VnfmException e) { + LOG.error("function=connect, msg=connect VnfmException e={}.", e); + } catch(IOException e) { + LOG.error("function=connect, msg=connect IOException e={}.", e); + } finally { + clearCSMPwd(info); + if(httpMethod != null) { + httpMethod.releaseConnection(); + } + } + return statusCode; + + } + + private void clearCSMPwd(ConnectInfo connectInfo) { + if(null != connectInfo) { + connectInfo.setUserPwd(""); + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequests.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequests.java new file mode 100644 index 00000000..07f3f6b8 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequests.java @@ -0,0 +1,375 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.csm.connect; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import javax.net.ssl.SSLHandshakeException; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.EntityEnclosingMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.commons.lang.StringUtils; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; + +/** + * HTTP Request class.
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public final class HttpRequests { + + private static final Logger LOG = LoggerFactory.getLogger(HttpRequest.class); + + private static MultiThreadedHttpConnectionManager httpClientMgr; + + private static final int PORT = 31943; + + private HttpRequests() { + // constructor + } + + static { + httpClientMgr = new MultiThreadedHttpConnectionManager(); + httpClientMgr.getParams().setStaleCheckingEnabled(true); + httpClientMgr.getParams().setMaxTotalConnections(20); + httpClientMgr.getParams().setDefaultMaxConnectionsPerHost(100); + } + + /** + * Request builder.
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ + public static class Builder { + + private final List
headers = new ArrayList<>(10); + + private String paramsJson; + + private HttpClient client; + + private HttpMethod httpMethod; + + private String encoding; + + private String url; + + private String authenticateMode; + + /** + * + * Constructor
+ * + * @param authenticateMode + * @since NFVO 0.5 + */ + public Builder(String authenticateMode) { + this.authenticateMode = authenticateMode; + client = new HttpClient(httpClientMgr); + client.getHttpConnectionManager().getParams().setConnectionTimeout(30000); + client.getHttpConnectionManager().getParams().setSoTimeout(30000); + encoding = Constant.ENCODEING; + } + + /** + * Add header + *
+ * + * @param name + * @param value + * @return + * @since NFVO 0.5 + */ + public Builder addHeader(String name, String value) { + headers.add(new Header(name, value)); + return this; + } + + /** + * Add headers + *
+ * + * @param header + * @param headers + * @return + * @since NFVO 0.5 + */ + public Builder addHeaders(Header header, Header... headers) { + if(header != null) { + this.headers.add(header); + } + if(headers != null && headers.length > 0) { + for(Header h : headers) { + this.headers.add(h); + } + } + return this; + } + + /** + * Add headers + *
+ * + * @param headers + * @return + * @since NFVO 0.5 + */ + public Builder addHeaders(List
headers) { + if(headers != null && !headers.isEmpty()) { + this.headers.addAll(headers); + } + return this; + } + + /** + * Update URL + *
+ * + * @param url + * @param path + * @return + * @throws VnfmException + * @since NFVO 0.5 + */ + public Builder setUrl(String url, String path) throws VnfmException { + if(StringUtils.isEmpty(url)) { + throw new VnfmException("com.huawei.nfvo.vcmmadapter.fusionsphere.check.httprequest.url"); + } + + this.url = url + path; + + LOG.info("setUrl: url =" + url); + + Protocol.registerProtocol("https", + new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT)); + + return this; + } + + /** + * Update URL + *
+ * + * @param url + * @param path + * @param defPort + * @return + * @throws VnfmException + * @since NFVO 0.5 + */ + public Builder setUrl(String url, String path, int defPort) throws VnfmException { + if(StringUtils.isEmpty(url)) { + throw new VnfmException("com.huawei.nfvo.vcmmadapter.fusionsphere.check.httprequest.url"); + } + + this.url = url + path; + + LOG.info("setUrl: url =" + url); + + Protocol.registerProtocol("https", + new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), defPort)); + + return this; + } + + /** + * HTTP POST + *
+ * + * @return + * @since NFVO 0.5 + */ + public Builder post() { + this.httpMethod = new PostMethod(url); + return this; + } + + /** + * HTTP GET + *
+ * + * @return + * @since NFVO 0.5 + */ + public Builder get() { + this.httpMethod = new GetMethod(url); + return this; + } + + /** + * HTTP PUT + *
+ * + * @return + * @since NFVO 0.5 + */ + public Builder put() { + this.httpMethod = new PutMethod(url); + return this; + } + + /** + * HTTP DELETE + *
+ * + * @return + * @since NFVO 0.5 + */ + public Builder delete() { + this.httpMethod = new DeleteMethod(url); + return this; + } + + /** + * Update Params + *
+ * + * @param json + * @return + * @since NFVO 0.5 + */ + public Builder setParams(String json) { + this.paramsJson = json; + return this; + } + + /** + * Set the encoding + *
+ * + * @param encode + * @return + * @since NFVO 0.5 + */ + public Builder setEncoding(String encode) { + this.encoding = encode; + return this; + } + + /** + * Make HTTP request + *
+ * + * @return + * @since NFVO 0.5 + */ + public String request() { + String result = null; + try { + result = executeMethod().getResponseBodyAsString(); + } catch(SSLHandshakeException e) { + LOG.error(String.format("function=request, msg=http request url: %s, SSLHandshake Fail : ", url), e); + try { + LOG.error("function=request, msg=SSLHandshake Fail, start refresh certificate ..."); + SslProtocolSocketFactory socketFactory = SslProtocolSocketFactory.getInstance(); + socketFactory.refresh(authenticateMode); + Protocol.registerProtocol("https", + new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT)); + LOG.error("function=request, msg=SSLHandshake Fail, certificate refresh successful ."); + + result = executeMethod().getResponseBodyAsString(); + } catch(IOException ioe) { + LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), ioe); + } catch(VnfmException ose) { + LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), ose); + } + } catch(IOException | VnfmException e) { + LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), e); + } finally { + httpMethod.releaseConnection(); + } + return result; + } + + /** + * Execute the HTTP method + *
+ * + * @return + * @throws VnfmException + * @throws IOException + * @since NFVO 0.5 + */ + public HttpMethod execute() throws VnfmException, IOException { + try { + executeMethod(); + } catch(SSLHandshakeException e) { + LOG.error(String.format("function=execute, msg=http request url: %s, SSLHandshake Fail : ", url), e); + LOG.error("function=execute, SSLHandshake Fail, start refresh certificate ..."); + SslProtocolSocketFactory socketFactory = SslProtocolSocketFactory.getInstance(); + socketFactory.refresh(authenticateMode); + Protocol.registerProtocol("https", + new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT)); + LOG.error("function=execute, SSLHandshake Fail, certificate refresh successful ."); + + executeMethod(); + } + return httpMethod; + } + + private HttpMethod executeMethod() throws VnfmException, IOException { + if(httpMethod == null) { + httpMethod = new GetMethod(url); + } + + handleParams(); + + client.executeMethod(httpMethod); + + return httpMethod; + } + + private void handleParams() throws UnsupportedEncodingException { + if(paramsJson != null && !paramsJson.isEmpty()) { + StringRequestEntity stringRequestEntity = + new StringRequestEntity(paramsJson, "application/json", encoding); + String contentLengthString = String.valueOf(stringRequestEntity.getContentLength()); + + if(httpMethod instanceof PostMethod || httpMethod instanceof PutMethod) { + ((EntityEnclosingMethod)httpMethod).setRequestEntity(stringRequestEntity); + ((EntityEnclosingMethod)httpMethod).addRequestHeader("Content-Length", contentLengthString); + } else { + httpMethod.setQueryString(paramsJson); + } + addHeader("Content-Type", String.format("application/json;charset=%s", encoding)); + } + + for(Header header : headers) { + httpMethod.addRequestHeader(header); + } + } + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocket.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocket.java new file mode 100644 index 00000000..09ec841a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocket.java @@ -0,0 +1,89 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.csm.connect; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.security.GeneralSecurityException; + +import javax.net.ssl.SSLSocketFactory; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; +import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Create socket with Anonymous + */ +public class SslAnonymousSocket extends AbstractSslContext implements SecureProtocolSocketFactory { + + private static final Logger LOG = LoggerFactory.getLogger(SslAnonymousSocket.class); + + private SSLSocketFactory sslSocketFactory = null; + + /** + * Initialize + *
+ * + * @throws VnfmException + * @since NFVO 0.5 + */ + public void init() throws VnfmException { + try { + sslSocketFactory = getAnonymousSSLContext().getSocketFactory(); + } catch(GeneralSecurityException e) { + LOG.error("function=init, get Anonymous SSLContext exception, exceptioninfo", e); + throw (VnfmException)new VnfmException().initCause(e); + } + } + + @Override + public Socket createSocket(String host, int port) throws IOException { + return sslSocketFactory.createSocket(host, port); + } + + @Override + public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException { + return sslSocketFactory.createSocket(host, port, clientHost, clientPort); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, + HttpConnectionParams params) throws IOException, ConnectTimeoutException { + if(params == null) { + throw new IOException("Illegal socket parameters!"); + } else { + int timeout = params.getConnectionTimeout(); + + if(timeout == 0) { + return createSocket(host, port, localAddress, localPort); + } else { + return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout); + } + } + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + return sslSocketFactory.createSocket(socket, host, port, autoClose); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocket.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocket.java new file mode 100644 index 00000000..9eca6e28 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocket.java @@ -0,0 +1,87 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.nfvo.vnfmadapter.service.csm.connect; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; +import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLSocketFactory; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.security.GeneralSecurityException; + +/** + * Created by QuanZhong on 2017/3/6. + */ +public class SslCertificateSocket extends AbstractSslContext implements SecureProtocolSocketFactory { + + private static final Logger LOG = LoggerFactory.getLogger(SslAnonymousSocket.class); + + private SSLSocketFactory sslSocketFactory = null; + + /** + * Initialize + *
+ * + * @throws VnfmException + * @since NFVO 0.5 + */ + public void init() throws VnfmException { + try { + sslSocketFactory = getCertificateSSLContext().getSocketFactory(); + } catch(GeneralSecurityException e) { + LOG.error("function=init, get Anonymous SSLContext exception, exceptioninfo", e); + throw (VnfmException)new VnfmException().initCause(e); + } + } + + @Override + public Socket createSocket(String host, int port) throws IOException { + return sslSocketFactory.createSocket(host, port); + } + + @Override + public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException { + return sslSocketFactory.createSocket(host, port, clientHost, clientPort); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, + HttpConnectionParams params) throws IOException, ConnectTimeoutException { + if(params == null) { + throw new IOException("Illegal socket parameters!"); + } else { + int timeout = params.getConnectionTimeout(); + + if(timeout == 0) { + return createSocket(host, port, localAddress, localPort); + } else { + return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout); + } + } + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + return sslSocketFactory.createSocket(socket, host, port, autoClose); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactory.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactory.java new file mode 100644 index 00000000..d14d939a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactory.java @@ -0,0 +1,101 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.csm.connect; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SSL Socket Factory. + * .
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class SslProtocolSocketFactory { + + private static final Logger LOG = LoggerFactory.getLogger(SslProtocolSocketFactory.class); + + private static final Map SOCKMAP = + new ConcurrentHashMap(2); + + private static SslProtocolSocketFactory singleinstance = null; + + /** + * Generate instance of SslProtocolSocketFactory + *
+ * + * @return + * @since NFVO 0.5 + */ + public static synchronized SslProtocolSocketFactory getInstance() { + if(singleinstance == null) { + singleinstance = new SslProtocolSocketFactory(); + } + return singleinstance; + } + + /** + * + *
+ * + * @param authenticateMode + * @return + * @throws VnfmException + * @since NFVO 0.5 + */ + public synchronized ProtocolSocketFactory get(String authenticateMode) throws VnfmException { + if(SOCKMAP.get(authenticateMode) == null) { + if(Constant.ANONYMOUS.equals(authenticateMode)) { + SslAnonymousSocket anonymous = new SslAnonymousSocket(); + anonymous.init(); + SOCKMAP.put(Constant.ANONYMOUS, anonymous); + }else if (Constant.CERTIFICATE.equals(authenticateMode)){ + SslCertificateSocket certificateSocket = new SslCertificateSocket(); + certificateSocket.init(); + SOCKMAP.put(Constant.CERTIFICATE, certificateSocket); + } else { + LOG.error("funtion=get, msg=ProtocolSocketFactory Unknown AuthenticateMode={}", authenticateMode); + throw new VnfmException(String.format("Illegal Auth mode", authenticateMode)); + } + } + + return SOCKMAP.get(authenticateMode); + } + + /** + * Refresh local socket map + *
+ * + * @param autherMode + * @throws VnfmException + * @since NFVO 0.5 + */ + public synchronized void refresh(String autherMode) throws VnfmException { + if(Constant.ANONYMOUS.equals(autherMode)) { + SslAnonymousSocket anonymous = new SslAnonymousSocket(); + anonymous.init(); + SOCKMAP.put(Constant.ANONYMOUS, anonymous); + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceConnectMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceConnectMgr.java new file mode 100644 index 00000000..f2a2c5e5 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceConnectMgr.java @@ -0,0 +1,45 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.csm.inf; + +import org.openo.nfvo.vnfmadapter.common.VnfmException; + +import net.sf.json.JSONObject; +/** + * Provide interface for connecting + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +@FunctionalInterface +public interface InterfaceConnectMgr { + + /** + * Provide interface for connecting + *
+ * + * @param obj + * @return + * @throws VnfmException + * @since NFVO 0.5 + */ + int connect(JSONObject obj) throws VnfmException; + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceVnfMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceVnfMgr.java new file mode 100644 index 00000000..8a1cb0b3 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceVnfMgr.java @@ -0,0 +1,83 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.csm.inf; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces for instantiate or terminate VNF. + *
+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public interface InterfaceVnfMgr { + + /** + * Provide interface for scale VNF. + * @param vnfObject + * @param vnfmObject + * @param vnfmId + * @param vnfInstanceId + * @return + */ + public JSONObject scaleVnf(JSONObject vnfObject, JSONObject vnfmObject, String vnfmId, String vnfInstanceId); + /** + * Provide interface for instantiate VNF. + *
+ * + * @param subJsonObject + * @param vnfmObjcet + * @return + * @since NFVO 0.5 + */ + JSONObject createVnf(JSONObject subJsonObject, JSONObject vnfmObjcet); + + /** + * Provide interface for terminate VNF + *
+ * + * @param vnfmObject + * @param vnfId + * @param vnfObject + * @return + * @since NFVO 0.5 + */ + JSONObject removeVnf(JSONObject vnfmObject, String vnfId, JSONObject vnfObject); + + /** + * Provide interface for get VNF info + *
+ * + * @param vnfmObject + * @param vnfId + * @return + * @since NFVO 0.5 + */ + JSONObject getVnf(JSONObject vnfmObject, String vnfId); + + /** + * Retrieve job + *
+ * + * @param vnfmObject + * @param jobId + * @return + * @since NFVO 0.5 + */ + JSONObject getJob(JSONObject vnfmObject, String jobId); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfm.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfm.java new file mode 100644 index 00000000..dea8c0bf --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfm.java @@ -0,0 +1,223 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.csm.vnf; + +import net.sf.json.JSONArray; +import org.openo.nfvo.vnfmadapter.common.ResultRequestUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.openo.nfvo.vnfmadapter.service.csm.inf.InterfaceVnfMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +import javax.print.attribute.standard.ReferenceUriSchemesSupported; + +/** + * create or terminate VNF to M + *
+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class VnfMgrVnfm implements InterfaceVnfMgr { + + private static final Logger LOG = LoggerFactory.getLogger(VnfMgrVnfm.class); + + @Override + public JSONObject scaleVnf(JSONObject vnfObject, JSONObject vnfmObject, String vnfmId, String vnfInstanceId) { + LOG.warn("function=scaleVnf, msg=enter to scale a vnf"); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + String path = String.format(ParamConstants.VNF_SCALE, vnfInstanceId); + + int scaleType = getScaleType(vnfObject.getString("type")); + //build request json object + JSONObject paramJson = new JSONObject(); + JSONObject scaleInfo = new JSONObject(); + JSONArray vduList = new JSONArray(); + JSONObject vdu = new JSONObject(); + vdu.put("vdu_type",this.getVduType(vnfmObject,vnfInstanceId));//TODO:set vdu_type + vdu.put("h_steps",vnfObject.get("numberOfSteps")); + vduList.add(vdu); + scaleInfo.put("vnf_id",vnfInstanceId); + scaleInfo.put("scale_type",0); + scaleInfo.put("scale_action",scaleType); + scaleInfo.put("vdu_list",vduList); + if(scaleType == 0){//scale_in + JSONArray vmList = new JSONArray(); + try { + JSONObject additionalParam = vnfObject.getJSONObject("additionalParam"); + vmList = additionalParam.getJSONArray("vm_list"); + }catch (JSONException e) { + LOG.error("the param 'additionalParam' or 'vm_list' not found,please check it",e); + } + scaleInfo.put("vm_list",vmList); + } + paramJson.put("scale_info",scaleInfo); + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, path, Constant.PUT, paramJson.toString(),Constant.CERTIFICATE); + LOG.info("SCALE execute result:"+queryResult.toString()); + try { + int statusCode = queryResult.getInt(Constant.RETCODE); + + if(statusCode == Constant.HTTP_CREATED || statusCode == Constant.HTTP_OK) { + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + JSONObject resultObj = new JSONObject(); + resultObj.put("jobId", vnfInstanceId + "_" + Constant.PUT); + restJson.put("data", resultObj); + } else { + LOG.error("function=scaleVnf, msg=send create vnf msg to csm get wrong status: " + statusCode); + } + + } catch(JSONException e) { + LOG.error("function=scaleVnf, msg=parse scale vnf return data occoured JSONException, e={}.", e); + } + + return restJson; + } + + + private String getVduType(JSONObject vnfmObject, String vnfInstanceId){ + String vduType = ""; + try { + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, String.format(ParamConstants.VNF_GET_VMINFO, vnfInstanceId), Constant.GET, null,Constant.CERTIFICATE); + LOG.info("getVduType result="+queryResult); + vduType = queryResult.getJSONObject("data").getJSONArray("vms").getJSONObject(0).getString("vdu_type"); + } catch (Exception e) { + LOG.error("get vdu_type failed.",e); + } + LOG.info("vdu_type="+vduType); + return vduType; + } + private int getScaleType(String type){ + if("SCALE_OUT".equalsIgnoreCase(type)){ + return 1; + }else if("SCALE_IN".equalsIgnoreCase(type)){ + return 0; + } + return -1; + } + @Override + public JSONObject createVnf(JSONObject subJsonObject, JSONObject vnfmObject) { + LOG.info("function=createVnf, msg=enter to create a vnf"); + LOG.info("createVnf csm request body :"+subJsonObject); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + String path = ParamConstants.VNF_INSTANCE + Constant.ROARAND; + + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, path, Constant.POST, subJsonObject.toString(),Constant.CERTIFICATE); + LOG.info("createVnf csm response content:"+queryResult); + try { + int statusCode = queryResult.getInt(Constant.RETCODE); + + if(statusCode == Constant.HTTP_CREATED) { + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + JSONObject appInfo = JSONObject.fromObject(queryResult.getString("data")).getJSONObject("app_info"); + JSONObject resultObj = new JSONObject(); + resultObj.put("vnfInstanceId", appInfo.getString("id")); + resultObj.put("jobId", appInfo.getString("id") + "_" + Constant.POST); + restJson.put("data", resultObj); + } else { + LOG.error("function=createVnf, msg=send create vnf msg to csm get wrong status: " + statusCode); + } + + } catch(JSONException e) { + LOG.error("function=createVnf, msg=parse create vnf return data occoured JSONException, e={}.", e); + } + + return restJson; + } + + @Override + public JSONObject removeVnf(JSONObject vnfmObject, String vnfId, JSONObject vnfObject) { + LOG.warn("function=removeVnf, msg=enter to remove a vnf: {}", vnfId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, + String.format(ParamConstants.VNF_INSTANCE_DEL, vnfId) + Constant.ROARAND, Constant.DELETE, null,Constant.CERTIFICATE); + + int statusCode = queryResult.getInt(Constant.RETCODE); + + if(statusCode == Constant.HTTP_NOCONTENT) { + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + JSONObject resultObj = new JSONObject(); + resultObj.put("jobId", vnfId + "_" + Constant.DELETE); + restJson.put("data", resultObj); + } else { + LOG.error("function=removeVnf, msg=send remove vnf msg to csm get wrong status: {}", statusCode); + } + + return restJson; + } + + @Override + public JSONObject getVnf(JSONObject vnfmObject, String vnfId) { + LOG.warn("function=getVnf, msg=enter to get a vnf: {}", vnfId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, + String.format(ParamConstants.VNF_INSTANCE_GET, vnfId) + Constant.ROARAND + "&type=status", Constant.GET, + null,Constant.CERTIFICATE); + + int statusCode = queryResult.getInt("retCode"); + + if(statusCode == Constant.HTTP_OK || statusCode == Constant.HTTP_CREATED) { + if(null == (queryResult.get("data"))) { + LOG.warn("function=getVnf, msg=query is null {}", queryResult.get("data")); + return restJson; + } + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + restJson.put("data", JSONObject.fromObject(queryResult.getString("data")).getJSONArray("basic")); + } else { + LOG.error("function=getVnf, msg=send get vnf msg to csm get wrong status: {}", statusCode); + } + + return restJson; + } + + @Override + public JSONObject getJob(JSONObject vnfmObject, String jobId) { + LOG.warn("function=getJob, msg=enter to get a job: {}", jobId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + + String vnfId = jobId.split("_")[0]; + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, + String.format(ParamConstants.VNF_INSTANCE_GET, vnfId) + Constant.ROARAND + "&type=status", Constant.GET, + null,Constant.CERTIFICATE); + + int statusCode = queryResult.getInt("retCode"); + + if(statusCode == Constant.HTTP_OK || statusCode == Constant.HTTP_CREATED) { + + if((queryResult.get("data")) == null) { + LOG.warn("function=getJob, msg=query is null {}", queryResult.get("data")); + return restJson; + } + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + restJson.put("data", JSONObject.fromObject(queryResult.getString("data")).getJSONArray("basic")); + } else { + LOG.error("function=getJob, msg=send get vnf msg to csm get wrong status: {}", statusCode); + } + + return restJson; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImpl.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImpl.java new file mode 100644 index 00000000..c104bd16 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImpl.java @@ -0,0 +1,62 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.dao.impl; + +import java.util.List; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.service.dao.inf.AbstractDao; +import org.openo.nfvo.vnfmadapter.service.dao.inf.VnfmDao; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; +import org.openo.nfvo.vnfmadapter.service.mapper.VnfmMapper; + +/** + * VNFM DAO + * .
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class VnfmDaoImpl extends AbstractDao implements VnfmDao { + + @Override + public int insertVnfm(Vnfm vnfm) throws ServiceException { + return getMapperManager(VnfmMapper.class).insertVnfm(vnfm); + } + + @Override + public int deleteVnfm(String vnfmDn) throws ServiceException { + return getMapperManager(VnfmMapper.class).deleteVnfm(vnfmDn); + } + + @Override + public int updateVnfm(Vnfm vnfm) throws ServiceException { + return getMapperManager(VnfmMapper.class).updateVnfm(vnfm); + } + + @Override + public List indexVnfms(int pageSize, int pageNo) throws ServiceException { + VnfmMapper vnfmMapper = getMapperManager(VnfmMapper.class); + int offset = (pageNo - 1) * pageSize; + return vnfmMapper.indexVnfms(offset, pageSize); + } + + @Override + public Vnfm getVnfmById(String id) { + return getMapperManager(VnfmMapper.class).getVnfmById(id); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/AbstractDao.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/AbstractDao.java new file mode 100644 index 00000000..592c3d50 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/AbstractDao.java @@ -0,0 +1,50 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.dao.inf; + +import org.apache.ibatis.session.SqlSession; + +/** + * database abstract class to get the MapperManager. + */ +public class AbstractDao { + + private SqlSession session; + + protected AbstractDao() { + //Constructor + } + + public SqlSession getSession() { + return session; + } + + public void setSession(SqlSession session) { + this.session = session; + } + + /** + * get Mybatis Mapper. + * + * @param type : The class of the instance + * @param : The type of the instance + * @return Mapper : The instance + */ + public T getMapperManager(Class type) { + return (T)getSession().getMapper(type); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/VnfmDao.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/VnfmDao.java new file mode 100644 index 00000000..8fc4431c --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/VnfmDao.java @@ -0,0 +1,87 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.dao.inf; + +import java.util.List; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; + +/** + * VNFM DAO + * .
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public interface VnfmDao { + + /** + * Add VNFM + *
+ * + * @param vnfm + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + int insertVnfm(Vnfm vnfm) throws ServiceException; + + /** + * Delete VNFM + *
+ * + * @param vnfmDn + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + int deleteVnfm(String vnfmDn) throws ServiceException; + + /** + * Update VNFM + *
+ * + * @param vnfm + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + int updateVnfm(Vnfm vnfm) throws ServiceException; + + /** + * Index VNFM + *
+ * + * @param pageSize + * @param pageNo + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + List indexVnfms(int pageSize, int pageNo) throws ServiceException; + + /** + * Get VNFM by id. + *
+ * + * @param id + * @return + * @since NFVO 0.5 + */ + Vnfm getVnfmById(String id); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/entity/Vnfm.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/entity/Vnfm.java new file mode 100644 index 00000000..dec1724c --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/entity/Vnfm.java @@ -0,0 +1,110 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.entity; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * Provide database class + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Sep 3, 2016 + */ +public class Vnfm { + + private String id; + + private String version; + + private String vnfdId; + + private String vnfPackageId; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getVnfdId() { + return vnfdId; + } + + public void setVnfdId(String vnfdId) { + this.vnfdId = vnfdId; + } + + public String getVnfPackageId() { + return vnfPackageId; + } + + public void setVnfPackageId(String vnfPackageId) { + this.vnfPackageId = vnfPackageId; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(!(obj instanceof Vnfm)) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } + Vnfm other = (Vnfm)obj; + if(id == null) { + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } + return true; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/mapper/VnfmMapper.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/mapper/VnfmMapper.java new file mode 100644 index 00000000..63317626 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/mapper/VnfmMapper.java @@ -0,0 +1,91 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; + +/** + * VNFM mapper.
+ * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public interface VnfmMapper { + + /** + * Add VNFM + *
+ * + * @param vnfm Vnfm + * @return + * @since NFVO 0.5 + */ + int insertVnfm(Vnfm vnfm); + + /** + * Update VNFM + *
+ * + * @param vnfm Vnfm + * @return + * @since NFVO 0.5 + */ + int updateVnfm(Vnfm vnfm); + + /** + * Delete VNFM + *
+ * + * @param vnfmDn + * @return + * @since NFVO 0.5 + */ + int deleteVnfm(String vnfmDn); + + /** + * Index VNFM + *
+ * + * @param offset + * @param pageSize + * @return + * @since NFVO 0.5 + */ + List indexVnfms(@Param("offset") int offset, @Param("pageSize") int pageSize); + + /** + * Get VNFM counts. + *
+ * + * @return + * @since NFVO 0.5 + */ + int getCountVnfms(); + + /** + * Get VNFM by id + *
+ * + * @param id + * @return + * @since NFVO 0.5 + */ + Vnfm getVnfmById(String id); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgr.java new file mode 100644 index 00000000..1793755d --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgr.java @@ -0,0 +1,74 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.process; + +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Provide function for authInfo. + *
+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class AuthMgr { + + private static final Logger LOG = LoggerFactory.getLogger(AuthMgr.class); + + /** + * Provide function for add authInfo. + *
+ * + * @param params + * @return + * @since NFVO 0.5 + */ + public JSONObject authToken(JSONObject params) { + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + String userName = params.getString("userName"); + + restJson = getStatusResult(userName); + } catch(JSONException e) { + LOG.error("function=login, msg=Params error occurs, e={}.", e); + restJson.put("data", "JSONException"); + return restJson; + } + return restJson; + } + + private JSONObject getStatusResult(String userName) { + JSONObject restJson = new JSONObject(); + JSONObject authResult = new JSONObject(); + JSONObject addInfo = new JSONObject(); + authResult.put("accessSession", "1234"); + authResult.put("roaRand", "RoaRand"); + authResult.put("expires", 1800); + addInfo.put("expires", 10); + addInfo.put("passwdStatus", "expiring"); + authResult.put("additionalInfo", addInfo); + restJson.put("retCode", Constant.REST_SUCCESS); + restJson.put("data", authResult); + return restJson; + } +} \ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgr.java new file mode 100644 index 00000000..7da24c0e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgr.java @@ -0,0 +1,83 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.process; + +import java.util.HashMap; +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.RegisterConfigInfo; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide function for register or unregister service to Bus. + *
+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class RegisterMgr { + + private static final Logger LOG = LoggerFactory.getLogger(RegisterMgr.class); + + /** + * Register service to the Bus + *
+ * + * @since NFVO 0.5 + */ + public void register() { + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(ParamConstants.MSB_REGISTER_URL, + VnfmRestfulUtil.TYPE_POST, getRegsiterBody()); + + LOG.error("funtion=register, status={}", rsp.getStatus()); + } + + /** + * UnRegister service to the Bus + *
+ * + * @since NFVO 0.5 + */ + public void unRegister() { + Map paramsMap = new HashMap<>(); + paramsMap.put("url", ParamConstants.MSB_UNREGISTER_URL); + paramsMap.put("methodType", VnfmRestfulUtil.TYPE_DEL); + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(ParamConstants.MSB_UNREGISTER_URL, + VnfmRestfulUtil.TYPE_DEL, null); + + LOG.error("funtion=register, status={}", rsp.getStatus()); + } + + private String getRegsiterBody() { + JSONObject body = new JSONObject(); + body.put("serviceName", RegisterConfigInfo.getInstance().getServiceName()); + body.put("version", RegisterConfigInfo.getInstance().getVersion()); + body.put("url", RegisterConfigInfo.getInstance().getUrl()); + body.put("protocol", RegisterConfigInfo.getInstance().getProtocol()); + body.put("port", RegisterConfigInfo.getInstance().getPort()); + body.put("ip", RegisterConfigInfo.getInstance().getIp()); + body.put("ttl", RegisterConfigInfo.getInstance().getTtl()); + + return body.toString(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgr.java new file mode 100644 index 00000000..816af06f --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgr.java @@ -0,0 +1,296 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.process; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.common.VnfmUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.impl.AdapterResourceManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.csm.vnf.VnfMgrVnfm; +import org.openo.nfvo.vnfmadapter.service.dao.inf.VnfmDao; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Provide function for instantiate or terminate VNF + *
+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class VnfMgr { + + private static final Logger LOG = LoggerFactory.getLogger(VnfMgr.class); + + private VnfmDao vnfmDao; + + public void setVnfmDao(VnfmDao vnfmDao) { + this.vnfmDao = vnfmDao; + } + + + /** + * Scale vnf + * @param vnfObject + * { + * "vnfInstanceId":"5", + * "type":"SCALE_OUT", + * "aspectId":"101", + * "numberOfSteps":"1", + * "additionalParam":{} + * } + * @param vnfmId + * @param vnfInstanceId + * @return + */ + public JSONObject scaleVNF(JSONObject vnfObject, String vnfmId, String vnfInstanceId) { + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + + if(vnfObject.isNullObject() || vnfObject.isEmpty()) { + return restJson; + } + + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + LOG.info("vnfm info:"+vnfmObjcet); + if(vnfmObjcet.isNullObject()) { + LOG.error("function=scaleVNF,can't find vnfm from db by vnfmId="+vnfmId); + return restJson; + } + restJson = (new VnfMgrVnfm()).scaleVnf(vnfObject, vnfmObjcet, vnfmId, vnfInstanceId); + } catch(JSONException e) { + LOG.error("function=scaleVNF, msg=JSONException occurs, e={}.", e); + } + + return restJson; + } + + /** + * Provide function for instantiate VNF + *
+ * + * @param vnfObject + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject addVnf(JSONObject vnfObject, String vnfmId) { + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + + if(vnfObject.isNullObject() || vnfObject.isEmpty()) { + return restJson; + } + + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + + if(vnfmObjcet.isNullObject()) { + return restJson; + } + + Map conMap = new ConcurrentHashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + conMap.put("csarid", vnfObject.getString("vnfPackageId")); + conMap.put("vnfmid", vnfmId); + conMap.put("vnfDescriptorId",vnfObject.getString("vnfDescriptorId")); + + JSONObject resObjcet = (new AdapterResourceManager()).uploadVNFPackage(null, conMap); + + if(resObjcet.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + return restJson; + } + + JSONObject csmBody = transferVnfBody(vnfObject, resObjcet, vnfmId); + restJson = (new VnfMgrVnfm()).createVnf(csmBody, vnfmObjcet); + saveVnfInfo(restJson, resObjcet); + } catch(JSONException e) { + LOG.error("function=addVnf, msg=JSONException occurs, e={}.", e); + } + + return restJson; + } + + /** + * Provide function for terminate VNF + *
+ * + * @param vnfId + * @param vnfmId + * @param vnfObject + * @return + * @since NFVO 0.5 + */ + public JSONObject deleteVnf(String vnfId, String vnfmId, JSONObject vnfObject) { + LOG.warn("function=deleteVnf ,msg=enter to delete a vnf, vnfId:{}, vnfmId:{}", vnfId, vnfmId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + if(vnfmObjcet.isNullObject()) { + LOG.error("function=deleteVnf, msg=vnfm not exists, vnfmId: {}", vnfmId); + return restJson; + } + + restJson = (new VnfMgrVnfm()).removeVnf(vnfmObjcet, vnfId, vnfObject); + } catch(JSONException e) { + LOG.error("function=deleteVnf, msg=JSONException occurs, e={}.", e); + } + return restJson; + } + + /** + * Provide function for get VNF + *
+ * + * @param vnfId + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject getVnf(String vnfId, String vnfmId) { + LOG.warn("function=getVnf ,msg=enter to get a vnf, vnfId:{}, vnfmId:{}", vnfId, vnfmId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + if(vnfmObjcet.isNullObject()) { + LOG.error("function=getVnf, msg=vnfm not exists, vnfmId: {}", vnfmId); + return restJson; + } + + restJson = (new VnfMgrVnfm()).getVnf(vnfmObjcet, vnfId); + + return restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL ? restJson : getVnfBody(restJson); + + } catch(JSONException e) { + LOG.error("function=getVnf, msg=JSONException occurs, e={}.", e); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + } + return restJson; + } + + private JSONObject getVnfBody(JSONObject restJson) { + try { + JSONObject vnfInfoJson = new JSONObject(); + JSONObject basicInfoJson = new JSONObject(); + + JSONObject retJson = restJson.getJSONArray("data").getJSONObject(0); + + basicInfoJson.put("vnfInstanceId", retJson.getString("id")); + basicInfoJson.put("vnfInstanceName", retJson.getString("vapp_name")); + basicInfoJson.put("vnfInstanceDescription", "vFW"); + + Vnfm vnfm = vnfmDao.getVnfmById(retJson.getString("id")); + basicInfoJson.put("vnfdId", vnfm == null ? "" : vnfm.getVnfdId()); + basicInfoJson.put("vnfdPackageId", vnfm == null ? "" : vnfm.getVnfPackageId()); + basicInfoJson.put("version", vnfm == null ? "" : vnfm.getVersion()); + basicInfoJson.put("vnfProvider", "hw"); + basicInfoJson.put("vnfType", retJson.get("vapp_type")); + basicInfoJson.put("vnfStatus", retJson.getString(Constant.STATUS)); + + vnfInfoJson.put("vnfInfo", basicInfoJson); + vnfInfoJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + return vnfInfoJson; + } catch(JSONException e) { + LOG.error("function=getVnf, msg=JSONException occurs, e={}.", e); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + return restJson; + } catch(IndexOutOfBoundsException e) { + LOG.error("function=getVnf, msg=IndexOutOfBoundsException occurs, e={}.", e); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + return restJson; + } + } + + @SuppressWarnings("unchecked") + private JSONObject transferVnfBody(JSONObject vnfObject, JSONObject resObject, String vnfmId) { + JSONObject restJson = new JSONObject(); + JSONObject vappIfno = new JSONObject(); + restJson.put("vnfd_id", resObject.getString("vnfdId")); + restJson.put("plan_id", resObject.getOrDefault("planId", "")); + restJson.put("plan_name", resObject.getOrDefault("planName", "")); + restJson.put("vapp_name", vnfObject.get("vnfInstanceName")); + restJson.put("project_id", vnfmId); + restJson.put("parameters", resObject.getJSONObject("parameters")); + restJson.put("nfvo_id", ""); + restJson.put("location", ""); + restJson.put("vnfm_id", vnfmId); + vappIfno.put("vapp_info", restJson); + return vappIfno; + } + + /** + * Provide function for get job + *
+ * + * @param jobId + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject getJob(String jobId, String vnfmId) { + LOG.warn("function=getJob ,msg=enter to get a job, vnfId:{}", jobId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + if(vnfmObjcet.isNullObject()) { + LOG.error("function=getJob, msg=vnfm not exists, vnfmId: {}", vnfmId); + return restJson; + } + + restJson = (new VnfMgrVnfm()).getJob(vnfmObjcet, jobId); + + } catch(JSONException e) { + LOG.error("function=getJob, msg=JSONException occurs, e={}.", e); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + } + return restJson; + } + + /** + * Provide function for save vnfInfo + *
+ * + * @param vnfObject + * @param resObject + * @since NFVO 0.5 + */ + public void saveVnfInfo(JSONObject vnfObject, JSONObject resObject) { + LOG.warn("function=saveVnfInfo , vnfObject:{}", vnfObject); + if(vnfObject.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) { + Vnfm info = new Vnfm(); + info.setId(vnfObject.getJSONObject("data").getString("vnfInstanceId")); + info.setVersion(resObject.getString("vnfdVersion")); + info.setVnfdId(resObject.getString("vnfdId")); + info.setVnfPackageId(""); + try { + vnfmDao.insertVnfm(info); + } catch(Exception e) { + LOG.error("function=saveVnfInfo, msg=ServiceException occurs, e={}.", e); + } + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgr.java new file mode 100644 index 00000000..11bb2291 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgr.java @@ -0,0 +1,254 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.process; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Provide function of resource for VNFM. + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public class VnfResourceMgr { + + private static final Logger LOG = LoggerFactory.getLogger(VnfResourceMgr.class); + + /** + * Provide function of grant resource for VNFM. + *
+ * + * @param vnfObj + * @param vnfId + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject grantVnfResource(JSONObject vnfObj, String vnfId, String vnfmId) { + LOG.warn("function=grantVnfResource, msg=enter to grant vnf resource, params: {}", vnfObj); + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + try { + String type = vnfObj.getString("type"); + String requestType = vnfObj.getString("operation_right"); + String vnfName = vnfObj.getString("vnf_name"); + + if(StringUtils.isEmpty(type) || StringUtils.isEmpty(requestType) || StringUtils.isEmpty(vnfName) + || StringUtils.isEmpty(vnfId)) { + LOG.error("function=grantVnfResource, msg=grant basic params error"); + resultJson.put("errorMsg", "basic params error"); + return resultJson; + } + + JSONArray vmList = vnfObj.getJSONArray("vm_list"); + + Map resMap = calculateGrantRes(vmList); + + if(null == resMap) { + LOG.error("function=grantVnfResource, msg=grant resource params error"); + resultJson.put("errorMsg", "resource params error"); + return resultJson; + } + + JSONObject grantObj = new JSONObject(); + grantObj.put("vimId", vnfObj.getString("vim_id")); + grantObj.put("vnfId", vnfId); + grantObj.put("vnfName", vnfName); + grantObj.put("vnfmId", vnfmId); + String action = getGrantAction(type, requestType); + grantObj.put("action", action); + + JSONObject grantParam = parseGrantParam(resMap, grantObj); + resultJson = sendGrantToResmgr(grantParam); + LOG.error("function=grantVnfResource, resultJson={}.", resultJson); + } catch(JSONException e) { + LOG.error("function=grantVnfResource, msg=parse params occoured JSONException e={}.", e); + resultJson.put("errorMsg", "params parse exception"); + } + + return resultJson; + } + + /** + *
+ * + * @param grantParam + * @return + * @since NFVO 0.5 + */ + private JSONObject sendGrantToResmgr(JSONObject grantParam) { + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(ParamConstants.GRANT_RES_URL, VnfmRestfulUtil.TYPE_PUT, + grantParam.toString()); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + return null; + } + LOG.error("funtion=sendGrantToResmgr, status={}", rsp.getStatus()); + return JSONObject.fromObject(rsp.getResponseContent()); + } + + /** + *
+ * + * @param resMap + * @param grantParam + * @return + * @since NFVO 0.5 + */ + private JSONObject parseGrantParam(Map resMap, JSONObject grantParam) { + JSONObject result = new JSONObject(); + result.put("vnfInstanceId", grantParam.getString("vnfId")); + result.put("vimId", grantParam.getString("vimId")); + + JSONArray resource = new JSONArray(); + JSONObject resourceObj = new JSONObject(); + resourceObj.put("type", "vdu"); + JSONObject resourceTemplate = new JSONObject(); + JSONObject storage = new JSONObject(); + storage.put("sizeOfStorage", resMap.get("diskNum")); + storage.put("typeOfStorage", ""); + storage.put("swImageDescriptor", ""); + JSONObject compute = new JSONObject(); + JSONObject virtualMemory = new JSONObject(); + virtualMemory.put("virtualMemSize", resMap.get("memNum")); + JSONObject virtualCpu = new JSONObject(); + virtualCpu.put("numVirtualCpu", resMap.get("cpuNum")); + compute.put("virtualMemory", virtualMemory); + compute.put("virtualCpu", virtualCpu); + resourceTemplate.put("virtualStorageDescriptor", storage); + resourceTemplate.put("virtualComputeDescriptor", compute); + resourceObj.put("resourceTemplate", resourceTemplate); + resourceObj.put("resourceDefinitionId", ""); + resourceObj.put("vdu", grantParam.getString("vnfName")); + resource.add(resourceObj); + + if("online".equals(grantParam.getString("action")) || "scaleOut".equals(grantParam.getString("action"))) { + result.put("addResource", resource); + } else { + result.put("removeResource", resource); + } + + JSONObject additionalParam = new JSONObject(); + additionalParam.put("vnfmId", grantParam.getString("vnfmId")); + additionalParam.put("vimId", grantParam.getString("vimId")); + additionalParam.put("tenant", ""); + result.put("additionalParam", additionalParam); + LOG.info("funtion=parseGrantParam, result={}", result); + return result; + } + + private Map calculateGrantRes(JSONArray vmList) { + Map resMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + int vmSize = vmList.size(); + int cpuNum = 0; + int memNum = 0; + int diskNum = 0; + int diskSize = 0; + int cpuTmp = 0; + int memTmp = 0; + int diskTmp = 0; + int initNum = 0; + + try { + for(int i = 0; i < vmSize; i++) { + JSONObject resInfo = vmList.getJSONObject(i); + JSONObject vmFlavor = resInfo.getJSONObject("vm_flavor"); + initNum = Integer.parseInt(resInfo.getString("init_number")); + + if(initNum == 0) { + continue; + } + + JSONArray volumList = vmFlavor.getJSONArray("storage"); + diskSize = volumList.size(); + + for(int j = 0; j < diskSize; j++) { + JSONObject volumeInfo = volumList.getJSONObject(j); + diskTmp += getDiskQuantity(volumeInfo); + } + + cpuTmp = Integer.parseInt(vmFlavor.getString("num_cpus")); + memTmp = Integer.parseInt(vmFlavor.getString("mem_size")); + + cpuNum += cpuTmp * initNum; + memNum += memTmp * initNum; + diskNum += diskTmp * initNum; + + diskTmp = 0; + + } + } catch(JSONException e) { + LOG.error("function=calculateGrantRes, msg=parse params occoured JSONException e={}.", e); + return null; + } + + resMap.put("cpuNum", cpuNum); + resMap.put("memNum", memNum); + resMap.put("diskNum", diskNum); + return resMap; + } + + private String getGrantAction(String type, String requestType) { + String action = "unknown"; + + if(("increase").equals(requestType)) { + if(("instantiation").equals(type)) { + action = "online"; + } else if(("scale").equals(type)) { + action = "scaleOut"; + } + + } else if(("decrease").equals(requestType)) { + if(("instantiation").equals(type)) { + action = "offline"; + } else if(("scale").equals(type)) { + action = "scaleIn"; + } + } + + return action; + } + + private int getDiskQuantity(JSONObject volumeObj) { + int disk = 0; + if(volumeObj.containsKey("vol_type")) { + if("local_volume".equals(volumeObj.getString("vol_type"))) { + disk = Integer.parseInt(volumeObj.getString("vol_size")); + } + } else if(volumeObj.containsKey("storage_type") && "local_image".equals(volumeObj.getString("storage_type"))) { + + disk = Integer.parseInt(volumeObj.getString("disk_size")); + + } + return disk; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoa.java new file mode 100644 index 00000000..445dd619 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoa.java @@ -0,0 +1,151 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.openo.nfvo.vnfmadapter.service.process.AuthMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces for authInfo + *
+ *

+ *

+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@Path("/rest/plat/smapp/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class AuthRoa { + + private static final Logger LOG = LoggerFactory.getLogger(AuthRoa.class); + + private AuthMgr authMgr; + + public void setAuthMgr(AuthMgr authMgr) { + this.authMgr = authMgr; + } + + /** + * Provide interface for add authInfo + *
+ * + * @param context + * @return + * @since NFVO 0.5 + */ + @PUT + @Path("/oauth/token") + public String authToken(@Context HttpServletRequest context, @Context HttpServletResponse resp) { + LOG.warn("function=login, msg=enter to get token."); + JSONObject subJsonObject = VnfmJsonUtil.getJsonFromContexts(context); + LOG.warn("subJsonObject: {}", subJsonObject); + + if(null == subJsonObject) { + LOG.error("function=login, msg=params are insufficient"); + String resultStr = "Login params insufficient"; + resp.setStatus(Constant.HTTP_BAD_REQUEST); + + return resultStr; + } + + JSONObject authResult = authMgr.authToken(subJsonObject); + LOG.warn("authResult: {}", authResult); + if(authResult.getInt("retCode") == Constant.REST_SUCCESS) { + JSONObject data = authResult.getJSONObject("data"); + + resp.setStatus(Constant.HTTP_OK); + // resp.setHeader("accessSession", data.getString("accessSession")); + return data.toString();// String.format(ParamConstants.GET_TOKEN_SUC_RESP, + // data.getString("userName"), + // data.getString("userName"), data.getString("roaRand")); + } else if(authResult.getInt("retCode") == Constant.HTTP_INNERERROR) { + Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(authResult.getString("data")).build(); + + return String.format(ParamConstants.GET_TOKEN_FAIL_RESP, authResult.getString("data")); + } else { + Response.status(Response.Status.UNAUTHORIZED).entity(authResult.getString("data")).build(); + + return String.format(ParamConstants.GET_TOKEN_FAIL_RESP, authResult.getString("data")); + } + } + + /** + * Provide interface for delete authInfo + *
+ * + * @param context + * @param userName + * @param roarand + * @return + * @since NFVO 0.5 + */ + @DELETE + @Path("/auth/tokens/{userName}/{roarand}") + public String delAuthToken(@Context HttpServletRequest context, @PathParam("userName") String userName, + @PathParam("roarand") String roarand, @Context HttpServletResponse resp) { + LOG.warn("function=logout, msg=enter to logout"); + JSONObject resultJson = new JSONObject(); + + resultJson.put("Information", "Operation success"); + resp.setStatus(Constant.HTTP_NOCONTENT); + LOG.warn("function=logout, msg=end to logout"); + return resultJson.toString(); + } + + /** + * Provide interface for handshake authInfo + *
+ * + * @param context + * @param roattr + * @return + * @since NFVO 0.5 + */ + @GET + @Path("/nfvo/shakehand") + public String shakehand(@Context HttpServletRequest context, @QueryParam("roattr") String roattr, + @Context HttpServletResponse resp) { + JSONObject resultJson = new JSONObject(); + resultJson.put("status", "running"); + resultJson.put("description", "Operation success"); + resp.setStatus(Constant.HTTP_OK); + + return resultJson.toString(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoa.java new file mode 100644 index 00000000..5dfd290b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoa.java @@ -0,0 +1,49 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.rest; + +import java.io.IOException; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.io.IOUtils; + +/** + * Swagger API Doc.
+ * + * @author + * @version NFVO 0.5 Oct 24, 2016 + */ +@Path("/openoapi/hwvnfm/v1") +@Produces({MediaType.APPLICATION_JSON}) +public class SwaggerRoa { + /** + * API doc. + * @param filename + * @return + * @throws IOException + */ + @GET + @Path("/swagger.json") + public String apidoc() throws IOException{ + ClassLoader classLoader = getClass().getClassLoader(); + return IOUtils.toString(classLoader.getResourceAsStream("swagger.json")); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoa.java new file mode 100644 index 00000000..138e284e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoa.java @@ -0,0 +1,68 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.openo.nfvo.vnfmadapter.service.adapter.impl.AdapterResourceManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + + +/** + * Provide interfaces of resource for VNFM. + *
+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@Path("/rest/v2/computeservice/getAllCloud") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VnfAdapterResourceRoa { + + private static final Logger LOG = LoggerFactory.getLogger(VnfAdapterResourceRoa.class); + + + /** + * Provide function of grant resource. + *
+ * + * @param context + * @return + * @since NFVO 0.5 + */ + @GET + public String getAllCloudInfo(@Context HttpServletRequest context) { + LOG.info("function=getAllCloudInfo, msg=getAllCloudInfo resource"); + + //Find a way to get url and pass it getAllCloud(); //NOSONAR + + AdapterResourceManager arm = new AdapterResourceManager(); + JSONObject resultObj = arm.getAllCloud("",""); + + return resultObj.getString("vim_id"); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoa.java new file mode 100644 index 00000000..ad7663e8 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoa.java @@ -0,0 +1,105 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.process.VnfResourceMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces of resource for VNFM. + *
+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@Path("/rest/vnfmmed/csm/v2/vapps") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VnfResourceRoa { + + private static final Logger LOG = LoggerFactory.getLogger(VnfResourceRoa.class); + + private VnfResourceMgr vnfResourceMgr; + + public void setVnfResourceMgr(VnfResourceMgr vnfResourceMgr) { + this.vnfResourceMgr = vnfResourceMgr; + } + + /** + * Provide function of grant resource. + *
+ * + * @param context + * @param vnfId + * @return + * @since NFVO 0.5 + */ + @PUT + @Path("/instances/{vnfId}/grant") + public String grantVnfRes(@Context HttpServletRequest context, @PathParam("vnfId") String vnfId) { + LOG.info("function=grantVnfRes, msg=enter to grant vnf resource."); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + + JSONObject dataObject = VnfmJsonUtil.getJsonFromContexts(context); + LOG.info("function=grantVnfRes, dataObject: {}", dataObject); + /*if(null == dataObject) { + LOG.error("function=grantVnfRes, msg=param error"); + restJson.put("data", "Params error"); + return restJson.toString(); + } + + JSONObject grantObj = dataObject.getJSONObject("grant"); + + if(null == grantObj) { + LOG.error("function=grantVnfRes, msg=param error"); + restJson.put("data", "Grant param error"); + return restJson.toString(); + } + + String vnfmId = grantObj.getString("project_id"); + + JSONObject resultObj = vnfResourceMgr.grantVnfResource(grantObj, vnfId, vnfmId);*/ + JSONObject res = new JSONObject(); + res.put("msg","grant success"); + return res.toString(); + } + + @PUT + @Path("/lifecycle_changes_notification") + public String notify(@Context HttpServletRequest context) { + LOG.info("function=notify, msg=enter to notify vnf resource"); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + + return restJson.toString(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoa.java new file mode 100644 index 00000000..c68cb61c --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoa.java @@ -0,0 +1,286 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.rest; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.collections.map.UnmodifiableMap; +import org.apache.commons.lang3.StringUtils; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.process.VnfMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces for instantiate or terminate VNF. + *
+ * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@SuppressWarnings("unchecked") +@Path("/openoapi/hwvnfm/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VnfRoa { + + private static final Logger LOG = LoggerFactory.getLogger(VnfRoa.class); + + private VnfMgr vnfMgr; + + private static Map PROGRESSITEM; + + private static Map JOBSTATUSITEM; + + static { + Map map = new HashMap<>(); + map.put("Building", "50"); + map.put("Active", "100"); + map.put("Stopped", "50"); + map.put("Error", "100"); + PROGRESSITEM = UnmodifiableMap.decorate(map); + + map = new HashMap<>(); + map.put("Building", "processing"); + map.put("Active", "finished"); + map.put("Stopped", "processing"); + map.put("Error", "error"); + JOBSTATUSITEM = UnmodifiableMap.decorate(map); + } + + public void setVnfMgr(VnfMgr vnfMgr) { + this.vnfMgr = vnfMgr; + } + + /** + * Scale VNF + * + * @param context + * * { + * "vnfInstanceId":"5", + * "type":"SCALE_OUT", + * "aspectId":"101", + * "numberOfSteps":"1", + * "additionalParam":{} + * } + * @param resp + * @param vnfmId + * @return + * { + * "jobId":"1" + * } + * @throws ServiceException + */ + @POST + @Path("/{vnfmId}/vnfs/{vnfInstanceId}/scale") + public String scaleVnf(@Context HttpServletRequest context, @Context HttpServletResponse resp, + @PathParam("vnfmId") String vnfmId, @PathParam("vnfInstanceId") String vnfInstanceId) + throws ServiceException { + JSONObject jsonObject = VnfmJsonUtil.getJsonFromContexts(context); + LOG.info("function=scaleVNF, msg=enter to scale a vnf. request body:" + jsonObject); + JSONObject result = new JSONObject(); + String msg = ""; + if(null == jsonObject) { + msg = "the parameters do not meet the requirements,please check it!"; + LOG.error("function=scalVnf," + msg); + resp.setStatus(Constant.HTTP_NOT_ACCEPTABLE); + result.put("msg", msg); + return result.toString(); + } + + result = vnfMgr.scaleVNF(jsonObject, vnfmId, vnfInstanceId); + LOG.info("function=scaleVNF,result=" + result.toString()); + if(result.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=scaleVNF, msg=scaleVnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return result.toString(); + } + return JSONObject.fromObject(result.getJSONObject("data")).toString(); + } + + /** + * Provide function for instantiate VNF + *
+ * + * @param context + * @param resp + * @param vnfmId + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @POST + @Path("/{vnfmId}/vnfs") + public String addVnf(@Context HttpServletRequest context, @Context HttpServletResponse resp, + @PathParam("vnfmId") String vnfmId) throws ServiceException { + LOG.warn("function=addVnf, msg=enter to add a vnf"); + JSONObject subJsonObject = VnfmJsonUtil.getJsonFromContexts(context); + JSONObject restJson = new JSONObject(); + + if(null == subJsonObject) { + LOG.error("function=addVnf, msg=params are insufficient"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + LOG.info("addVnf request info from (LCM):" + subJsonObject); + restJson = vnfMgr.addVnf(subJsonObject, vnfmId); + + if(restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=addVnf, msg=addvnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + return JSONObject.fromObject(restJson.getJSONObject("data")).toString(); + } + + /** + * Provide function for terminate VNF + *
+ * + * @param vnfmId + * @param resp + * @param vnfInstanceId + * @param context + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @POST + @Path("/{vnfmId}/vnfs/{vnfInstanceId}/terminate") + public String delVnf(@PathParam("vnfmId") String vnfmId, @Context HttpServletResponse resp, + @PathParam("vnfInstanceId") String vnfInstanceId, @Context HttpServletRequest context) + throws ServiceException { + LOG.warn("function=delVnf, msg=enter to delete a vnf: vnfInstanceId: {}, vnfmId: {}", vnfInstanceId, vnfmId); + JSONObject vnfObject = VnfmJsonUtil.getJsonFromContexts(context); + JSONObject restJson = new JSONObject(); + + if(StringUtils.isEmpty(vnfInstanceId) || StringUtils.isEmpty(vnfmId)) { + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.deleteVnf(vnfInstanceId, vnfmId, vnfObject); + if(restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=delVnf, msg=delVnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + return JSONObject.fromObject(restJson.getJSONObject("data")).toString(); + } + + /** + * Provide function for get VNF + *
+ * + * @param vnfmId + * @param resp + * @param vnfInstanceId + * @param context + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/{vnfmId}/vnfs/{vnfInstanceId}") + public String getVnf(@PathParam("vnfmId") String vnfmId, @Context HttpServletResponse resp, + @PathParam("vnfInstanceId") String vnfInstanceId, @Context HttpServletRequest context) + throws ServiceException { + LOG.warn("function=getVnf, msg=enter to get a vnf: vnfInstanceId: {}, vnfmId: {}", vnfInstanceId, vnfmId); + JSONObject restJson = new JSONObject(); + + if(StringUtils.isEmpty(vnfInstanceId) || StringUtils.isEmpty(vnfmId)) { + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.getVnf(vnfInstanceId, vnfmId); + if(restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=getVnf, msg=getVnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson.remove(Constant.RETCODE); + return restJson.toString(); + } + + /** + * Provide function for get job + *
+ * + * @param jobId + * @param vnfmId + * @param resp + * @param responseId + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/{vnfmId}/jobs/{jobId}") + public String getJob(@PathParam("jobId") String jobId, @PathParam("vnfmId") String vnfmId, + @Context HttpServletResponse resp, @QueryParam("@responseId") String responseId) throws ServiceException { + LOG.warn("function=getJob, msg=enter to get a job: jobId: {}", jobId); + JSONObject restJson = new JSONObject(); + + if(StringUtils.isEmpty(jobId) || StringUtils.isEmpty(vnfmId)) { + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.getJob(jobId, vnfmId); + if(restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=getJob, msg=getJob fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + return getJobBody(restJson); + } + + private String getJobBody(JSONObject restJson) { + JSONObject responseJson = new JSONObject(); + JSONObject jobInfoJson = new JSONObject(); + JSONObject retJson = restJson.getJSONArray("data").getJSONObject(0); + jobInfoJson.put("jobId", retJson.getString("id")); + responseJson.put("progress", PROGRESSITEM.get(retJson.getString(Constant.STATUS))); + responseJson.put("status", JOBSTATUSITEM.get(retJson.getString(Constant.STATUS))); + responseJson.put("errorCode", "null"); + responseJson.put("responseId", PROGRESSITEM.get(retJson.getString(Constant.STATUS))); + jobInfoJson.put("responsedescriptor", responseJson); + return jobInfoJson.toString(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java new file mode 100644 index 00000000..7b4738dc --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java @@ -0,0 +1,64 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import org.apache.http.HttpStatus; + +/** + * Exception response model.
+ * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +public class ExceptionMessage { + + private String errorCode = "unknown.error"; + + private int httpCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; + + private String message; + + @Override + public String toString() { + return "Error {errorCode=" + this.errorCode + ", httpCode=" + this.httpCode + ", message=" + + this.message + "}"; + } + + public String getErrorCode() { + return this.errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getMessage() { + return this.message; + } + + public void setMessage(String message) { + this.message = message; + } + + public int getHttpCode() { + return this.httpCode; + } + + public void setHttpCode(int httpCode) { + this.httpCode = httpCode; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java new file mode 100644 index 00000000..25eb8c24 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java @@ -0,0 +1,41 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +/** + * Generic exception response provider.
+ * + * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +@Provider +public class GenericExceptionMapper implements ExceptionMapper{ + + @Override + public Response toResponse(Exception exception) { + ExceptionMessage message = new ExceptionMessage(); + message.setMessage(exception.getMessage()); + return Response.status(message.getHttpCode()).type( + MediaType.APPLICATION_JSON).entity(message).build(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java new file mode 100644 index 00000000..957c0d40 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java @@ -0,0 +1,45 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +/** + * ServiceException response provider.
+ * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +@Provider +public class ServiceExceptionMapper implements ExceptionMapper{ + + @Override + public Response toResponse(ServiceException exception) { + ExceptionMessage message = new ExceptionMessage(); + message.setErrorCode(exception.getId()); + message.setHttpCode(exception.getHttpCode()); + message.setMessage(exception.getMessage()); + return Response.status(message.getHttpCode()). + type(MediaType.APPLICATION_JSON).entity(message).build(); + } + +} -- cgit 1.2.3-korg