aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java
blob: 0aca8fb1dc414a932111ad1b71496df77802d6f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*-
 * ============LICENSE_START=======================================================
 * ONAP CLAMP
 * ================================================================================
 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
 *                             reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END============================================
 * ===================================================================
 * 
 */

package org.onap.clamp.clds.client;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.util.Date;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.onap.clamp.clds.config.ClampProperties;
import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException;
import org.onap.clamp.clds.util.LoggingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * This class implements the communication with DCAE for the service
 * deployments.
 */
@Component
public class DcaeDispatcherServices {

    protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);
    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
    @Autowired
    private ClampProperties refProp;
    private static final String STATUS_URL_LOG = "Status URL extracted: ";
    private static final String DCAE_URL_PREFIX = "/dcae-deployments/";
    private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url";
    public static final String DCAE_REQUESTID_PROPERTY_NAME = "dcae.header.requestId";
    private static final String DCAE_LINK_FIELD = "links";
    private static final String DCAE_STATUS_FIELD = "status";

    /**
     * Delete the deployment on DCAE.
     * 
     * @param deploymentId
     *            The deployment ID
     * @return Return the URL Status
     */
    public String deleteDeployment(String deploymentId) {
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "deleteDeployment");
        try {
            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
            String statusUrl = getDcaeResponse(url, "DELETE", null, null, DCAE_LINK_FIELD, DCAE_STATUS_FIELD);
            logger.info(STATUS_URL_LOG + statusUrl);
            LoggingUtils.setResponseContext("0", "Delete deployments success", this.getClass().getName());
            return statusUrl;
        } catch (Exception e) {
            LoggingUtils.setResponseContext("900", "Delete deployments failed", this.getClass().getName());
            LoggingUtils.setErrorContext("900", "Delete deployments error");
            logger.error("Exception occurred during Delete Deployment Operation with DCAE", e);
            throw new DcaeDeploymentException("Exception occurred during Delete Deployment Operation with DCAE", e);
        } finally {
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("deleteDeployment complete");
        }
    }

    public String getOperationStatusWithRetry(String operationStatusUrl) throws InterruptedException {
        String operationStatus = "";
        for (int i = 0; i < Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.limit")); i++) {
            logger.info("Trying to get Operation status on DCAE for url:" + operationStatusUrl);
            operationStatus = getOperationStatus(operationStatusUrl);
            logger.info("Current Status is:" + operationStatus);
            if (!"processing".equalsIgnoreCase(operationStatus)) {
                return operationStatus;
            } else {
                Thread.sleep(Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.interval")));
            }
        }
        logger.warn("Number of attempts on DCAE is over, stopping the getOperationStatus method");
        return operationStatus;
    }

    /**
     * Get the Operation Status from a specified URL.
     * 
     * @param statusUrl
     *            The URL provided by a previous DCAE Query
     * @return The status
     */
    public String getOperationStatus(String statusUrl) {
        // Assigning processing status to monitor operation status further
        String opStatus = "processing";
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "getOperationStatus");
        try {
            String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(statusUrl, "GET", null, null);
            JSONObject jsonObj = parseResponse(responseStr);
            String operationType = (String) jsonObj.get("operationType");
            String status = (String) jsonObj.get(DCAE_STATUS_FIELD);
            logger.info("Operation Type - " + operationType + ", Status " + status);
            LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName());
            opStatus = status;
        } catch (Exception e) {
            LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName());
            LoggingUtils.setErrorContext("900", "Get operation status error");
            logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);
        } finally {
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("getOperationStatus complete");
        }
        return opStatus;
    }

    /**
     * This method send a getDeployments operation to DCAE.
     */
    public void getDeployments() {
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "getDeployments");
        try {
            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX;
            DcaeHttpConnectionManager.doDcaeHttpQuery(url, "GET", null, null);
            LoggingUtils.setResponseContext("0", "Get deployments success", this.getClass().getName());
        } catch (Exception e) {
            LoggingUtils.setResponseContext("900", "Get deployments failed", this.getClass().getName());
            LoggingUtils.setErrorContext("900", "Get deployments error");
            logger.error("Exception occurred during getDeployments Operation with DCAE", e);
            throw new DcaeDeploymentException("Exception occurred during getDeployments Operation with DCAE", e);
        } finally {
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("getDeployments complete");
        }
    }

    /**
     * Returns status URL for createNewDeployment operation.
     *
     * @param deploymentId
     *            The deployment ID
     * @param serviceTypeId
     *            Service type ID
     * @param blueprintInputJson
     *            The value for each blueprint parameters in a flat JSON
     * @return The status URL
     */
    public String createNewDeployment(String deploymentId, String serviceTypeId, JsonNode blueprintInputJson) {
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "createNewDeployment");
        try {
            ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.deployment.template");
            rootNode.put("serviceTypeId", serviceTypeId);
            if (blueprintInputJson != null) {
                rootNode.set("inputs", blueprintInputJson);
            }
            String apiBodyString = rootNode.toString();
            logger.info("Dcae api Body String - " + apiBodyString);
            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
            String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD,
                    DCAE_STATUS_FIELD);
            LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName());
            return statusUrl;
        } catch (Exception e) {
            LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName());
            LoggingUtils.setErrorContext("900", "Create new deployment error");
            logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);
            throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);
        } finally {
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("createNewDeployment complete");
        }
    }

    /***
     * Returns status URL for deleteExistingDeployment operation.
     * 
     * @param deploymentId
     *            The deployment ID
     * @param serviceTypeId
     *            The service Type ID
     * @return The status URL
     */
    public String deleteExistingDeployment(String deploymentId, String serviceTypeId) {
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");
        try {
            String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";
            logger.info("Dcae api Body String - " + apiBodyString);
            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
            String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD,
                    DCAE_STATUS_FIELD);
            LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName());
            return statusUrl;

        } catch (Exception e) {
            LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName());
            LoggingUtils.setErrorContext("900", "Delete existing deployment error");
            logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);
            throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",
                    e);
        } finally {
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("deleteExistingDeployment complete");
        }
    }

    private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node,
            String nodeAttr) throws IOException, ParseException {
        Date startTime = new Date();
        try {
            String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, requestMethod, payload, contentType);
            JSONObject jsonObj = parseResponse(responseStr);
            JSONObject linksObj = (JSONObject) jsonObj.get(node);
            String statusUrl = (String) linksObj.get(nodeAttr);
            logger.info(STATUS_URL_LOG + statusUrl);
            return statusUrl;
        } catch (IOException | ParseException e) {
            logger.error("Exception occurred getting response from DCAE", e);
            throw e;
        } finally {
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("getDcaeResponse complete");
        }
    }

    private JSONObject parseResponse(String responseStr) throws ParseException {
        JSONParser parser = new JSONParser();
        Object obj0 = parser.parse(responseStr);
        JSONObject jsonObj = (JSONObject) obj0;
        return jsonObj;
    }
}