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