984afc5372bcbbb228cf190490f5c8809252212a
[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     @Override
56     public boolean createAndDeployModifyCLLPolicy() {
57         try {
58             //Create policy
59             File policyFile = Resources.getResourceAsFile("intentPolicy/modifycll.json");
60             String policyBody = FileUtils.readFileToString(policyFile, StandardCharsets.UTF_8);
61             logger.info(String.format("Create policy, request body: %s", policyBody));
62             RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyBody.toString());
63             Response<ResponseBody> policyResponse = getPolicyAPICall().createPolicy(ModifyCLLPolicyConstants.policyType,
64                 ModifyCLLPolicyConstants.policyTypeVersion, policyReq).execute();
65             logger.info(
66                 String.format("Create policy result, code: %d body: %s", policyResponse.code(), policyResponse.body()));
67             if (!policyResponse.isSuccessful()) {
68                 logger.error("Create modify cll policy failed.");
69                 return false;
70             }
71
72             //Deploy policy
73             File deployPolicyFile = Resources.getResourceAsFile("intentPolicy/deploy_modifycll.json");
74             String deployPolicyBody = FileUtils.readFileToString(deployPolicyFile, StandardCharsets.UTF_8);
75             logger.info(String.format("Deploy policy, request body: %s", deployPolicyBody));
76             RequestBody deployPolicyReq = RequestBody.create(MediaType.parse("application/json"),
77                 deployPolicyBody.toString());
78             Response<ResponseBody> deployPolicyResponse = getPolicyAPICall().deployPolicy(deployPolicyReq).execute();
79             logger.info(String.format("Deploy policy result, code: %d body: %s", deployPolicyResponse.code(),
80                 deployPolicyResponse.body()));
81             if (!deployPolicyResponse.isSuccessful()) {
82                 logger.error("Deploy modify cll policy failed.");
83                 return false;
84             }
85
86         } catch (IOException e) {
87             logger.error("Exception in create and deploy modify cll policy.", e);
88             return false;
89         }
90         return true;
91     }
92
93     @Override
94     public boolean undeployAndRemoveModifyCLLPolicy() {
95         return undeployAndRemovePolicyIfExist(ModifyCLLPolicyConstants.policyType,
96             ModifyCLLPolicyConstants.policyTypeVersion, ModifyCLLPolicyConstants.policyName,
97             ModifyCLLPolicyConstants.policyVersion);
98     }
99
100     @Override
101     public boolean updateIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus) {
102         //the policy engine does not support update now. so we need to remove and recreate the policy now.
103         logger.info(String.format(
104             "Start to update the intent configuration policy, cllId: %s, originalBW: %s, closedLooopStatus:%b", cllId,
105             originalBW, closedLoopStatus));
106         //remove the configuration policy first
107         boolean res = undeployAndRemovePolicyIfExist(IntentConfigPolicyConstants.policyType,
108             IntentConfigPolicyConstants.policyTypeVersion, IntentConfigPolicyConstants.policyName,
109             IntentConfigPolicyConstants.policyVersion);
110         if (!res) {
111             logger.warn("Undeploy and remove the intent configuration policy failed.");
112         }
113         res = createAndDeployIntentConfigPolicy(cllId, originalBW, closedLoopStatus);
114         if (!res) {
115             logger.error("Create and deploy the intent configuration policy failed.");
116         }
117         logger.info(String.format("update intent configuration finished, result: %b", res));
118         return res;
119     }
120
121     /**
122      * Create and deploy the configuration policy
123      *
124      * @param cllId
125      * @param originalBW
126      * @param closedLoopStatus
127      * @return
128      */
129     public boolean createAndDeployIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus) {
130         try {
131             //Create policy type
132             File policyTypeFile = Resources.getResourceAsFile("intentPolicy/intent_configs_policy_type.json");
133             String policyTypeBody = FileUtils.readFileToString(policyTypeFile, StandardCharsets.UTF_8);
134             logger.info(String.format("Create policy type, request body: %s", policyTypeBody));
135             RequestBody policyTypeReq = RequestBody.create(MediaType.parse("application/json"),
136                 policyTypeBody.toString());
137             Response<ResponseBody> response = getPolicyAPICall().createPolicyType(policyTypeReq).execute();
138             logger.info(
139                 String.format("Create policy type result, code: %d body: %s", response.code(), response.body()));
140             if (!response.isSuccessful()) {
141                 logger.error("Create intent configuration policy type failed.");
142                 return false;
143             }
144             //Create policy
145             File policyFile = Resources.getResourceAsFile("intentPolicy/intent_configs_policy.json");
146             String policyBodyTemplate = FileUtils.readFileToString(policyFile, StandardCharsets.UTF_8);
147             String policyBody = policyBodyTemplate.replace("${CLL_ID}", cllId)
148                 .replace("${CLOSED_LOOP_STATUS}", String.valueOf(closedLoopStatus))
149                 .replace("${ORIGINAL_BW}", originalBW);
150             logger.info(String.format("Create policy, request body: %s", policyBody));
151             RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyBody.toString());
152             Response<ResponseBody> policyResponse = getPolicyAPICall().createPolicy(IntentConfigPolicyConstants.policyType,
153                 IntentConfigPolicyConstants.policyTypeVersion, policyReq).execute();
154             logger.info(
155                 String.format("Create policy result, code: %d body: %s", policyResponse.code(), policyResponse.body()));
156             if (!policyResponse.isSuccessful()) {
157                 logger.error("Create intent configuration policy failed.");
158                 return false;
159             }
160
161             //Deploy policy
162             File deployPolicyFile = Resources.getResourceAsFile("intentPolicy/deploy_intent_configs.json");
163             String deployPolicyBody = FileUtils.readFileToString(deployPolicyFile, StandardCharsets.UTF_8);
164             logger.info(String.format("Deploy policy, request body: %s", deployPolicyBody));
165             RequestBody deployPolicyReq = RequestBody.create(MediaType.parse("application/json"),
166                 deployPolicyBody.toString());
167             Response<ResponseBody> deployPolicyResponse = getPolicyAPICall().deployPolicy(deployPolicyReq).execute();
168             logger.info(String.format("Deploy policy result, code: %d body: %s", deployPolicyResponse.code(),
169                 deployPolicyResponse.body()));
170             if (!deployPolicyResponse.isSuccessful()) {
171                 logger.error("Deploy intent configuration policy failed.");
172                 return false;
173             }
174
175         } catch (IOException e) {
176             logger.error("Exception in create and deploy intent config policy.", e);
177             return false;
178         }
179         return true;
180     }
181
182     /**
183      * undeploy and remove the configuration policy
184      *
185      * @return
186      */
187     private boolean undeployAndRemovePolicyIfExist(String policyType, String policyTypeVersion, String policyName,
188         String policyVersion) {
189         try {
190             //check if the policy exists
191             Response<ResponseBody> response = getPolicyAPICall().getPolicy(policyType, policyTypeVersion, policyName,
192                 policyVersion).execute();
193             logger.info(String.format("The policy query result, code: %d body: %s", response.code(), response.body()));
194             // remove the policy if exists.
195             if (response.isSuccessful()) {
196                 logger.info("The policy exists, start to undeploy.");
197                 Response<ResponseBody> undeployResponse = getPolicyAPICall().undeployPolicy(policyName).execute();
198                 logger.info(String.format("Undeploy policy result. code: %d body: %s", undeployResponse.code(),
199                     undeployResponse.body()));
200                 logger.info("Start to remove the policy.");
201                 Response<ResponseBody> removeResponse = getPolicyAPICall().removePolicy(policyName, policyVersion).execute();
202                 logger.info(String.format("Remove policy result. code: %d body: %s", removeResponse.code(),
203                     removeResponse.body()));
204                 return true;
205             }
206             return true;
207
208         } catch (IOException e) {
209             logger.error("Exception in undeploy and remove policy", e);
210             return false;
211         }
212
213     }
214 }