5cd9966dab6854343cf90d3806902ed629c89bc7
[policy/distribution.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.distribution.forwarding.lifecycle.api;
22
23 import com.google.common.collect.ImmutableMap;
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
31 import javax.ws.rs.client.Entity;
32 import javax.ws.rs.core.HttpHeaders;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.Response.Status;
36
37 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
38 import org.onap.policy.common.endpoints.http.client.HttpClient;
39 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
40 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
41 import org.onap.policy.common.gson.GsonMessageBodyHandler;
42 import org.onap.policy.common.parameters.ParameterService;
43 import org.onap.policy.distribution.forwarding.PolicyForwarder;
44 import org.onap.policy.distribution.forwarding.PolicyForwardingException;
45 import org.onap.policy.models.pap.concepts.PdpDeployPolicies;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * This class provides an implementation of {@link PolicyForwarder} interface for forwarding the given policies & policy
55  * types to the life cycle api's of policy framework.
56  *
57  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
58  */
59 public class LifecycleApiPolicyForwarder implements PolicyForwarder {
60
61     private static final String DEPLOY_POLICY_URI = "/policy/pap/v1/pdps/policies";
62     private static final String CREATE_POLICY_TYPE_URI = "/policy/api/v1/policytypes/";
63     private static final Logger LOGGER = LoggerFactory.getLogger(LifecycleApiPolicyForwarder.class);
64     private LifecycleApiForwarderParameters forwarderParameters;
65
66     /**
67      * {@inheritDoc}.
68      */
69     @Override
70     public void configure(final String parameterGroupName) {
71         forwarderParameters = ParameterService.get(parameterGroupName);
72     }
73
74     /**
75      * {@inheritDoc}.
76      */
77     @Override
78     public void forward(final Collection<ToscaEntity> entities) throws PolicyForwardingException {
79         final List<ToscaEntity> failedEntities = new ArrayList<>();
80         for (final ToscaEntity entity : entities) {
81             forwardSingleEntity(failedEntities, entity);
82         }
83         if (!failedEntities.isEmpty()) {
84             throw new PolicyForwardingException(
85                     "Failed forwarding the following entities: " + Arrays.toString(failedEntities.toArray()));
86         }
87     }
88
89     private void forwardSingleEntity(final List<ToscaEntity> failedEntities, final ToscaEntity entity) {
90         Response policyCreated = null;
91         try {
92             if (entity instanceof ToscaServiceTemplate) {
93                 final ToscaServiceTemplate toscaServiceTemplate = (ToscaServiceTemplate) entity;
94                 if (null != toscaServiceTemplate.getPolicyTypes() && !toscaServiceTemplate.getPolicyTypes().isEmpty()) {
95                     createPolicyType(toscaServiceTemplate);
96                 }
97                 if (null != toscaServiceTemplate.getToscaTopologyTemplate()
98                         && null != toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()
99                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().isEmpty()
100                         && !toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet().isEmpty()) {
101                     policyCreated = createPolicy(toscaServiceTemplate);
102                 }
103                 if (forwarderParameters.isDeployPolicies() && policyCreated != null) {
104                     deployPolicy(policyCreated.readEntity(ToscaServiceTemplate.class));
105                 }
106             } else {
107                 throw new PolicyForwardingException("The entity is not of type ToscaServiceTemplate - " + entity);
108             }
109         } catch (final Exception exp) {
110             LOGGER.error(exp.getMessage(), exp);
111             failedEntities.add(entity);
112         }
113     }
114
115     private Response createPolicyType(final ToscaServiceTemplate toscaServiceTemplate)
116             throws PolicyForwardingException {
117         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON), CREATE_POLICY_TYPE_URI,
118                 true);
119     }
120
121     private Response createPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
122         final ToscaPolicy policy = toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).entrySet()
123                 .iterator().next().getValue();
124         return invokeHttpClient(Entity.entity(toscaServiceTemplate, MediaType.APPLICATION_JSON),
125                 CREATE_POLICY_TYPE_URI + policy.getType() + "/versions/" + policy.getTypeVersion() + "/policies", true);
126     }
127
128     private Response deployPolicy(final ToscaServiceTemplate toscaServiceTemplate) throws PolicyForwardingException {
129         final PdpDeployPolicies pdpPolicies = new PdpDeployPolicies();
130         final List<ToscaPolicyIdentifierOptVersion> policyIdentifierList = new ArrayList<>();
131         for (final Map<String, ToscaPolicy> policyMap : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies()) {
132             final String policyId = policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-id");
133             final String policyVersion =
134                     policyMap.entrySet().iterator().next().getValue().getMetadata().get("policy-version");
135             final ToscaPolicyIdentifierOptVersion toscaPolicyIdentifier =
136                     new ToscaPolicyIdentifierOptVersion(policyId, policyVersion);
137             policyIdentifierList.add(toscaPolicyIdentifier);
138         }
139         pdpPolicies.setPolicies(policyIdentifierList);
140         return invokeHttpClient(Entity.entity(pdpPolicies, MediaType.APPLICATION_JSON), DEPLOY_POLICY_URI, false);
141     }
142
143     private Response invokeHttpClient(final Entity<?> entity, final String path, final boolean wantApi)
144             throws PolicyForwardingException {
145         Response response = null;
146         try {
147             response = getHttpClient(wantApi).post(path, entity, ImmutableMap.of(HttpHeaders.ACCEPT,
148                     MediaType.APPLICATION_JSON, HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
149             if (response.getStatus() != Status.OK.getStatusCode()) {
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         } catch (final HttpClientConfigException exception) {
156             LOGGER.error(
157                     "Invocation of path " + path + " failed for entity " + entity + " due to error opening Http client",
158                     exception);
159             throw new PolicyForwardingException("Failed creating the entity - " + entity, exception);
160         }
161         return response;
162     }
163
164     private HttpClient getHttpClient(final boolean wantApi) throws HttpClientConfigException {
165         final boolean https = forwarderParameters.isHttps();
166         final LifecycleApiParameters parameters =
167                 (wantApi ? forwarderParameters.getApiParameters() : forwarderParameters.getPapParameters());
168         final BusTopicParams params = BusTopicParams.builder().clientName("Policy Distribution").useHttps(https)
169                 .hostname(parameters.getHostName()).port(parameters.getPort()).userName(parameters.getUserName())
170                 .password(parameters.getPassword()).serializationProvider(GsonMessageBodyHandler.class.getName())
171                 .build();
172         return HttpClientFactoryInstance.getClientFactory().build(params);
173     }
174 }
175