summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/crud/service/CrudAsyncGraphDataService.java
blob: dc30a4e10b1647096112aedfda28b7dc601cb01b (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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017-2018 Amdocs
 * ================================================================================
 * 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.crud.service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Timer;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.PreDestroy;
import javax.ws.rs.core.Response.Status;
import org.onap.aai.cl.api.LogFields;
import org.onap.aai.cl.api.Logger;
import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.cl.mdc.MdcContext;
import org.onap.aai.cl.mdc.MdcOverride;
import org.onap.aai.event.api.EventConsumer;
import org.onap.aai.event.api.EventPublisher;
import org.onap.crud.dao.GraphDao;
import org.onap.crud.entity.Edge;
import org.onap.crud.entity.Vertex;
import org.onap.crud.event.GraphEvent;
import org.onap.crud.event.GraphEvent.GraphEventOperation;
import org.onap.crud.event.GraphEventEdge;
import org.onap.crud.event.GraphEventVertex;
import org.onap.crud.event.envelope.GraphEventEnvelope;
import org.onap.crud.event.response.GraphEventResponseHandler;
import org.onap.crud.exception.CrudException;
import org.onap.crud.logging.CrudServiceMsgs;
import org.onap.crud.util.CrudProperties;
import org.onap.crud.util.CrudServiceConstants;
import org.onap.schema.OxmModelValidator;
import org.onap.schema.RelationshipSchemaValidator;

public class CrudAsyncGraphDataService extends AbstractGraphDataService {

    private static Integer requestTimeOut;

    private EventPublisher asyncRequestPublisher;

    private Timer timer;

    public static final Integer DEFAULT_REQUEST_TIMEOUT = 30000;
    private static final Integer DEFAULT_ASYNC_RESPONSE_PROCESS_POLL_INTERVAL = 1000;

    private static Logger logger = LoggerFactory.getInstance().getLogger(CrudAsyncGraphDataService.class.getName());
    private static Logger metricsLogger =
            LoggerFactory.getInstance().getMetricsLogger(CrudAsyncGraphDataService.class.getName());
    private static LogFields okFields = new LogFields();

    static {
        okFields.setField(Status.OK, Status.OK.toString());
    }

    private GraphEventResponseHandler responseHandler = new GraphEventResponseHandler();

    public static Integer getRequestTimeOut() {
        return requestTimeOut;
    }

    public CrudAsyncGraphDataService(GraphDao dao, EventPublisher asyncRequestPublisher,
            EventConsumer asyncResponseConsumer) throws CrudException {
        this(dao, dao, asyncRequestPublisher, asyncResponseConsumer);
    }

    public CrudAsyncGraphDataService(GraphDao dao, GraphDao daoForGet, EventPublisher asyncRequestPublisher,
            EventConsumer asyncResponseConsumer) throws CrudException {

        super();
        this.dao = dao;
        this.daoForGet = daoForGet;

        requestTimeOut = DEFAULT_REQUEST_TIMEOUT;
        try {
            requestTimeOut = Integer.parseInt(CrudProperties.get(CrudServiceConstants.CRD_ASYNC_REQUEST_TIMEOUT));
        } catch (NumberFormatException ex) {
            // Leave it as the default
        }

        Integer responsePollInterval = DEFAULT_ASYNC_RESPONSE_PROCESS_POLL_INTERVAL;
        try {
            responsePollInterval =
                    Integer.parseInt(CrudProperties.get(CrudServiceConstants.CRD_ASYNC_RESPONSE_PROCESS_POLL_INTERVAL));
        } catch (Exception ex) {
            logger.error(CrudServiceMsgs.ASYNC_DATA_SERVICE_ERROR, "Unable to parse "
                    + CrudServiceConstants.CRD_ASYNC_RESPONSE_PROCESS_POLL_INTERVAL + " error: " + ex.getMessage());
        }

        // Start the Response Consumer timer
        CrudAsyncResponseConsumer crudAsyncResponseConsumer = new CrudAsyncResponseConsumer(asyncResponseConsumer);
        timer = new Timer("crudAsyncResponseConsumer-1");
        timer.schedule(crudAsyncResponseConsumer, responsePollInterval, responsePollInterval);

        this.asyncRequestPublisher = asyncRequestPublisher;

        logger.info(CrudServiceMsgs.ASYNC_DATA_SERVICE_INFO, "CrudAsyncGraphDataService initialized SUCCESSFULLY!");
    }

    public class CollectGraphResponse implements Callable<GraphEventEnvelope> {
        private volatile GraphEventEnvelope graphEventEnvelope;
        private volatile CountDownLatch latch = new CountDownLatch(1);

        @Override
        public GraphEventEnvelope call() throws TimeoutException {
            try {
                // Wait until graphEvent is available
                latch.await(CrudAsyncGraphDataService.getRequestTimeOut(), TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                latch.countDown();
                if (this.graphEventEnvelope != null) {
                    return this.graphEventEnvelope;
                } else {
                    throw new TimeoutException();
                }
            }
            return this.graphEventEnvelope;
        }

        public void populateGraphEventEnvelope(GraphEventEnvelope eventEnvelope) {
            this.graphEventEnvelope = eventEnvelope;
            latch.countDown();
        }
    }

    private GraphEventEnvelope sendAndWait(GraphEvent event) throws CrudException {

        long startTimeInMs = System.currentTimeMillis();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        MdcOverride override = new MdcOverride();
        override.addAttribute(MdcContext.MDC_START_TIME, formatter.format(startTimeInMs));

        String eventEnvelopeJson = new GraphEventEnvelope(event).toJson();

        // publish to request queue
        try {
            asyncRequestPublisher.sendSync(eventEnvelopeJson);
        } catch (Exception e) {
            throw new CrudException(
                    "Error publishing request " + event.getTransactionId() + "  Cause: " + e.getMessage(),
                    Status.INTERNAL_SERVER_ERROR);
        }

        logger.debug(CrudServiceMsgs.ASYNC_DATA_SERVICE_INFO, "Event Sent =" + eventEnvelopeJson);

        logger.info(CrudServiceMsgs.ASYNC_DATA_SERVICE_INFO,
                "Event submitted of type: " + event.getObjectType() + " with key: " + event.getObjectKey()
                        + " , transaction-id: " + event.getTransactionId() + " , operation: "
                        + event.getOperation().toString());

        ExecutorService executor =
                Executors.newSingleThreadExecutor(new CrudThreadFactory("TX-" + event.getTransactionId()));
        CollectGraphResponse collector = new CollectGraphResponse();
        CrudAsyncGraphEventCache.put(event.getTransactionId(), collector);
        GraphEventEnvelope response;
        Future<GraphEventEnvelope> future = executor.submit(collector);
        try {
            response = future.get(requestTimeOut, TimeUnit.MILLISECONDS);

        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            CrudAsyncGraphEventCache.invalidate(event.getTransactionId());
            logger.error(CrudServiceMsgs.ASYNC_DATA_SERVICE_ERROR,
                    "Request timed out for transactionId: " + event.getTransactionId());
            future.cancel(true);
            throw new CrudException("Timed out , transactionId: " + event.getTransactionId() + " , operation: "
                    + event.getOperation().toString(), Status.INTERNAL_SERVER_ERROR);
        } finally {
            // Kill the thread as the work is completed
            executor.shutdownNow();
        }
        metricsLogger.info(CrudServiceMsgs.ASYNC_DATA_SERVICE_INFO, okFields, override,
                "Total elapsed time for operation: " + event.getOperation().toString() + " , transactionId: "
                        + event.getTransactionId() + " is " + Long.toString(System.currentTimeMillis() - startTimeInMs)
                        + " ms");
        return response;
    }

    @Override
    public String addVertex(String version, String type, VertexPayload payload) throws CrudException {
        // Validate the incoming payload
        Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, type, payload.getProperties());
        // Create graph request event
        GraphEvent event = GraphEvent.builder(GraphEventOperation.CREATE)
                .vertex(GraphEventVertex.fromVertex(vertex, version)).build();

        GraphEventEnvelope response = sendAndWait(event);
        return responseHandler.handleVertexResponse(version, event, response);
    }

    @Override
    public String addEdge(String version, String type, EdgePayload payload) throws CrudException {
        Edge edge = RelationshipSchemaValidator.validateIncomingAddPayload(version, type, payload);
        // Create graph request event
        GraphEvent event =
                GraphEvent.builder(GraphEventOperation.CREATE).edge(GraphEventEdge.fromEdge(edge, version)).build();

        GraphEventEnvelope response = sendAndWait(event);
        return responseHandler.handleEdgeResponse(version, event, response);
    }

    @Override
    public String updateVertex(String version, String id, String type, VertexPayload payload) throws CrudException {
        Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(id, version, type, payload.getProperties());
        GraphEvent event = GraphEvent.builder(GraphEventOperation.UPDATE)
                .vertex(GraphEventVertex.fromVertex(vertex, version)).build();

        GraphEventEnvelope response = sendAndWait(event);
        return responseHandler.handleVertexResponse(version, event, response);
    }

    @Override
    public String patchVertex(String version, String id, String type, VertexPayload payload) throws CrudException {
        Vertex existingVertex = dao.getVertex(id, OxmModelValidator.resolveCollectionType(version, type), version,
                new HashMap<String, String>());
        Vertex patchedVertex = OxmModelValidator.validateIncomingPatchPayload(id, version, type,
                payload.getProperties(), existingVertex);
        GraphEvent event = GraphEvent.builder(GraphEventOperation.UPDATE)
                .vertex(GraphEventVertex.fromVertex(patchedVertex, version)).build();

        GraphEventEnvelope response = sendAndWait(event);
        return responseHandler.handleVertexResponse(version, event, response);
    }

    @Override
    public String deleteVertex(String version, String id, String type) throws CrudException {
        type = OxmModelValidator.resolveCollectionType(version, type);
        GraphEvent event = GraphEvent.builder(GraphEventOperation.DELETE)
                .vertex(new GraphEventVertex(id, version, type, null)).build();

        GraphEventEnvelope response = sendAndWait(event);
        return responseHandler.handleDeletionResponse(event, response);
    }

    @Override
    public String deleteEdge(String version, String id, String type) throws CrudException {
        RelationshipSchemaValidator.validateType(version, type);
        GraphEvent event = GraphEvent.builder(GraphEventOperation.DELETE)
                .edge(new GraphEventEdge(id, version, type, null, null, null)).build();

        GraphEventEnvelope response = sendAndWait(event);
        return responseHandler.handleDeletionResponse(event, response);
    }

    @Override
    public String updateEdge(String version, String id, String type, EdgePayload payload) throws CrudException {
        Edge edge = dao.getEdge(id, type, new HashMap<String, String>());
        Edge validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, payload);
        GraphEvent event = GraphEvent.builder(GraphEventOperation.UPDATE)
                .edge(GraphEventEdge.fromEdge(validatedEdge, version)).build();

        GraphEventEnvelope response = sendAndWait(event);
        return responseHandler.handleEdgeResponse(version, event, response);
    }

    @Override
    public String patchEdge(String version, String id, String type, EdgePayload payload) throws CrudException {
        Edge edge = dao.getEdge(id, type, new HashMap<String, String>());
        Edge patchedEdge = RelationshipSchemaValidator.validateIncomingPatchPayload(edge, version, payload);
        GraphEvent event = GraphEvent.builder(GraphEventOperation.UPDATE)
                .edge(GraphEventEdge.fromEdge(patchedEdge, version)).build();

        GraphEventEnvelope response = sendAndWait(event);
        return responseHandler.handleEdgeResponse(version, event, response);
    }

    @PreDestroy
    protected void preShutdown() {
        timer.cancel();
    }

    @Override
    protected Vertex addBulkVertex(Vertex vertex, String version, String dbTransId) throws CrudException {
        GraphEvent event = GraphEvent.builder(GraphEventOperation.CREATE)
                .vertex(GraphEventVertex.fromVertex(vertex, version)).build();
        event.setDbTransactionId(dbTransId);
        GraphEvent response = publishEvent(event);
        return response.getVertex().toVertex();
    }

    @Override
    protected Vertex updateBulkVertex(Vertex vertex, String id, String version, String dbTransId) throws CrudException {
        GraphEvent event = GraphEvent.builder(GraphEventOperation.UPDATE)
                .vertex(GraphEventVertex.fromVertex(vertex, version)).build();
        event.setDbTransactionId(dbTransId);
        GraphEvent response = publishEvent(event);
        return response.getVertex().toVertex();
    }

    @Override
    protected void deleteBulkVertex(String id, String version, String type, String dbTransId) throws CrudException {
        GraphEvent event = GraphEvent.builder(GraphEventOperation.DELETE)
                .vertex(new GraphEventVertex(id, version, type, null)).build();
        event.setDbTransactionId(dbTransId);
        publishEvent(event);
    }

    @Override
    protected Edge addBulkEdge(Edge edge, String version, String dbTransId) throws CrudException {
        GraphEvent event =
                GraphEvent.builder(GraphEventOperation.CREATE).edge(GraphEventEdge.fromEdge(edge, version)).build();
        event.setDbTransactionId(dbTransId);
        GraphEvent response = publishEvent(event);
        return response.getEdge().toEdge();
    }

    @Override
    protected Edge updateBulkEdge(Edge edge, String version, String dbTransId) throws CrudException {
        GraphEvent event =
                GraphEvent.builder(GraphEventOperation.UPDATE).edge(GraphEventEdge.fromEdge(edge, version)).build();
        event.setDbTransactionId(dbTransId);
        GraphEvent response = publishEvent(event);
        return response.getEdge().toEdge();
    }

    @Override
    protected void deleteBulkEdge(String id, String version, String type, String dbTransId) throws CrudException {
        GraphEvent event = GraphEvent.builder(GraphEventOperation.DELETE)
                .edge(new GraphEventEdge(id, version, type, null, null, null)).build();
        event.setDbTransactionId(dbTransId);
        publishEvent(event);
    }

    private GraphEvent publishEvent(GraphEvent event) throws CrudException {
        GraphEventEnvelope response = sendAndWait(event);
        responseHandler.handleBulkEventResponse(event, response);
        return response.getBody();
    }
}