Made network.log output more verbose.
[policy/drools-applications.git] / controlloop / common / model-impl / so / src / main / java / org / onap / policy / so / SOManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * mso
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.so;
22
23 import java.util.Base64;
24 import java.util.HashMap;
25 import java.util.Map;
26
27 import org.onap.policy.so.util.Serialization;
28 import org.onap.policy.drools.system.PolicyEngine;
29 import org.onap.policy.rest.RESTManager;
30 import org.onap.policy.rest.RESTManager.Pair;
31 import org.drools.core.WorkingMemory;
32
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.gson.Gson;
40 import com.google.gson.GsonBuilder;
41 import com.google.gson.JsonSyntaxException;
42
43 public final class SOManager {
44
45         private static final Logger logger = LoggerFactory.getLogger(SOManager.class);
46         private static final Logger netLogger = LoggerFactory.getLogger(org.onap.policy.drools.event.comm.Topic.NETWORK_LOGGER);
47         private static ExecutorService executors = Executors.newCachedThreadPool();
48                 
49         public static SOResponse createModuleInstance(String url, String urlBase, String username, String password, SORequest request) {
50                 
51                 //
52                 // Call REST
53                 //
54                 Map<String, String> headers = new HashMap<String, String>();
55                 //headers.put("X-FromAppId", "POLICY");
56                 //headers.put("X-TransactionId", requestID.toString());
57                 headers.put("Accept", "application/json");
58                 
59                 //
60                 // 201 - CREATED - you are done just return 
61                 //
62                 String requestJson = Serialization.gsonPretty.toJson(request);
63                 netLogger.info("[OUT|{}|{}|]{}{}", "SO", url, System.lineSeparator(), requestJson);
64                 Pair<Integer, String> httpDetails = RESTManager.post(url, username, password, headers, "application/json", requestJson);
65                 
66                 if (httpDetails == null) {
67                         return null;
68                 }
69                 
70                 if (httpDetails.a == 202) {
71                         try {
72                                 SOResponse response = Serialization.gsonPretty.fromJson(httpDetails.b, SOResponse.class);
73                                 
74                                 String body = Serialization.gsonPretty.toJson(response);
75                                 logger.debug("***** Response to post:");
76                                 logger.debug(body);
77                                 
78                                 String requestId = response.requestReferences.requestId;
79                                 int attemptsLeft = 20;
80                                 
81                                 //String getUrl = "/orchestrationRequests/v2/"+requestId;
82                                 String urlGet = urlBase + "/orchestrationRequests/v2/"+requestId;
83                                 SOResponse responseGet = null;
84                                 
85                                 while(attemptsLeft-- > 0){
86                                         
87                                         Pair<Integer, String> httpDetailsGet = RESTManager.get(urlGet, username, password, headers);
88                                         responseGet = Serialization.gsonPretty.fromJson(httpDetailsGet.b, SOResponse.class);
89                                         netLogger.info("[IN|{}|{}|]{}{}", "SO", urlGet, System.lineSeparator(), httpDetailsGet.b);
90                     
91                                         body = Serialization.gsonPretty.toJson(responseGet);
92                                         logger.debug("***** Response to get:");
93                                         logger.debug(body);
94                                         
95                                         if(httpDetailsGet.a == 200){
96                                                 if(responseGet.request.requestStatus.requestState.equalsIgnoreCase("COMPLETE") || 
97                                                                 responseGet.request.requestStatus.requestState.equalsIgnoreCase("FAILED")){
98                                                         logger.debug("***** ########  VF Module Creation "+responseGet.request.requestStatus.requestState);
99                                                         return responseGet;
100                                                 }
101                                         }
102                                         Thread.sleep(20000);
103                                 }
104
105                                 if (responseGet != null
106                                  && responseGet.request != null
107                                  &&     responseGet.request.requestStatus != null
108                                  && responseGet.request.requestStatus.requestState != null) {
109                                         logger.warn("***** ########  VF Module Creation timeout. Status: ( {})", responseGet.request.requestStatus.requestState);
110                                 }
111
112                                 return responseGet;
113                         } catch (JsonSyntaxException e) {
114                                 logger.error("Failed to deserialize into SOResponse: ", e);
115                         } catch (InterruptedException e) {
116                                 logger.error("Interrupted exception: ", e);
117                                 Thread.currentThread().interrupt();
118                         }
119                 }
120                 
121                 
122                 
123                 
124                 return null;
125         }
126
127         /**
128          * 
129          * @param wm
130          * @param url
131          * @param urlBase
132          * @param username
133          * @param password
134          * @param request
135          * 
136          * This method makes an asynchronous Rest call to MSO and inserts the response into the Drools working memory
137          */
138           public void asyncSORestCall(WorkingMemory wm, String serviceInstanceId, String vnfInstanceId, SORequest request) {
139                   executors.submit(new Runnable()
140                         {
141                           @Override
142                                 public void run()
143                           {
144                                   try {
145                                           String serverRoot = PolicyEngine.manager.getEnvironmentProperty("so.url");
146                                           String username = PolicyEngine.manager.getEnvironmentProperty("so.username");
147                                           String password = PolicyEngine.manager.getEnvironmentProperty("so.password");
148                                           
149                                           String url = serverRoot + "/serviceInstances/v5/" + serviceInstanceId + "/vnfs/" + vnfInstanceId + "/vfModulesHTTPS/1.1";
150                                           
151                                           String auth = username + ":" + password;
152                                           
153                                           Map<String, String> headers = new HashMap<String, String>();
154                                           byte[] encodedBytes = Base64.getEncoder().encode(auth.getBytes());
155                                           headers.put("Accept", "application/json");
156                                           headers.put("Authorization", "Basic " + new String(encodedBytes));
157                                           
158                                           Gson gsonPretty = new GsonBuilder().disableHtmlEscaping()
159                                                           .setPrettyPrinting()
160                                                           .create();
161                                           
162                                           String soJson = gsonPretty.toJson(request);
163                                           
164                                           SOResponse so = new SOResponse();
165                                           netLogger.info("[OUT|{}|{}|]{}{}", "SO", url, System.lineSeparator(), soJson);
166                                           Pair<Integer, String> httpResponse = RESTManager.post(url, "policy", "policy", headers, "application/json", soJson);
167                                           
168                                           if (httpResponse != null) {
169                                                   netLogger.info("[IN|{}|{}|]{}{}", url, "SO", System.lineSeparator(), httpResponse.b);
170                                                   
171                                                   Gson gson = new Gson();
172                                                   so = gson.fromJson(httpResponse.b, SOResponse.class);
173                                                   so.httpResponseCode = httpResponse.a;
174                                           } else {
175                                                   logger.error("SO Response returned null.");
176                                                   so.httpResponseCode = 999;
177                                           }
178                                           
179                                           wm.insert(so);
180                                           logger.info("SOResponse inserted " + gsonPretty.toJson(so));
181                                   } catch (Exception e) {
182                                           logger.error("Error while performing asyncSORestCall: "+ e.getMessage(),e);
183                                           
184                                           // create dummy SO object to trigger cleanup
185                                           SOResponse so = new SOResponse();
186                                           so.httpResponseCode = 999;
187                                           wm.insert(so);
188                                   }
189                           }
190                         });
191           }
192
193 }