Add modify vnf feature on driver
[vfc/nfvo/driver/vnfm/svnfm.git] / nokia / vnfmdriver / vfcadaptorservice / vfcadaptor / src / main / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / cbam / impl / CbamMgmrImpl.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
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.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.impl;
18
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.util.HashMap;
24
25 import org.apache.http.client.ClientProtocolException;
26 import org.apache.log4j.Logger;
27 import org.json.JSONException;
28 import org.json.JSONObject;
29 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMCreateVnfRequest;
30 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMCreateVnfResponse;
31 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMHealVnfRequest;
32 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMHealVnfResponse;
33 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMInstantiateVnfRequest;
34 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMInstantiateVnfResponse;
35 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMModifyVnfRequest;
36 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMModifyVnfResponse;
37 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMQueryOperExecutionResponse;
38 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMQueryVnfResponse;
39 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMScaleVnfRequest;
40 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMScaleVnfResponse;
41 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMTerminateVnfRequest;
42 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.CBAMTerminateVnfResponse;
43 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.inf.CbamMgmrInf;
44 import org.onap.vfc.nfvo.driver.vnfm.svnfm.common.bo.AdaptorEnv;
45 import org.onap.vfc.nfvo.driver.vnfm.svnfm.constant.CommonConstants;
46 import org.onap.vfc.nfvo.driver.vnfm.svnfm.http.client.HttpClientProcessorInf;
47 import org.onap.vfc.nfvo.driver.vnfm.svnfm.http.client.HttpResult;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.http.MediaType;
50 import org.springframework.stereotype.Component;
51 import org.springframework.web.bind.annotation.RequestMethod;
52
53 import com.google.gson.Gson;
54
55 @Component
56 public class CbamMgmrImpl implements CbamMgmrInf {
57         private static final Logger logger = Logger.getLogger(CbamMgmrImpl.class);
58         private Gson gson = new Gson();
59         
60         @Autowired 
61         private AdaptorEnv adaptorEnv;
62         
63         @Autowired
64         HttpClientProcessorInf httpClientProcessor;
65         
66         public String retrieveToken() throws ClientProtocolException, IOException, JSONException {
67                 String result = null;
68                 String url= adaptorEnv.getCbamApiUriFront() + CommonConstants.CbamRetrieveTokenPath;
69                 HashMap<String, String> map = new HashMap<>();
70                 map.put(CommonConstants.ACCEPT, "*/*");
71                 map.put(CommonConstants.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
72                 
73                 String bodyPostStr = String.format(CommonConstants.CbamRetrieveTokenPostStr, adaptorEnv.getClientId(), adaptorEnv.getClientSecret(), adaptorEnv.getCbamUserName(), adaptorEnv.getCbamPassword());
74                 
75                 logger.debug("CbamMgmrImpl -> retrieveToken, url is " + url);
76                 logger.debug("CbamMgmrImpl -> retrieveToken, bodyPostStr is " + bodyPostStr);
77                 
78                 String responseStr = httpClientProcessor.process(url, RequestMethod.POST, map, bodyPostStr).getContent();
79                 
80                 logger.info("CbamMgmrImpl -> retrieveToken, responseStr is " + responseStr);
81                 
82                 JSONObject tokenJsonObject = new JSONObject(responseStr);
83                 
84                 result = tokenJsonObject.getString(CommonConstants.CBAM_TOKEN_KEY);
85                 
86                 return result;
87         }
88         
89         public CBAMCreateVnfResponse createVnf(CBAMCreateVnfRequest cbamRequest) throws ClientProtocolException, IOException {
90                 String httpPath = CommonConstants.CbamCreateVnfPath;
91                 RequestMethod method = RequestMethod.POST;
92                         
93                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
94                 String responseStr = httpResult.getContent();
95                 
96                 logger.info("CbamMgmrImpl -> createVnf, responseStr is " + responseStr);
97                 int code = httpResult.getStatusCode();
98                 if(code == 201) {
99                         logger.info("CbamMgmrImpl -> createVnf success");
100                 }else {
101                         logger.error("CbamMgmrImpl -> createVnf error ");
102                 }
103                 CBAMCreateVnfResponse response = gson.fromJson(responseStr, CBAMCreateVnfResponse.class);
104                 
105                 return response;
106         }
107         
108         public CBAMModifyVnfResponse modifyVnf(CBAMModifyVnfRequest cbamRequest, String vnfInstanceId)
109                         throws ClientProtocolException, IOException {
110                 String httpPath = String.format(CommonConstants.CbamModifyVnfPath, vnfInstanceId);
111                 
112                 RequestMethod method = RequestMethod.PATCH;
113                         
114                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
115                 String responseStr = httpResult.getContent();
116                 
117                 logger.info("CbamMgmrImpl -> modifyVnf, responseStr is " + responseStr);
118                 int code = httpResult.getStatusCode();
119                 if(code == 201) {
120                         logger.info("CbamMgmrImpl -> modifyVnf success");
121                 }else {
122                         logger.error("CbamMgmrImpl -> modifyVnf error ");
123                 }
124                 CBAMModifyVnfResponse response = gson.fromJson(responseStr, CBAMModifyVnfResponse.class);
125                 return response;
126         }
127         
128         /* (non-Javadoc)
129          * @see com.nokia.vfcadaptor.cbam.impl.CbamMgmrInf#instantiateVnf(com.nokia.vfcadaptor.cbam.bo.CBAMInstantiateVnfRequest, java.lang.String)
130          */
131         public CBAMInstantiateVnfResponse instantiateVnf(CBAMInstantiateVnfRequest cbamRequest, String vnfInstanceId) throws ClientProtocolException, IOException {
132                 String httpPath = String.format(CommonConstants.CbamInstantiateVnfPath, vnfInstanceId);
133                 RequestMethod method = RequestMethod.POST;
134                         
135                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
136                 String responseStr = httpResult.getContent();
137                 
138                 logger.info("CbamMgmrImpl -> instantiateVnf, responseStr is " + responseStr);
139                 int code = httpResult.getStatusCode();
140                 if(code == 202) {
141                         logger.info("CbamMgmrImpl -> instantiateVnf success " );
142                 }else {
143                         logger.error("CbamMgmrImpl -> instantiateVnf error " );
144                 }
145                 CBAMInstantiateVnfResponse response = gson.fromJson(responseStr, CBAMInstantiateVnfResponse.class);
146                 
147                 return response;
148         }
149         
150         public CBAMTerminateVnfResponse terminateVnf(CBAMTerminateVnfRequest cbamRequest, String vnfInstanceId) throws ClientProtocolException, IOException {
151                 String httpPath = String.format(CommonConstants.CbamTerminateVnfPath, vnfInstanceId);
152                 RequestMethod method = RequestMethod.POST;
153                 
154                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
155                 String responseStr = httpResult.getContent();
156                 
157                 logger.info("CbamMgmrImpl -> terminateVnf, responseStr is " + responseStr);
158                 int code = httpResult.getStatusCode();
159                 if(code == 202) {
160                         logger.info("CbamMgmrImpl -> terminateVnf  sucess " );
161                 }else {
162                         logger.error("CbamMgmrImpl -> terminateVnf error " );
163                 }
164                 CBAMTerminateVnfResponse response = gson.fromJson(responseStr, CBAMTerminateVnfResponse.class);
165                 
166                 return response;
167         }
168         
169         public void deleteVnf(String vnfInstanceId) throws ClientProtocolException, IOException {
170                 String httpPath = String.format(CommonConstants.CbamDeleteVnfPath, vnfInstanceId);
171                 RequestMethod method = RequestMethod.DELETE;
172                 HttpResult httpResult = operateCbamHttpTask(null, httpPath, method);
173                 
174                 int code = httpResult.getStatusCode();
175                 if(code == 204) {
176                         logger.info("CbamMgmrImpl -> deleteVnf success.");
177                 }else {
178                     logger.error("CbamMgmrImpl -> deleteVnf error. detail info is " + httpResult.getContent());
179                 }
180                 
181         }
182         
183         public CBAMScaleVnfResponse scaleVnf(CBAMScaleVnfRequest cbamRequest, String vnfInstanceId) throws ClientProtocolException, IOException {
184                 String httpPath = String.format(CommonConstants.CbamScaleVnfPath, vnfInstanceId);
185                 RequestMethod method = RequestMethod.POST;
186                         
187                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
188                 String responseStr = httpResult.getContent();
189                 int code = httpResult.getStatusCode();
190                 if(code == 202) {
191                         logger.info("CbamMgmrImpl -> scaleVnf success.");
192                 }else {
193                     logger.error("CbamMgmrImpl -> scaleVnf error. " );
194                 }
195                 CBAMScaleVnfResponse response = gson.fromJson(responseStr, CBAMScaleVnfResponse.class);
196                 
197                 return response;
198         }
199
200         public CBAMHealVnfResponse healVnf(CBAMHealVnfRequest cbamRequest, String vnfInstanceId) throws ClientProtocolException, IOException {
201                 String httpPath = String.format(CommonConstants.CbamHealVnfPath, vnfInstanceId);
202                 RequestMethod method = RequestMethod.POST;
203                         
204                 HttpResult httpResult = operateCbamHttpTask(cbamRequest, httpPath, method);
205                 String responseStr = httpResult.getContent();
206                 
207                 logger.info("CbamMgmrImpl -> healVnf, responseStr is " + responseStr);
208                 int code = httpResult.getStatusCode();
209                 if(code == 202) {
210                         logger.info("CbamMgmrImpl -> healVnf success.");
211                 }else {
212                     logger.error("CbamMgmrImpl -> healVnf error. " );
213                 }
214                 CBAMHealVnfResponse response = gson.fromJson(responseStr, CBAMHealVnfResponse.class);
215                 
216                 return response;
217         }
218         
219         public CBAMQueryVnfResponse queryVnf(String vnfInstanceId) throws ClientProtocolException, IOException {
220                 String httpPath = String.format(CommonConstants.CbamQueryVnfPath, vnfInstanceId);
221                 RequestMethod method = RequestMethod.GET;
222                 
223                 HttpResult httpResult = operateCbamHttpTask(null, httpPath, method);
224                 String responseStr = httpResult.getContent();
225                 
226                 logger.info("CbamMgmrImpl -> queryVnf, responseStr is " + responseStr);
227                 int code = httpResult.getStatusCode();
228                 if(code == 200) {
229                         logger.info("CbamMgmrImpl -> queryVnf success.");
230                 }else {
231                     logger.error("CbamMgmrImpl -> queryVnf error. " );
232                 }
233                 
234                 CBAMQueryVnfResponse response = gson.fromJson(responseStr, CBAMQueryVnfResponse.class);
235                 
236                 return response;
237         }
238
239         public HttpResult operateCbamHttpTask(Object httpBodyObj, String httpPath, RequestMethod method) throws ClientProtocolException, IOException {
240                 String token = null;
241                 try {
242                         token = retrieveToken();
243                 } catch (JSONException e) {
244                         logger.error("retrieveTokenError ", e);
245                 }
246         
247                 String url= adaptorEnv.getCbamApiUriFront() + httpPath;
248                 
249                 HashMap<String, String> map = new HashMap<>();
250                 map.put(CommonConstants.AUTHORIZATION, "bearer " + token);
251                 map.put(CommonConstants.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
252                 
253                 return httpClientProcessor.process(url, method, map, gson.toJson(httpBodyObj));
254         }
255
256         public CBAMQueryOperExecutionResponse queryOperExecution(String execId) throws ClientProtocolException, IOException{
257                 String httpPath = String.format(CommonConstants.CbamGetOperStatusPath, execId);
258                 RequestMethod method = RequestMethod.GET;
259                 
260                 HttpResult httpResult = operateCbamHttpTask(null, httpPath, method);
261                 String responseStr = httpResult.getContent();
262                 
263                 logger.info("CbamMgmrImpl -> CBAMQueryOperExecutionResponse, responseStr is " + responseStr);
264                 
265                 int code = httpResult.getStatusCode();
266                 if(code == 200) {
267                         logger.info("CbamMgmrImpl -> CBAMQueryOperExecutionResponse, success" );
268                 }else if(code == 202) {
269                         logger.info("CbamMgmrImpl -> CBAMQueryOperExecutionResponse, ongoing" );
270                 }else {
271                         logger.error("CbamMgmrImpl -> CBAMQueryOperExecutionResponse, error" );
272                 }
273                 
274                 CBAMQueryOperExecutionResponse response = gson.fromJson(responseStr, CBAMQueryOperExecutionResponse.class);
275                 
276                 return response;
277         }
278
279         public void setAdaptorEnv(AdaptorEnv adaptorEnv) {
280                 this.adaptorEnv = adaptorEnv;
281         }
282
283         @Override
284         public void uploadVnfPackage(String cbamPackageFilePath) throws ClientProtocolException, IOException {
285                 String httpPath = CommonConstants.CbamUploadVnfPackagePath;
286                 RequestMethod method = RequestMethod.POST;
287                 
288                 HttpResult httpResult = operateCbamHttpUploadTask(cbamPackageFilePath, httpPath, method);
289                 String responseStr = httpResult.getContent();
290                 
291                 logger.info("CbamMgmrImpl -> uploadVnfPackage, statusCode is " + httpResult.getStatusCode() + ", cause is " + httpResult.getStatusCause() + ". responseStr is " + responseStr);
292                 
293                 int code = httpResult.getStatusCode();
294                 if(code == 200) {
295                         logger.info("CbamMgmrImpl -> uploadVnfPackage, success" );
296                         logger.info("Upload vnf package " + cbamPackageFilePath + " to CBAM is successful.");
297                 }else {
298                         logger.error("CbamMgmrImpl -> uploadVnfPackage, error" );
299                 }
300         }
301
302         public HttpResult operateCbamHttpUploadTask(String filePath, String httpPath, RequestMethod method) throws ClientProtocolException, IOException {
303                 String token = null;
304                 try {
305                         token = retrieveToken();
306                 } catch (JSONException e) {
307                         logger.error("retrieveTokenError ", e);
308                 }
309                 String url = adaptorEnv.getCbamApiUriFront() + httpPath;
310                 logger.info("start to upload file.");
311                 String command =  "/usr/bin/curl --insecure -X POST -H \"Authorization: bearer " + token + "\" --form content=@" + filePath + " " + url;
312                 StringBuffer respStr = execCommand(command);
313                 
314 //              HashMap<String, String> map = new HashMap<>();
315 //              map.put(CommonConstants.AUTHORIZATION, "bearer " + token);
316 //              map.put(CommonConstants.CONTENT_TYPE, "multipart/form-data, boundary=---CFSGSSGGSGdssdfsdhd---");
317 //              byte[] fileBytes = CommonUtil.getBytes(filePath);
318 //              logger.info("CbamMgmrImpl -> operateCbamHttpUploadTask, url is " + url);
319 //              logger.info("CbamMgmrImpl -> operateCbamHttpUploadTask, token is " + token);
320 //              logger.info("CbamMgmrImpl -> operateCbamHttpUploadTask, bodyPostStr byte lenth is " + fileBytes.length);
321                 
322 //              return httpClientProcessor.processBytes(url, method, map, fileBytes);
323                 
324                 HttpResult hResult = new HttpResult();
325                 hResult.setStatusCause(respStr.toString());
326                 hResult.setContent(respStr.toString());
327                 hResult.setStatusCode(200);
328                 return hResult;
329                 
330 //              String charset = "UTF-8";
331 //        File uploadFile1 = new File(filePath);
332 //        String requestURL = url;
333 //        HttpResult result = new HttpResult();
334 // 
335 //        try {
336 //            MultipartUtility multipart = new MultipartUtility(requestURL, charset);
337 //             
338 //            multipart.addHeaderField("User-Agent", "CodeJava");
339 //            multipart.addHeaderField(CommonConstants.AUTHORIZATION, "bearer " + token);
340 //             
341 //            multipart.addFilePart("fileUpload", uploadFile1);
342 // 
343 //            List<String> response = multipart.finish();
344 //             
345 //            result.setContent(Arrays.deepToString(response.toArray(new String[0])));
346 //            result.setStatusCode(200);
347 //        } catch (Exception ex) {
348 //              logger.error("CbamMgmrImpl -> operateCbamHttpUploadTask, error ", ex);
349 //            result.setStatusCode(500);
350 //        }
351 //        
352 //        return result;
353         }
354
355         private StringBuffer execCommand(String command) {
356                 logger.info("CbamMgmrImpl -> execCommand, command is " + command);
357                 StringBuffer respStr = new StringBuffer("\r\n");
358                 try {
359                         String os = System.getProperty("os.name"); 
360                         String[] cmd = {"cmd", "/c", command};
361                         if(!os.toLowerCase().startsWith("win")){
362                                 cmd = new String[]{"/bin/sh","-c", command};
363                         }  
364                         Process process = Runtime.getRuntime().exec(cmd);
365                         Thread t=new Thread(new InputStreamRunnable(process.getErrorStream(),"ErrorStream"));  
366             t.start(); 
367             Thread.sleep(3000);
368              InputStream fis=process.getInputStream();    
369              InputStreamReader isr=new InputStreamReader(fis);  
370              
371              BufferedReader br=new BufferedReader(isr);    
372              String line = null;
373             while((line = br.readLine())!=null)    
374              {    
375                 respStr.append(line + "\r\n");    
376              }
377             respStr.append("\r\n");
378             process.waitFor();
379             fis.close();
380             isr.close();
381             process.destroy();
382             logger.info("operateCbamHttpUploadTask respStr is: " + respStr);
383                 } catch (Exception e) {
384                         logger.error("operateCbamHttpUploadTask error", e);
385                 }
386                 return respStr;
387         }
388         
389 //      public static String postByHttps(String url, String body, Object contentType) {
390 //          String result = "";
391 //          Protocol https = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443);
392 //          Protocol.registerProtocol("https", https);
393 //          PostMethod post = new PostMethod(url);
394 //          HttpClient client = new HttpClient();
395 //          try {
396 //              post.setRequestHeader("Content-Type", contentType);
397 //              post.setRequestBody(body);
398 //              client.executeMethod(post);
399 //              result = post.getResponseBodyAsString();
400 //              Protocol.unregisterProtocol("https");
401 //              return result;
402 //          } catch (HttpException e) {
403 //              e.printStackTrace();
404 //          } catch (IOException e) {
405 //              e.printStackTrace();
406 //          } catch(Exception e) {
407 //              e.printStackTrace();
408 //          }
409 //       
410 //          return "error";
411 //      }
412
413         public HttpClientProcessorInf getHttpClientProcessor() {
414                 return httpClientProcessor;
415         }
416
417         public void setHttpClientProcessor(HttpClientProcessorInf httpClientProcessor) {
418                 this.httpClientProcessor = httpClientProcessor;
419         }
420 }