Set all cross references of policy/pap
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / rest / PdpGroupDeployControllerV1.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
7  * Modifications Copyright (C) 2022-2023 Nordix Foundation.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.rest;
24
25 import io.micrometer.core.instrument.MeterRegistry;
26 import io.micrometer.core.instrument.Timer;
27 import java.time.Duration;
28 import java.time.Instant;
29 import java.util.UUID;
30 import lombok.RequiredArgsConstructor;
31 import org.onap.policy.common.utils.resources.PrometheusUtils;
32 import org.onap.policy.models.base.PfModelException;
33 import org.onap.policy.models.base.PfModelRuntimeException;
34 import org.onap.policy.models.pap.concepts.PdpDeployPolicies;
35 import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse;
36 import org.onap.policy.models.pdp.concepts.DeploymentGroups;
37 import org.onap.policy.models.pdp.concepts.PdpPolicyStatus;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.context.annotation.Profile;
42 import org.springframework.http.ResponseEntity;
43 import org.springframework.web.bind.annotation.RestController;
44
45 /**
46  * Class to provide REST end points for PAP component to deploy a PDP group.
47  */
48 @RestController
49 @RequiredArgsConstructor
50 @Profile("default")
51 public class PdpGroupDeployControllerV1 extends PapRestControllerV1 implements PdpGroupDeployControllerV1Api {
52     public static final String POLICY_STATUS_URI = "/policy/pap/v1/policies/status";
53
54     public static final String DEPLOYMENT_RESPONSE_MSG = "Use the policy status url to fetch the latest status. "
55             + "Kindly note that when a policy is successfully undeployed,"
56             + " it will no longer appear in policy status response.";
57
58     private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeployControllerV1.class);
59
60     private final PdpGroupDeployProvider provider;
61     private Timer deploySuccessTimer;
62     private Timer deployFailureTimer;
63
64
65     @Autowired
66     public PdpGroupDeployControllerV1(PdpGroupDeployProvider provider, MeterRegistry meterRegistry) {
67         this.provider = provider;
68         initMetrics(meterRegistry);
69     }
70
71     /**
72      * Initializes the metrics for delete operation.
73      *
74      * @param meterRegistry spring bean for MeterRegistry to add the new metric
75      */
76     public void initMetrics(MeterRegistry meterRegistry) {
77         String metricName = String.join(".", "pap", "policy", "deployments");
78         String description = "Timer for HTTP request to deploy/undeploy a policy";
79         deploySuccessTimer = Timer.builder(metricName).description(description)
80             .tags(PrometheusUtils.OPERATION_METRIC_LABEL, PrometheusUtils.DEPLOY_OPERATION,
81                 PrometheusUtils.STATUS_METRIC_LABEL, PdpPolicyStatus.State.SUCCESS.name())
82             .register(meterRegistry);
83         deployFailureTimer = Timer.builder(metricName).description(description)
84             .tags(PrometheusUtils.OPERATION_METRIC_LABEL, PrometheusUtils.DEPLOY_OPERATION,
85                 PrometheusUtils.STATUS_METRIC_LABEL, PdpPolicyStatus.State.FAILURE.name())
86             .register(meterRegistry);
87     }
88
89     /**
90      * Updates policy deployments within specific PDP groups.
91      *
92      * @param requestId request ID used in ONAP logging
93      * @param groups PDP group configuration
94      * @return a response
95      */
96     @Override
97     public ResponseEntity<PdpGroupDeployResponse> updateGroupPolicies(UUID requestId, DeploymentGroups groups) {
98         return doOperation(requestId, "update policy deployments failed",
99             () -> provider.updateGroupPolicies(groups, getPrincipal()));
100     }
101
102     /**
103      * Deploys or updates PDP policies.
104      *
105      * @param requestId request ID used in ONAP logging
106      * @param policies PDP policies
107      * @return a response
108      */
109     @Override
110     public ResponseEntity<PdpGroupDeployResponse> deployPolicies(UUID requestId, PdpDeployPolicies policies) {
111         return doOperation(requestId, "deploy policies failed",
112             () -> provider.deployPolicies(policies, getPrincipal()));
113     }
114
115     /**
116      * Invokes an operation.
117      *
118      * @param requestId request ID
119      * @param errmsg error message to log if the operation throws an exception
120      * @param runnable operation to invoke
121      * @return a {@link PdpGroupDeployResponse} response entity
122      */
123     private ResponseEntity<PdpGroupDeployResponse> doOperation(UUID requestId, String errmsg,
124         RunnableWithPfEx runnable) {
125         Instant start = Instant.now();
126         try {
127             runnable.run();
128             deploySuccessTimer.record(Duration.between(start, Instant.now()));
129             return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.accepted()), requestId)
130                 .body(new PdpGroupDeployResponse(DEPLOYMENT_RESPONSE_MSG, POLICY_STATUS_URI));
131
132         } catch (PfModelException | PfModelRuntimeException e) {
133             logger.warn(errmsg, e);
134             var resp = new PdpGroupDeployResponse();
135             resp.setErrorDetails(e.getErrorResponse().getErrorMessage());
136             deployFailureTimer.record(Duration.between(start, Instant.now()));
137             return addLoggingHeaders(
138                 addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())),
139                 requestId).body(resp);
140         }
141     }
142
143 }