aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/crud/service/CrudAsyncGraphDataService.java
blob: 60a18d330691cdec78d55675e1930a0e83761020 (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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/**
 * ============LICENSE_START=======================================================
 * Gizmo
 * ================================================================================
 * Copyright © 2017 AT&T Intellectual Property.
 * Copyright © 2017 Amdocs
 * 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=========================================================
 *
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */
package org.onap.crud.service;

import com.att.ecomp.event.api.EventConsumer;
import com.att.ecomp.event.api.EventPublisher;

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.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.GraphEvent.GraphEventResult;
import org.onap.crud.event.GraphEventEdge;
import org.onap.crud.event.GraphEventVertex;
import org.onap.crud.exception.CrudException;
import org.onap.crud.logging.CrudServiceMsgs;
import org.onap.crud.parser.CrudResponseBuilder;
import org.onap.crud.util.CrudProperties;
import org.onap.crud.util.CrudServiceConstants;
import org.onap.schema.OxmModelValidator;
import org.onap.schema.RelationshipSchemaValidator;

import java.text.SimpleDateFormat;
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;

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 OK_FIELDS = new LogFields();

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

  public static Integer getRequestTimeOut() {
    return requestTimeOut;
  }

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

     super(dao);
     
    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<GraphEvent> {
    private volatile GraphEvent graphEvent;
    private volatile CountDownLatch latch = new CountDownLatch(1);

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

    public void populateGraphEvent(GraphEvent event) {
      this.graphEvent = event;
      latch.countDown();
    }
  }

  private GraphEvent 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));

    // publish to request queue
    try {
      asyncRequestPublisher.sendSync(event.toJson());
    } 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 ="+event.toJson());

    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);
    GraphEvent response;
    Future<GraphEvent> 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, OK_FIELDS, override,
            "Total elapsed time for operation: " + event.getOperation().toString()
            + " , transactionId: " + event.getTransactionId() + " is "
            + Long.toString(System.currentTimeMillis() - startTimeInMs) + " ms");
    return response;
  }

  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();

    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
      return CrudResponseBuilder.buildUpsertVertexResponse(
                                                           OxmModelValidator.validateOutgoingPayload(version,
                                                                                                     response.getVertex().toVertex()), version);
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation Failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    }

  }

  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();

    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
      return CrudResponseBuilder.buildUpsertEdgeResponse(
                                                         RelationshipSchemaValidator.validateOutgoingPayload(version, response.getEdge().toEdge()),
                                                         version);
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation Failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    }
  }

  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();

    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
      return CrudResponseBuilder.buildUpsertVertexResponse(
                                                           OxmModelValidator.validateOutgoingPayload(version, response.getVertex().toVertex()),
                                                           version);
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation Failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    }

  }

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

    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
      return CrudResponseBuilder.buildUpsertVertexResponse(
                                                           OxmModelValidator.validateOutgoingPayload(version, response.getVertex().toVertex()),
                                                           version);
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation Failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    }

  }

  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();

    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
      return "";
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation Failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    }

  }

  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();

    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
      return "";
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation Failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    }

  }

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

    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
      return CrudResponseBuilder.buildUpsertEdgeResponse(
                                                         RelationshipSchemaValidator.validateOutgoingPayload(version,
                                                                                                             response.getEdge().toEdge()), version);
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation Failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    }

  }

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

    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
      return CrudResponseBuilder.buildUpsertEdgeResponse(
                                                         RelationshipSchemaValidator.validateOutgoingPayload(version, response.getEdge().toEdge()),
                                                         version);
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation Failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    }

  }

  @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 {
    GraphEvent response = sendAndWait(event);
    if (response.getResult().equals(GraphEventResult.SUCCESS)) {
      logSuccessResponse(event, response);
    } else {
      logErrorResponse(event, response);
      throw new CrudException("Operation failed with transaction-id: " + response.getTransactionId()
                              + " Error: " + response.getErrorMessage(), response.getHttpErrorStatus());
    } 
    
    return response;
  }

  private void logSuccessResponse(GraphEvent event, GraphEvent response) {
    logger.info(CrudServiceMsgs.ASYNC_DATA_SERVICE_INFO,
        "Event response received: " + response.getObjectType() + " with key: "
        + response.getObjectKey() + " , transaction-id: " + response.getTransactionId()
        + " , operation: " + event.getOperation().toString() + " , result: "
        + response.getResult());
  }
  
  private void logErrorResponse(GraphEvent event, GraphEvent response) {
    logger.info(CrudServiceMsgs.ASYNC_DATA_SERVICE_INFO,
        "Event response received: " + response.getObjectType() + " with key: "
        + response.getObjectKey() + " , transaction-id: " + response.getTransactionId()
        + " , operation: " + event.getOperation().toString() + " , result: "
        + response.getResult() + " , error: " + response.getErrorMessage());
  }
  
}