2983c5ef649d8b037150aecc08f7f50566fa08c0
[policy/distribution.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
5  *  Modifications Copyright (C) 2021 Bell Canada.
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  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.distribution.forwarding.lifecycle.api;
24
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.List;
29 import java.util.Map;
30 import javax.ws.rs.client.Entity;
31 import javax.ws.rs.core.HttpHeaders;
32 import javax.ws.rs.core.MediaType;
33 import javax.ws.rs.core.Response;
34 import org.onap.policy.common.endpoints.http.client.HttpClient;
35 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
36 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
37 import org.onap.policy.common.parameters.ParameterService;
38 import org.onap.policy.distribution.forwarding.PolicyForwarder;
39 import org.onap.policy.distribution.forwarding.PolicyForwardingException;
40 import org.onap.policy.models.pap.concepts.PdpDeployPolicies;
41 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
42 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * This class provides an implementation of {@link PolicyForwarder} interface for forwarding the given policies & policy
50  * types to the life cycle api's of policy framework.
51  *
52  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
53  */
54 public class LifecycleApiPolicyForwarder implements PolicyForwarder {
55
56     private static final String DEPLOY_POLICY_URI = "/policy/pap/v1/pdps/policies";
57     private static final String CREATE_POLICY_TYPE_URI = "/policy/api/v1/policytypes/";
58     private static final Logger LOGGER = LoggerFactory.getLogger(LifecycleApiPolicyForwarder.class);
59
60     private LifecycleApiForwarderParameters forwarderParameters;
61     private HttpClient apiClient;
62     private HttpClient papClient;
63
64     /**
65      * {@inheritDoc}.
66      */
67     @Override
68     public void configure(final String parameterGroupName) throws HttpClientConfigException {
69         forwarderParameters = ParameterService.get(parameterGroupName);
70
71         forwarderParameters.getApiParameters().setClientName("policy-api");
72         forwarderParameters.getPapParameters().setClientName("policy-pap");
73
74         apiClient = HttpClientFactoryInstance.getClientFactory().build(forwarderParameters.getApiParameters());
75         papClient = HttpClientFactoryInstance.getClientFactory().build(forwarderParameters.getPapParameters());
76     }
77
78     /**
79      * {@inheritDoc}.
80      */
81     @Override
82     public void forward(final Collection<ToscaEntity> entities) throws PolicyForwardingException {
83         final List<ToscaEntity> failedEntities = new ArrayList<>();
84         for (final ToscaEntity entity : entities) {
85             forwardSingleEntity(failedEntities, entity);
86         }
87         if (!failedEntities.isEmpty()) {
88             throw new PolicyForwardingException(
89                     "Failed forwarding the following entities: " + Arrays.toString(failedEntities.toArray()));
90         }
91     }
92
93     private void forwardSingleEntity(final List<ToscaEntity> failedEntities, final ToscaEntity entity) {
94         Response policyCreated = null;
95         try {
96             if (entity instanceof ToscaServiceTemplate) {
97                 final var toscaServiceTemplate = (ToscaServiceTemplate) entity;
98                 if (null != toscaServiceTemplate.getPolicyTypes() && !toscaServiceTemplate.getPolicyTypes().isEmpty()) {
99                     createPolicyType(toscaServiceTemplate);
100                 }
101                 if (null != toscaServiceTemplate.getToscaTopologyTemplate()
102                         && null != toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()
103                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().isEmpty()
104                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet().isEmpty()) {
105                     policyCreated = createPolicy(toscaServiceTemplate);
106                 }
107                 if (forwarderParameters.isDeployPolicies() && policyCreated != null) {
108                     deployPolicy(policyCreated.readEntity(ToscaServiceTemplate.class));
109                 }
110             } else {
111                 throw new PolicyForwardingException("The entity is not of type ToscaServiceTemplate - " + entity);
112             }
113         } catch (final Exception exp) {
114             LOGGER.error(exp.getMessage(), exp);
115             failedEntities.add(entity);
116         }
117     }
118
119     private Response createPolicyType(final ToscaServiceTemplate toscaServiceTemplate)
120             throws PolicyForwardingException {
121         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON), CREATE_POLICY_TYPE_URI,
122                 true);
123     }
124
125     private Response createPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
126         final ToscaPolicy policy = toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet()
127                 .iterator().next().getValue();
128         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON),
129                 CREATE_POLICY_TYPE_URI + policy.getType() + "/versions/" + policy.getTypeVersion() + "/policies", true);
130     }
131
132     private Response deployPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
133         final var pdpPolicies = new PdpDeployPolicies();
134         final List<ToscaConceptIdentifierOptVersion> policyIdentifierList = new ArrayList<>();
135         for (final Map<String, ToscaPolicy> policyMap : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()) {
136             final String policyId = policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-id");
137             final String policyVersion =
138                     policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-version");
139             final var toscaPolicyIdentifier =
140                     new ToscaConceptIdentifierOptVersion(policyId, policyVersion);
141             policyIdentifierList.add(toscaPolicyIdentifier);
142         }
143         pdpPolicies.setPolicies(policyIdentifierList);
144         return invokeHttpClient(Entity.entity(pdpPolicies, MediaType.APPLICATION_JSON), DEPLOY_POLICY_URI, false);
145     }
146
147     private Response invokeHttpClient(final Entity<?> entity, final String path, final boolean wantApi)
148             throws PolicyForwardingException {
149         Response response = null;
150         try {
151             response = getHttpClient(wantApi).post(path, entity, Map.of(HttpHeaders.ACCEPT,
152                     MediaType.APPLICATION_JSON, HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
153             if (response.getStatus() / 100 != 2) {
154                 LOGGER.error(
155                         "Invocation of path {} failed for entity {}. Response status: {}, Response status info: {}",
156                         path, entity, response.getStatus(), response.getStatusInfo());
157                 throw new PolicyForwardingException("Failed creating the entity - " + entity);
158             }
159         } catch (final HttpClientConfigException exception) {
160             throw new PolicyForwardingException("Invocation of path " + path + " failed for entity " + entity,
161                     exception);
162         }
163         return response;
164     }
165
166     private HttpClient getHttpClient(final boolean wantApi) throws HttpClientConfigException {
167         return (wantApi ? apiClient : papClient);
168     }
169 }
170