d51d33881d1b351decb154ee10436f23b7046776
[usecase-ui/intent-analysis.git] /
1 /*
2  * Copyright 2022 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.onap.usecaseui.intentanalysis.adapters.policy.impl;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.nio.charset.StandardCharsets;
22 import okhttp3.MediaType;
23 import okhttp3.RequestBody;
24 import okhttp3.ResponseBody;
25 import org.apache.commons.io.FileUtils;
26 import org.apache.ibatis.io.Resources;
27 import org.onap.usecaseui.intentanalysis.adapters.policy.PolicyService;
28 import org.onap.usecaseui.intentanalysis.adapters.policy.apicall.PolicyAPICall;
29 import org.onap.usecaseui.intentanalysis.adapters.policy.apicall.PolicyAuthConfig;
30 import org.onap.usecaseui.intentanalysis.util.RestfulServices;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.beans.factory.annotation.Autowired;
34 import org.springframework.stereotype.Service;
35 import retrofit2.Response;
36
37 @Service
38 public class PolicyServiceImpl implements PolicyService {
39
40     private static final Logger logger = LoggerFactory.getLogger(PolicyServiceImpl.class);
41
42     private PolicyAPICall policyAPICall;
43
44     @Autowired
45     PolicyAuthConfig policyAuthConfig;
46
47     public PolicyAPICall getPolicyAPICall() {
48         if (null == policyAPICall) {
49             this.policyAPICall = RestfulServices.create(PolicyAPICall.class, policyAuthConfig.getUserName(),
50                 policyAuthConfig.getPassword());
51         }
52         return this.policyAPICall;
53     }
54
55     public void setPolicyAPICall(PolicyAPICall policyAPICall) {
56         this.policyAPICall = policyAPICall;
57     }
58
59     @Override
60     public boolean createAndDeployModifyCLLPolicy() {
61         try {
62             //Create policy
63             File policyFile = Resources.getResourceAsFile("intentPolicy/modifycll.json");
64             String policyBody = FileUtils.readFileToString(policyFile, StandardCharsets.UTF_8);
65             logger.info(String.format("Create policy, request body: %s", policyBody));
66             RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyBody.toString());
67             Response<ResponseBody> policyResponse = getPolicyAPICall().createPolicy(ModifyCLLPolicyConstants.policyType,
68                 ModifyCLLPolicyConstants.policyTypeVersion, policyReq).execute();
69             logger.info(String.format("Create policy result, code: %d body: %s", policyResponse.code(),
70                 getResponseBodyStr(policyResponse)));
71             if (!policyResponse.isSuccessful()) {
72                 logger.error("Create modify cll policy failed.");
73                 return false;
74             }
75
76             //Deploy policy
77             File deployPolicyFile = Resources.getResourceAsFile("intentPolicy/deploy_modifycll.json");
78             String deployPolicyBody = FileUtils.readFileToString(deployPolicyFile, StandardCharsets.UTF_8);
79             logger.info(String.format("Deploy policy, request body: %s", deployPolicyBody));
80             RequestBody deployPolicyReq = RequestBody.create(MediaType.parse("application/json"),
81                 deployPolicyBody.toString());
82             Response<ResponseBody> deployPolicyResponse = getPolicyAPICall().deployPolicy(deployPolicyReq).execute();
83             logger.info(String.format("Deploy policy result, code: %d body: %s", deployPolicyResponse.code(),
84                 getResponseBodyStr(deployPolicyResponse)));
85             if (!deployPolicyResponse.isSuccessful()) {
86                 logger.error("Deploy modify cll policy failed.");
87                 return false;
88             }
89
90         } catch (IOException e) {
91             logger.error("Exception in create and deploy modify cll policy.", e);
92             return false;
93         }
94         return true;
95     }
96
97     @Override
98     public boolean undeployAndRemoveModifyCLLPolicy() {
99         return undeployAndRemovePolicyIfExist(ModifyCLLPolicyConstants.policyType,
100             ModifyCLLPolicyConstants.policyTypeVersion, ModifyCLLPolicyConstants.policyName,
101             ModifyCLLPolicyConstants.policyVersion);
102     }
103
104     @Override
105     public boolean updateIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus) {
106         //the policy engine does not support update now. so we need to remove and recreate the policy now.
107         logger.info(String.format(
108             "Start to update the intent configuration policy, cllId: %s, originalBW: %s, closedLooopStatus:%b", cllId,
109             originalBW, closedLoopStatus));
110         //remove the configuration policy first
111         boolean res = undeployAndRemovePolicyIfExist(IntentConfigPolicyConstants.policyType,
112             IntentConfigPolicyConstants.policyTypeVersion, IntentConfigPolicyConstants.policyName,
113             IntentConfigPolicyConstants.policyVersion);
114         if (!res) {
115             logger.warn("Undeploy and remove the intent configuration policy failed.");
116         }
117         res = createAndDeployIntentConfigPolicy(cllId, originalBW, closedLoopStatus);
118         if (!res) {
119             logger.error("Create and deploy the intent configuration policy failed.");
120         }
121         logger.info(String.format("update intent configuration finished, result: %b", res));
122         return res;
123     }
124
125     /**
126      * Create and deploy the configuration policy
127      *
128      * @param cllId
129      * @param originalBW
130      * @param closedLoopStatus
131      * @return
132      */
133     public boolean createAndDeployIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus) {
134         try {
135             //Create policy type
136             File policyTypeFile = Resources.getResourceAsFile("intentPolicy/intent_configs_policy_type.json");
137             String policyTypeBody = FileUtils.readFileToString(policyTypeFile, StandardCharsets.UTF_8);
138             logger.info(String.format("Create policy type, request body: %s", policyTypeBody));
139             RequestBody policyTypeReq = RequestBody.create(MediaType.parse("application/json"),
140                 policyTypeBody.toString());
141             Response<ResponseBody> response = getPolicyAPICall().createPolicyType(policyTypeReq).execute();
142             logger.info(String.format("Create policy type result, code: %d body: %s", response.code(),
143                 getResponseBodyStr(response)));
144             if (!response.isSuccessful()) {
145                 logger.error("Create intent configuration policy type failed.");
146                 return false;
147             }
148             //Create policy
149             File policyFile = Resources.getResourceAsFile("intentPolicy/intent_configs_policy.json");
150             String policyBodyTemplate = FileUtils.readFileToString(policyFile, StandardCharsets.UTF_8);
151             String policyBody = policyBodyTemplate.replace("${CLL_ID}", cllId)
152                 .replace("${CLOSED_LOOP_STATUS}", String.valueOf(closedLoopStatus))
153                 .replace("${ORIGINAL_BW}", originalBW);
154             logger.info(String.format("Create policy, request body: %s", policyBody));
155             RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyBody.toString());
156             Response<ResponseBody> policyResponse = getPolicyAPICall().createPolicy(
157                     IntentConfigPolicyConstants.policyType, IntentConfigPolicyConstants.policyTypeVersion, policyReq)
158                 .execute();
159             logger.info(String.format("Create policy result, code: %d body: %s", policyResponse.code(),
160                 getResponseBodyStr(policyResponse)));
161             if (!policyResponse.isSuccessful()) {
162                 logger.error("Create intent configuration policy failed.");
163                 return false;
164             }
165
166             //Deploy policy
167             File deployPolicyFile = Resources.getResourceAsFile("intentPolicy/deploy_intent_configs.json");
168             String deployPolicyBody = FileUtils.readFileToString(deployPolicyFile, StandardCharsets.UTF_8);
169             logger.info(String.format("Deploy policy, request body: %s", deployPolicyBody));
170             RequestBody deployPolicyReq = RequestBody.create(MediaType.parse("application/json"),
171                 deployPolicyBody.toString());
172             Response<ResponseBody> deployPolicyResponse = getPolicyAPICall().deployPolicy(deployPolicyReq).execute();
173             logger.info(String.format("Deploy policy result, code: %d body: %s", deployPolicyResponse.code(),
174                 getResponseBodyStr(deployPolicyResponse)));
175             if (!deployPolicyResponse.isSuccessful()) {
176                 logger.error("Deploy intent configuration policy failed.");
177                 return false;
178             }
179
180         } catch (IOException e) {
181             logger.error("Exception in create and deploy intent config policy.", e);
182             return false;
183         }
184         return true;
185     }
186
187     /**
188      * undeploy and remove the configuration policy
189      *
190      * @return
191      */
192     private boolean undeployAndRemovePolicyIfExist(String policyType, String policyTypeVersion, String policyName,
193         String policyVersion) {
194         try {
195             //check if the policy exists
196             Response<ResponseBody> response = getPolicyAPICall().getPolicy(policyType, policyTypeVersion, policyName,
197                 policyVersion).execute();
198             logger.info(String.format("The policy query result, code: %d body: %s", response.code(),
199                 getResponseBodyStr(response)));
200             // remove the policy if exists.
201             if (response.isSuccessful()) {
202                 logger.info("The policy exists, start to undeploy.");
203                 Response<ResponseBody> undeployResponse = getPolicyAPICall().undeployPolicy(policyName).execute();
204                 logger.info(String.format("Undeploy policy result. code: %d body: %s", undeployResponse.code(),
205                     getResponseBodyStr(undeployResponse)));
206                 logger.info("Start to remove the policy.");
207                 Response<ResponseBody> removeResponse = getPolicyAPICall().removePolicy(policyName, policyVersion)
208                     .execute();
209                 logger.info(String.format("Remove policy result. code: %d body: %s", removeResponse.code(),
210                     getResponseBodyStr(removeResponse)));
211                 return true;
212             }
213             return true;
214
215         } catch (IOException e) {
216             logger.error("Exception in undeploy and remove policy", e);
217             return false;
218         }
219
220     }
221
222     private String getResponseBodyStr(Response<ResponseBody> response) throws IOException {
223         if (response.body() != null) {
224             return response.body().string();
225         }
226         return null;
227     }
228 }