aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java
blob: 5f215968165e2f90e28237ca6fe010ffbce553c6 (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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*-
 * ============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.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;

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

import javax.ws.rs.BadRequestException;

import org.json.simple.JSONArray;
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.dao.CldsDao;
import org.onap.clamp.clds.model.CldsEvent;
import org.onap.clamp.clds.model.CldsModel;
import org.onap.clamp.clds.model.DcaeEvent;
import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
import org.onap.clamp.clds.model.properties.Global;
import org.onap.clamp.clds.model.properties.ModelProperties;
import org.onap.clamp.clds.util.JacksonUtils;
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 inventory.
 */
@Component
public class DcaeInventoryServices {

    protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);
    protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
    public static final String DCAE_INVENTORY_URL = "dcae.inventory.url";
    public static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";
    public static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";
    public static final String DCAE_TYPE_NAME = "typeName";
    public static final String DCAE_TYPE_ID = "typeId";
    @Autowired
    private ClampProperties refProp;
    @Autowired
    private CldsDao cldsDao;

    /**
     * Set the event inventory.
     * 
     * @param cldsModel
     *            The CldsModel
     * @param userId
     *            The user ID
     * @throws ParseException
     *             In case of DCAE Json parse exception
     */
    public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException, InterruptedException {
        String artifactName = cldsModel.getControlName();
        DcaeEvent dcaeEvent = new DcaeEvent();
        DcaeInventoryResponse dcaeResponse = null;
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "setEventInventory");
        if (artifactName != null) {
            artifactName = artifactName + ".yml";
        }
        try {
            // Below are the properties required for calling the dcae inventory
            ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,
                    "{}", cldsModel.getPropText());
            Global global = prop.getGlobal();
            String invariantServiceUuid = global.getService();
            List<String> resourceUuidList = global.getResourceVf();
            String resourceUuid = "";
            if (resourceUuidList != null && !resourceUuidList.isEmpty()) {
                resourceUuid = resourceUuidList.get(0);
            }
            /* Inventory service url is called in this method */
            dcaeResponse = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);
            /* set dcae events */
            dcaeEvent.setArtifactName(artifactName);
            dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);
            LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName());
        } catch (JsonProcessingException e) {
            LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());
            LoggingUtils.setErrorContext("900", "Set inventory error");
            logger.error("Error during JSON decoding", e);
        } catch (IOException ex) {
            LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());
            LoggingUtils.setErrorContext("900", "Set inventory error");
            logger.error("Error during DCAE communication", ex);
        } finally {
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("setEventInventory complete");
        }
        this.analyzeAndSaveDcaeResponse(dcaeResponse, cldsModel, dcaeEvent, userId);
    }

    private void analyzeAndSaveDcaeResponse(DcaeInventoryResponse dcaeResponse, CldsModel cldsModel,
            DcaeEvent dcaeEvent, String userId) {
        if (dcaeResponse != null) {
            logger.info("Dcae Response for query on inventory: " + dcaeResponse);
            String oldTypeId = cldsModel.getTypeId();
            if (dcaeResponse.getTypeId() != null) {
                cldsModel.setTypeId(dcaeResponse.getTypeId());
            }
            if (dcaeResponse.getTypeName() != null) {
                cldsModel.setTypeName(dcaeResponse.getTypeName());
            }
            if (oldTypeId == null || !cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_DISTRIBUTE)
                    || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) {
                CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),
                        CldsEvent.ACTION_STATE_RECEIVED, null);
            }
            cldsModel.save(cldsDao, userId);
        } else {
            logger.info(cldsModel.getName() + " Model is not present in Dcae Inventory Service.");
        }
    }

    private int getTotalCountFromDcaeInventoryResponse(String responseStr) throws ParseException {
        JSONParser parser = new JSONParser();
        Object obj0 = parser.parse(responseStr);
        JSONObject jsonObj = (JSONObject) obj0;
        Long totalCount = (Long) jsonObj.get("totalCount");
        return totalCount.intValue();
    }

    private DcaeInventoryResponse getItemsFromDcaeInventoryResponse(String responseStr)
            throws ParseException, IOException {
        JSONParser parser = new JSONParser();
        Object obj0 = parser.parse(responseStr);
        JSONObject jsonObj = (JSONObject) obj0;
        JSONArray itemsArray = (JSONArray) jsonObj.get("items");
        JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);
        return JacksonUtils.getObjectMapperInstance().readValue(dcaeServiceType0.toString(),
                DcaeInventoryResponse.class);
    }

    /**
     * DO a query to DCAE to get some Information.
     * 
     * @param artifactName
     *            The artifact Name
     * @param serviceUuid
     *            The service UUID
     * @param resourceUuid
     *            The resource UUID
     * @return The DCAE inventory for the artifact in DcaeInventoryResponse
     * @throws IOException
     *             In case of issues with the stream
     * @throws ParseException
     *             In case of issues with the Json parsing
     */
    public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)
            throws IOException, ParseException, InterruptedException {
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");
        String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="
                + artifactName;
        String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types" + queryString;
        logger.info("Dcae Inventory Service full url - " + fullUrl);
        DcaeInventoryResponse response = queryDcaeInventory(fullUrl);
        LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());
        LoggingUtils.setTimeContext(startTime, new Date());
        return response;
    }

    private DcaeInventoryResponse queryDcaeInventory(String fullUrl)
            throws IOException, InterruptedException, ParseException {
        int retryInterval = 0;
        int retryLimit = 1;
        if (refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT) != null) {
            retryLimit = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT));
        }
        if (refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL) != null) {
            retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL));
        }
        for (int i = 0; i < retryLimit; i++) {
            metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory");
            String response = DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);
            int totalCount = getTotalCountFromDcaeInventoryResponse(response);
            metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);
            if (totalCount > 0) {
                logger.info("getDcaeInformation, answer from DCAE inventory:" + response);
                return getItemsFromDcaeInventoryResponse(response);
            }
            logger.info(
                    "Dcae inventory totalCount returned is 0, so waiting " + retryInterval + "ms before retrying ...");
            // wait for a while and try to connect to DCAE again
            Thread.sleep(retryInterval);
        }
        logger.warn("Dcae inventory totalCount returned is still 0, after " + retryLimit + " attempts, returning NULL");
        return null;
    }

    /**
     * Inserts a new DCAEServiceType or updates an existing instance. If the
     * typeName is same second time(already exists) then the
     * DCAEServiceTypeRequest is updated
     * 
     * @param blueprintTemplate
     *            blueprint content
     * @param owner
     *            owner of the data
     * @param typeName
     *            The type/artifact Name
     * @param typeVersion
     *            type version
     * @param asdcServiceId
     *            The service UUID
     * @param asdcResourceId
     *            The vf UUID
     * @return The DCAE inventory type id
     */
    public String createupdateDCAEServiceType(String blueprintTemplate, String owner, String typeName, int typeVersion,
            String asdcServiceId, String asdcResourceId) {
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "createDCAEServiceType");
        String typeId = null;
        try {
            ObjectNode dcaeServiceTypeRequest = JacksonUtils.getObjectMapperInstance().createObjectNode();
            dcaeServiceTypeRequest.put("blueprintTemplate", blueprintTemplate);
            dcaeServiceTypeRequest.put("owner", owner);
            dcaeServiceTypeRequest.put("typeName", typeName);
            dcaeServiceTypeRequest.put("typeVersion", typeVersion);
            dcaeServiceTypeRequest.put("asdcServiceId", asdcServiceId);
            dcaeServiceTypeRequest.put("asdcResourceId", asdcResourceId);
            String apiBodyString = dcaeServiceTypeRequest.toString();
            logger.info("Dcae api Body String - " + apiBodyString);
            String url = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types";
            String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "POST", apiBodyString,
                    "application/json");
            // If the DCAEServiceTypeRequest is created successfully it will
            // return a json object responce containing a node for newly created
            // "typeId"
            // The newly generated DCAEServiceTypeRequest can then be accessed
            // via URL: https://<DCAE_INVENTORY_URL>/dcae-service-types/<typeId>
            JSONParser parser = new JSONParser();
            Object obj0 = parser.parse(responseStr);
            JSONObject jsonObj = (JSONObject) obj0;
            typeId = (String) jsonObj.get("typeId"); // need to save this
                                                     // as
                                                     // service_type_id
                                                     // in model table
        } catch (IOException | ParseException e) {
            logger.error("Exception occurred during createupdateDCAEServiceType Operation with DCAE", e);
            throw new BadRequestException("Exception occurred during createupdateDCAEServiceType Operation with DCAE",
                    e);
        } finally {
            if (typeId != null) {
                LoggingUtils.setResponseContext("0", "Create update DCAE ServiceType success",
                        this.getClass().getName());
            } else {
                LoggingUtils.setResponseContext("900", "Create update DCAE ServiceType failed",
                        this.getClass().getName());
                LoggingUtils.setErrorContext("900", "Create update DCAE ServiceType error");
            }
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("createupdateDCAEServiceType complete");
        }
        return typeId;
    }

    /**
     * Method to delete blueprint from dcae inventory if it's exists.
     * 
     * @param typeName
     * @param serviceUuid
     * @param resourceUuid
     * @throws InterruptedException
     */
    public void deleteDCAEServiceType(String typeName, String serviceUuid, String resourceUuid)
            throws InterruptedException {
        Date startTime = new Date();
        LoggingUtils.setTargetContext("DCAE", "deleteDCAEServiceType");
        boolean result = false;
        try {
            DcaeInventoryResponse inventoryResponse = getDcaeInformation(typeName, serviceUuid, resourceUuid);
            if (inventoryResponse != null && inventoryResponse.getTypeId() != null) {
                String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types/"
                        + inventoryResponse.getTypeId();
                DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "DELETE", null, null);
            }
            result = true;
        } catch (IOException | ParseException e) {
            logger.error("Exception occurred during deleteDCAEServiceType Operation with DCAE", e);
            throw new BadRequestException("Exception occurred during deleteDCAEServiceType Operation with DCAE", e);
        } finally {
            if (result) {
                LoggingUtils.setResponseContext("0", "Delete DCAE ServiceType success", this.getClass().getName());
            } else {
                LoggingUtils.setResponseContext("900", "Delete DCAE ServiceType failed", this.getClass().getName());
                LoggingUtils.setErrorContext("900", "Delete DCAE ServiceType error");
            }
            LoggingUtils.setTimeContext(startTime, new Date());
            metricsLogger.info("deleteDCAEServiceType completed");
        }
    }
}