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