aboutsummaryrefslogtreecommitdiffstats
path: root/intentanalysis/src/main/java/org/onap/usecaseui/intentanalysis/adapters/policy/impl/PolicyServiceImpl.java
blob: 984afc5372bcbbb228cf190490f5c8809252212a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*
 * Copyright 2022 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.usecaseui.intentanalysis.adapters.policy.impl;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.io.Resources;
import org.onap.usecaseui.intentanalysis.adapters.policy.PolicyService;
import org.onap.usecaseui.intentanalysis.adapters.policy.apicall.PolicyAPICall;
import org.onap.usecaseui.intentanalysis.adapters.policy.apicall.PolicyAuthConfig;
import org.onap.usecaseui.intentanalysis.util.RestfulServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import retrofit2.Response;

@Service
public class PolicyServiceImpl implements PolicyService {

    private static final Logger logger = LoggerFactory.getLogger(PolicyServiceImpl.class);

    private PolicyAPICall policyAPICall;

    @Autowired
    PolicyAuthConfig policyAuthConfig;

    public PolicyAPICall getPolicyAPICall() {
        if (null == policyAPICall) {
            this.policyAPICall = RestfulServices.create(PolicyAPICall.class, policyAuthConfig.getUserName(),
                policyAuthConfig.getPassword());
        }
        return this.policyAPICall;
    }

    @Override
    public boolean createAndDeployModifyCLLPolicy() {
        try {
            //Create policy
            File policyFile = Resources.getResourceAsFile("intentPolicy/modifycll.json");
            String policyBody = FileUtils.readFileToString(policyFile, StandardCharsets.UTF_8);
            logger.info(String.format("Create policy, request body: %s", policyBody));
            RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyBody.toString());
            Response<ResponseBody> policyResponse = getPolicyAPICall().createPolicy(ModifyCLLPolicyConstants.policyType,
                ModifyCLLPolicyConstants.policyTypeVersion, policyReq).execute();
            logger.info(
                String.format("Create policy result, code: %d body: %s", policyResponse.code(), policyResponse.body()));
            if (!policyResponse.isSuccessful()) {
                logger.error("Create modify cll policy failed.");
                return false;
            }

            //Deploy policy
            File deployPolicyFile = Resources.getResourceAsFile("intentPolicy/deploy_modifycll.json");
            String deployPolicyBody = FileUtils.readFileToString(deployPolicyFile, StandardCharsets.UTF_8);
            logger.info(String.format("Deploy policy, request body: %s", deployPolicyBody));
            RequestBody deployPolicyReq = RequestBody.create(MediaType.parse("application/json"),
                deployPolicyBody.toString());
            Response<ResponseBody> deployPolicyResponse = getPolicyAPICall().deployPolicy(deployPolicyReq).execute();
            logger.info(String.format("Deploy policy result, code: %d body: %s", deployPolicyResponse.code(),
                deployPolicyResponse.body()));
            if (!deployPolicyResponse.isSuccessful()) {
                logger.error("Deploy modify cll policy failed.");
                return false;
            }

        } catch (IOException e) {
            logger.error("Exception in create and deploy modify cll policy.", e);
            return false;
        }
        return true;
    }

    @Override
    public boolean undeployAndRemoveModifyCLLPolicy() {
        return undeployAndRemovePolicyIfExist(ModifyCLLPolicyConstants.policyType,
            ModifyCLLPolicyConstants.policyTypeVersion, ModifyCLLPolicyConstants.policyName,
            ModifyCLLPolicyConstants.policyVersion);
    }

    @Override
    public boolean updateIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus) {
        //the policy engine does not support update now. so we need to remove and recreate the policy now.
        logger.info(String.format(
            "Start to update the intent configuration policy, cllId: %s, originalBW: %s, closedLooopStatus:%b", cllId,
            originalBW, closedLoopStatus));
        //remove the configuration policy first
        boolean res = undeployAndRemovePolicyIfExist(IntentConfigPolicyConstants.policyType,
            IntentConfigPolicyConstants.policyTypeVersion, IntentConfigPolicyConstants.policyName,
            IntentConfigPolicyConstants.policyVersion);
        if (!res) {
            logger.warn("Undeploy and remove the intent configuration policy failed.");
        }
        res = createAndDeployIntentConfigPolicy(cllId, originalBW, closedLoopStatus);
        if (!res) {
            logger.error("Create and deploy the intent configuration policy failed.");
        }
        logger.info(String.format("update intent configuration finished, result: %b", res));
        return res;
    }

    /**
     * Create and deploy the configuration policy
     *
     * @param cllId
     * @param originalBW
     * @param closedLoopStatus
     * @return
     */
    public boolean createAndDeployIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus) {
        try {
            //Create policy type
            File policyTypeFile = Resources.getResourceAsFile("intentPolicy/intent_configs_policy_type.json");
            String policyTypeBody = FileUtils.readFileToString(policyTypeFile, StandardCharsets.UTF_8);
            logger.info(String.format("Create policy type, request body: %s", policyTypeBody));
            RequestBody policyTypeReq = RequestBody.create(MediaType.parse("application/json"),
                policyTypeBody.toString());
            Response<ResponseBody> response = getPolicyAPICall().createPolicyType(policyTypeReq).execute();
            logger.info(
                String.format("Create policy type result, code: %d body: %s", response.code(), response.body()));
            if (!response.isSuccessful()) {
                logger.error("Create intent configuration policy type failed.");
                return false;
            }
            //Create policy
            File policyFile = Resources.getResourceAsFile("intentPolicy/intent_configs_policy.json");
            String policyBodyTemplate = FileUtils.readFileToString(policyFile, StandardCharsets.UTF_8);
            String policyBody = policyBodyTemplate.replace("${CLL_ID}", cllId)
                .replace("${CLOSED_LOOP_STATUS}", String.valueOf(closedLoopStatus))
                .replace("${ORIGINAL_BW}", originalBW);
            logger.info(String.format("Create policy, request body: %s", policyBody));
            RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyBody.toString());
            Response<ResponseBody> policyResponse = getPolicyAPICall().createPolicy(IntentConfigPolicyConstants.policyType,
                IntentConfigPolicyConstants.policyTypeVersion, policyReq).execute();
            logger.info(
                String.format("Create policy result, code: %d body: %s", policyResponse.code(), policyResponse.body()));
            if (!policyResponse.isSuccessful()) {
                logger.error("Create intent configuration policy failed.");
                return false;
            }

            //Deploy policy
            File deployPolicyFile = Resources.getResourceAsFile("intentPolicy/deploy_intent_configs.json");
            String deployPolicyBody = FileUtils.readFileToString(deployPolicyFile, StandardCharsets.UTF_8);
            logger.info(String.format("Deploy policy, request body: %s", deployPolicyBody));
            RequestBody deployPolicyReq = RequestBody.create(MediaType.parse("application/json"),
                deployPolicyBody.toString());
            Response<ResponseBody> deployPolicyResponse = getPolicyAPICall().deployPolicy(deployPolicyReq).execute();
            logger.info(String.format("Deploy policy result, code: %d body: %s", deployPolicyResponse.code(),
                deployPolicyResponse.body()));
            if (!deployPolicyResponse.isSuccessful()) {
                logger.error("Deploy intent configuration policy failed.");
                return false;
            }

        } catch (IOException e) {
            logger.error("Exception in create and deploy intent config policy.", e);
            return false;
        }
        return true;
    }

    /**
     * undeploy and remove the configuration policy
     *
     * @return
     */
    private boolean undeployAndRemovePolicyIfExist(String policyType, String policyTypeVersion, String policyName,
        String policyVersion) {
        try {
            //check if the policy exists
            Response<ResponseBody> response = getPolicyAPICall().getPolicy(policyType, policyTypeVersion, policyName,
                policyVersion).execute();
            logger.info(String.format("The policy query result, code: %d body: %s", response.code(), response.body()));
            // remove the policy if exists.
            if (response.isSuccessful()) {
                logger.info("The policy exists, start to undeploy.");
                Response<ResponseBody> undeployResponse = getPolicyAPICall().undeployPolicy(policyName).execute();
                logger.info(String.format("Undeploy policy result. code: %d body: %s", undeployResponse.code(),
                    undeployResponse.body()));
                logger.info("Start to remove the policy.");
                Response<ResponseBody> removeResponse = getPolicyAPICall().removePolicy(policyName, policyVersion).execute();
                logger.info(String.format("Remove policy result. code: %d body: %s", removeResponse.code(),
                    removeResponse.body()));
                return true;
            }
            return true;

        } catch (IOException e) {
            logger.error("Exception in undeploy and remove policy", e);
            return false;
        }

    }
}