5dc8184bf14abb4947c4f6c5cc04d069361685c5
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / openo / nfvo / jujuvnfmadapter / service / adapter / impl / AdapterResourceManager.java
1 /*
2  * Copyright 2016 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openo.nfvo.jujuvnfmadapter.service.adapter.impl;
18
19 import java.io.*;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24
25 import org.openo.baseservice.roa.util.restclient.RestfulResponse;
26 import org.openo.baseservice.util.impl.SystemEnvVariablesFactory;
27 import org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager;
28 import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils;
29 import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.JujuVnfmRestfulUtil;
30 import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IResourceManager;
31 import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant;
32 import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.stereotype.Service;
36
37 import net.sf.json.JSONObject;
38
39 /**
40  * 
41  * Adapter resource manager class.<br>
42  * <p>
43  * </p>
44  * 
45  * @author
46  * @version     NFVO 0.5  Sep 12, 2016
47  */
48 @Service
49 public class AdapterResourceManager implements IResourceManager {
50
51     private static final Logger LOG = LoggerFactory.getLogger(AdapterResourceManager.class);
52
53
54     @Override
55     public JSONObject getJujuVnfmInfo(Map<String, String> paramsMap) {
56         JSONObject resultObj = new JSONObject();
57         //verify url,reserve
58         
59         RestfulResponse rsp = JujuVnfmRestfulUtil.getRemoteResponse(paramsMap,"");
60         if(null == rsp) {
61             LOG.error("function=getJujuVnfmInfo,  RestfulResponse is null");
62             resultObj.put(Constant.REASON, "RestfulResponse is null.");
63             resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE);
64             return resultObj;
65         }
66         String resultCreate = rsp.getResponseContent();
67
68         if(rsp.getStatus() == Constant.HTTP_OK) {
69             LOG.warn("function=getJujuVnfmInfo, msg= status={}, result={}.", rsp.getStatus(), resultCreate);
70             resultObj = JSONObject.fromObject(resultCreate);
71             resultObj.put(Constant.RETURN_CODE, Constant.HTTP_OK);
72             return resultObj;
73         } else {
74             LOG.error("function=getJujuVnfmInfo, msg=ESR return fail,status={}, result={}.", rsp.getStatus(),
75                     resultCreate);
76             resultObj.put(Constant.REASON, "ESR return fail.");
77         }
78         resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE);
79         return resultObj;
80     }
81
82     @Override
83     public JSONObject getVnfdInfo(String csarId) {
84         JSONObject resultObj = new JSONObject();
85         JSONObject csarPkgInfoObj = new JSONObject();
86         
87         if(null == csarId || "".equals(csarId)) {
88             resultObj.put("reason", "csarId is null.");
89             resultObj.put("retCode", Constant.REST_FAIL);
90             return resultObj;
91         }
92        String downloadUri =  this.fetchDownloadUrlFromCatalog(csarId);
93         if(downloadUri == null){
94             LOG.error("fetchDownloadUrlFromCatalog return null,csarId="+csarId);
95             resultObj.put(Constant.REASON, "fetchDownloadUrlFromCatalog is null.");
96             resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE);
97             return resultObj;
98         }
99         String csarPkgInfo;
100                 try {
101                         csarPkgInfo = readCsarPkgInfo();
102                 csarPkgInfoObj = JSONObject.fromObject(csarPkgInfo); //NOSONAR
103                 } catch (IOException e) {
104                         e.printStackTrace();
105                 }
106                 
107         String csarfilepath = csarPkgInfoObj.getString("csar_file_path");
108         String csarfilename = csarPkgInfoObj.getString("csar_file_name");
109
110         // download csar package and save in location.
111         JSONObject downloadObject = downloadCsar(downloadUri, csarfilepath+ System.getProperty("file.separator") +csarfilename);
112
113         if (Integer.valueOf(downloadObject.get("retCode").toString()) != Constant.REST_SUCCESS) {
114                 LOG.error("download CSAR fail.", downloadObject.get("retCode"));
115             resultObj.put("reason", downloadObject.get("reason").toString());
116             resultObj.put("retCode", downloadObject.get("retCode").toString());
117             return resultObj;
118         }
119         LOG.info("download CSAR successful.", downloadObject.get("retCode"));
120
121         // unzip csar package to location.
122         JSONObject unzipObject = unzipCSAR(csarfilepath+ System.getProperty("file.separator") +csarfilename, csarfilepath);
123
124         if (Integer.valueOf(unzipObject.get("retCode").toString()) != Constant.REST_SUCCESS) {
125                 LOG.error("unzip CSAR fail.", unzipObject.get("retCode"));
126             resultObj.put("reason", unzipObject.get("reason").toString());
127             resultObj.put("retCode", unzipObject.get("retCode").toString());
128             return resultObj;
129         }
130         LOG.info("unzip CSAR successful.", unzipObject.get("retCode"));
131
132         resultObj.put(Constant.RETURN_CODE, Constant.HTTP_OK);
133         resultObj.put("csarFilePath", getImagesPath(csarfilepath));
134
135         return resultObj;
136     }
137     private String getImagesPath(String csarfilepath){
138         File imageFile = new File(csarfilepath+"SoftwareImages");
139         if(imageFile.exists()){
140             File[] charmFiles = imageFile.listFiles();
141             for(File file : charmFiles){
142                 if(!file.getName().endsWith(".zip")){
143                     return file.getAbsolutePath()+"/";
144                 }
145             }
146         }
147         return csarfilepath;
148     }
149
150     public String fetchDownloadUrlFromCatalog(String csarId){
151         String downloadUri = null;
152         try {
153             Map paramsMap = new HashMap();
154
155             paramsMap.put("url", String.format(UrlConstant.REST_CSARINFO_GET, csarId));
156             paramsMap.put("methodType", Constant.GET);
157
158             RestfulResponse rsp = JujuVnfmRestfulUtil.getRemoteResponse(paramsMap,"");
159             if(null == rsp) {
160                 LOG.error("function=getVnfdInfo,  RestfulResponse is null");
161                return null;
162             }
163             String resultCreate = rsp.getResponseContent();
164
165             if(rsp.getStatus() != Constant.HTTP_OK) {
166                 LOG.error("function=getVnfdInfo, msg=catalog return fail,status={}, result={}.", rsp.getStatus(),
167                         resultCreate);
168                return null;
169             }
170             JSONObject csarObj = JSONObject.fromObject(resultCreate);
171             downloadUri = csarObj.getString("downloadUri");
172         } catch (Exception e) {
173            LOG.error("fetchDownloadUrlFromCatalog error",e);
174         }
175         return downloadUri;
176     }
177     
178     /**
179      * Get csar package information.<br>
180      *
181      * @return
182      * @throws IOException
183      * @since  NFVO 0.5
184      */
185     public static String readCsarPkgInfo() throws IOException {
186         InputStream ins = null;
187         BufferedInputStream bins = null;
188         String fileContent = "";
189
190         String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator")
191                 + "etc" + System.getProperty("file.separator") + "csarInfo" + System.getProperty("file.separator")
192                 + Constant.CSARINFO;
193
194         try {
195             ins = new FileInputStream(fileName);
196             bins = new BufferedInputStream(ins);
197
198             byte[] contentByte = new byte[ins.available()];
199             int num = bins.read(contentByte);
200
201             if (num > 0) {
202                 fileContent = new String(contentByte);
203             }
204         } catch (FileNotFoundException e) {
205             LOG.error(fileName + "is not found!", e);
206         } finally {
207             if (ins != null) {
208                 ins.close();
209             }
210             if (bins != null) {
211                 bins.close();
212             }
213         }
214         return fileContent;
215     }
216     
217     /**
218      * download CSAR.<br>
219      * @return
220      * @throws IOException
221      * @since  NFVO 0.5
222      */    
223     public JSONObject downloadCsar(String url, String filePath) {
224         JSONObject resultObj = new JSONObject();
225
226         if(url == null || "".equals(url)) {
227             resultObj.put("reason", "url is null.");
228             resultObj.put("retCode", Constant.REST_FAIL);
229             return resultObj;
230         }
231         if(filePath == null || "".equals(filePath)) {
232             resultObj.put("reason", "downloadUrl filePath is null.");
233             resultObj.put("retCode", Constant.REST_FAIL);
234             return resultObj;
235         }
236
237         String status = DownloadCsarManager.download(url, filePath);
238
239         if (Constant.DOWNLOADCSAR_SUCCESS.equals(status)) {
240             resultObj.put("reason", "download csar file successfully.");
241             resultObj.put("retCode", Constant.REST_SUCCESS);
242         } else {
243             resultObj.put("reason", "download csar file failed.");
244             resultObj.put("retCode", Constant.REST_FAIL);
245         }
246         return resultObj;
247     }
248     
249     /*
250      * unzip CSAR packge
251      * @param fileName filePath
252      * @return     
253      */
254     public JSONObject unzipCSAR(String fileName,String filePath) {
255         JSONObject resultObj = new JSONObject();
256
257         if(fileName == null || "".equals(fileName)) {
258             resultObj.put("reason", "fileName is null.");
259             resultObj.put("retCode", Constant.REST_FAIL);
260             return resultObj;
261         }
262         if(filePath == null || "".equals(filePath)) {
263             resultObj.put("reason", "unzipCSAR filePath is null.");
264             resultObj.put("retCode", Constant.REST_FAIL);
265             return resultObj;
266         }
267
268         int status = DownloadCsarManager.unzipCSAR(fileName, filePath);
269
270
271         if (Constant.UNZIP_SUCCESS == status) {
272             resultObj.put("reason", "unzip csar file successfully.");
273             resultObj.put("retCode", Constant.REST_SUCCESS);
274             chmodToFiles(filePath);
275         } else {
276             resultObj.put("reason", "unzip csar file failed.");
277             resultObj.put("retCode", Constant.REST_FAIL);
278         }
279         return resultObj;
280     }
281
282
283
284 private void chmodToFiles(String filePath) {
285     try {
286         List<String> commands = new ArrayList<String>();
287         commands.add("chmod");
288         commands.add("-R");
289         commands.add("777");
290         commands.add(filePath);
291         EntityUtils.ExeRes exeRes = EntityUtils.execute(null, commands);
292         if (exeRes.getCode() == EntityUtils.ExeRes.SUCCESS) {
293             LOG.info("chmod success:" + EntityUtils.formatCommand(commands));
294         } else {
295             LOG.error("dchmod fail" + EntityUtils.formatCommand(commands) + "\n" + exeRes);
296         }
297     } catch (Exception e) {
298         LOG.error("chmod error:",e);
299     }
300 }
301 }
302