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