8640332d17565cc3b54580b7cd16c8bc50a67f8f
[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         apiClient = HttpClientFactoryInstance.getClientFactory().build(forwarderParameters.getApiParameters());
72         papClient = HttpClientFactoryInstance.getClientFactory().build(forwarderParameters.getPapParameters());
73     }
74
75     /**
76      * {@inheritDoc}.
77      */
78     @Override
79     public void forward(final Collection<ToscaEntity> entities) throws PolicyForwardingException {
80         final List<ToscaEntity> failedEntities = new ArrayList<>();
81         for (final ToscaEntity entity : entities) {
82             forwardSingleEntity(failedEntities, entity);
83         }
84         if (!failedEntities.isEmpty()) {
85             throw new PolicyForwardingException(
86                     "Failed forwarding the following entities: " + Arrays.toString(failedEntities.toArray()));
87         }
88     }
89
90     private void forwardSingleEntity(final List<ToscaEntity> failedEntities, final ToscaEntity entity) {
91         Response policyCreated = null;
92         try {
93             if (entity instanceof ToscaServiceTemplate) {
94                 final var toscaServiceTemplate = (ToscaServiceTemplate) entity;
95                 if (null != toscaServiceTemplate.getPolicyTypes() && !toscaServiceTemplate.getPolicyTypes().isEmpty()) {
96                     createPolicyType(toscaServiceTemplate);
97                 }
98                 if (null != toscaServiceTemplate.getToscaTopologyTemplate()
99                         && null != toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()
100                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().isEmpty()
101                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet().isEmpty()) {
102                     policyCreated = createPolicy(toscaServiceTemplate);
103                 }
104                 if (forwarderParameters.isDeployPolicies() && policyCreated != null) {
105                     deployPolicy(policyCreated.readEntity(ToscaServiceTemplate.class));
106                 }
107             } else {
108                 throw new PolicyForwardingException("The entity is not of type ToscaServiceTemplate - " + entity);
109             }
110         } catch (final Exception exp) {
111             LOGGER.error(exp.getMessage(), exp);
112             failedEntities.add(entity);
113         }
114     }
115
116     private Response createPolicyType(final ToscaServiceTemplate toscaServiceTemplate)
117             throws PolicyForwardingException {
118         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON), CREATE_POLICY_TYPE_URI,
119                 true);
120     }
121
122     private Response createPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
123         final ToscaPolicy policy = toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet()
124                 .iterator().next().getValue();
125         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON),
126                 CREATE_POLICY_TYPE_URI + policy.getType() + "/versions/" + policy.getTypeVersion() + "/policies", true);
127     }
128
129     private Response deployPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
130         final var pdpPolicies = new PdpDeployPolicies();
131         final List<ToscaConceptIdentifierOptVersion> policyIdentifierList = new ArrayList<>();
132         for (final Map<String, ToscaPolicy> policyMap : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()) {
133             final String policyId = policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-id");
134             final String policyVersion =
135                     policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-version");
136             final var toscaPolicyIdentifier =
137                     new ToscaConceptIdentifierOptVersion(policyId, policyVersion);
138             policyIdentifierList.add(toscaPolicyIdentifier);
139         }
140         pdpPolicies.setPolicies(policyIdentifierList);
141         return invokeHttpClient(Entity.entity(pdpPolicies, MediaType.APPLICATION_JSON), DEPLOY_POLICY_URI, false);
142     }
143
144     private Response invokeHttpClient(final Entity<?> entity, final String path, final boolean wantApi)
145             throws PolicyForwardingException {
146         Response response = getHttpClient(wantApi).post(path, entity, Map.of(HttpHeaders.ACCEPT,
147                         MediaType.APPLICATION_JSON, HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
148         if (response.getStatus() / 100 != 2) {
149             LOGGER.error(
150                     "Invocation of path {} failed for entity {}. Response status: {}, Response status info: {}",
151                     path, entity, response.getStatus(), response.getStatusInfo());
152             throw new PolicyForwardingException("Failed creating the entity - " + entity);
153         }
154         return response;
155     }
156
157     private HttpClient getHttpClient(final boolean wantApi) {
158         return (wantApi ? apiClient : papClient);
159     }
160 }
161