summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp/sparky/synchronizer/ElasticSearchIndexCleaner.java
blob: b23764cb117e7df05dccc0c5c8b4df50857deeca (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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017 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=========================================================
 *
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */
package org.openecomp.sparky.synchronizer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.openecomp.sparky.dal.rest.OperationResult;
import org.openecomp.sparky.dal.rest.RestDataProvider;
import org.openecomp.sparky.synchronizer.entity.ObjectIdCollection;
import org.openecomp.sparky.synchronizer.entity.SearchableEntity;
import org.openecomp.sparky.synchronizer.enumeration.OperationState;
import org.openecomp.cl.api.Logger;
import org.openecomp.cl.eelf.LoggerFactory;
import org.openecomp.sparky.logging.AaiUiMsgs;

/**
 * The Class ElasticSearchIndexCleaner.
 */
public class ElasticSearchIndexCleaner implements IndexCleaner {

  private static final Logger LOG =
      LoggerFactory.getInstance().getLogger(ElasticSearchIndexCleaner.class);

  private static final String BULK_OP_LINE_TEMPLATE = "%s\n";
  private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

  private ObjectIdCollection before;
  private ObjectIdCollection after;

  private String host;
  private String port;

  private String indexName;
  private String indexType;
  private int scrollContextTimeToLiveInMinutes;
  private int numItemsToGetBulkRequest;

  private RestDataProvider restDataProvider;
  private ObjectMapper mapper;

  /**
   * Instantiates a new elastic search index cleaner.
   *
   * @param restDataProvider the rest data provider
   * @param indexName the index name
   * @param indexType the index type
   * @param host the host
   * @param port the port
   * @param scrollContextTimeToLiveInMinutes the scroll context time to live in minutes
   * @param numItemsToGetBulkRequest the num items to get bulk request
   */
  protected ElasticSearchIndexCleaner(RestDataProvider restDataProvider, String indexName,
      String indexType, String host, String port, int scrollContextTimeToLiveInMinutes,
      int numItemsToGetBulkRequest) {
    this.restDataProvider = restDataProvider;
    this.before = null;
    this.after = null;
    this.indexName = indexName;
    this.indexType = indexType;
    this.mapper = new ObjectMapper();
    this.host = host;
    this.port = port;
    this.scrollContextTimeToLiveInMinutes = scrollContextTimeToLiveInMinutes;
    this.numItemsToGetBulkRequest = numItemsToGetBulkRequest;
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexCleaner#populatePreOperationCollection()
   */
  @Override
  public OperationState populatePreOperationCollection() {

    try {
      before = retrieveAllDocumentIdentifiers();
      return OperationState.OK;
    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.ES_PRE_SYNC_FAILURE, indexName, exc.getMessage());
      return OperationState.ERROR;
    }

  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexCleaner#populatePostOperationCollection()
   */
  @Override
  public OperationState populatePostOperationCollection() {
    try {
      after = retrieveAllDocumentIdentifiers();
      return OperationState.OK;
    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.ES_PRE_SYNC_FAILURE, indexName, exc.getMessage());
      return OperationState.ERROR;
    }
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexCleaner#performCleanup()
   */
  @Override
  public OperationState performCleanup() {
    // TODO Auto-generated method stub
    LOG.info(AaiUiMsgs.ES_SYNC_CLEAN_UP, indexName);

    int sizeBefore = before.getSize();
    int sizeAfter = after.getSize();

    LOG.info(AaiUiMsgs.ES_SYNC_CLEAN_UP_SIZE, String.valueOf(sizeBefore),
        String.valueOf(sizeAfter));

    /*
     * If the processedImportIds size <= 0, then something has failed in the sync operation and we
     * shouldn't do the selective delete right now.
     */

    if (sizeAfter > 0) {

      Collection<String> presyncIds = before.getImportedObjectIds();
      presyncIds.removeAll(after.getImportedObjectIds());

      try {
        LOG.info(AaiUiMsgs.ES_SYNC_SELECTIVE_DELETE, indexName, indexType,
            String.valueOf(presyncIds.size()));

        ObjectIdCollection bulkIds = new ObjectIdCollection();

        Iterator<String> it = presyncIds.iterator();
        int numItemsInBulkRequest = 0;
        int numItemsRemainingToBeDeleted = presyncIds.size();

        while (it.hasNext()) {

          bulkIds.addObjectId(it.next());
          numItemsInBulkRequest++;

          if (numItemsInBulkRequest >= this.numItemsToGetBulkRequest) {
            LOG.info(AaiUiMsgs.ES_BULK_DELETE, indexName, String.valueOf(bulkIds.getSize()));
            OperationResult bulkDeleteResult = bulkDelete(bulkIds.getImportedObjectIds());
            // pegCountersForElasticBulkDelete(bulkDeleteResult);
            numItemsRemainingToBeDeleted -= numItemsInBulkRequest;
            numItemsInBulkRequest = 0;
            bulkIds.clear();
          }
        }

        if (numItemsRemainingToBeDeleted > 0) {
          LOG.info(AaiUiMsgs.ES_BULK_DELETE, indexName, String.valueOf(bulkIds.getSize()));
          OperationResult bulkDeleteResult = bulkDelete(bulkIds.getImportedObjectIds());
          // pegCountersForElasticBulkDelete(bulkDeleteResult);
        }


      } catch (Exception exc) {
        LOG.error(AaiUiMsgs.ES_BULK_DELETE_ERROR, indexName, exc.getLocalizedMessage());

      }
    }

    return OperationState.OK;
  }

  @Override
  public String getIndexName() {
    return indexName;
  }

  public void setIndexName(String indexName) {
    this.indexName = indexName;
  }

  /**
   * Builds the initial scroll request payload.
   *
   * @param numItemsToGetPerRequest the num items to get per request
   * @param fieldList the field list
   * @return the string
   * @throws JsonProcessingException the json processing exception
   */
  protected String buildInitialScrollRequestPayload(int numItemsToGetPerRequest,
      List<String> fieldList) throws JsonProcessingException {

    ObjectNode rootNode = mapper.createObjectNode();
    rootNode.put("size", numItemsToGetPerRequest);

    ArrayNode fields = mapper.createArrayNode();

    for (String f : fieldList) {
      fields.add(f);
    }

    rootNode.set("fields", fields);

    ObjectNode queryNode = mapper.createObjectNode();
    queryNode.set("match_all", mapper.createObjectNode());

    rootNode.set("query", queryNode);

    return mapper.writeValueAsString(rootNode);

  }

  /**
   * Builds the subsequent scroll context request payload.
   *
   * @param scrollId the scroll id
   * @param contextTimeToLiveInMinutes the context time to live in minutes
   * @return the string
   * @throws JsonProcessingException the json processing exception
   */
  protected String buildSubsequentScrollContextRequestPayload(String scrollId,
      int contextTimeToLiveInMinutes) throws JsonProcessingException {

    ObjectNode rootNode = mapper.createObjectNode();

    rootNode.put("scroll", contextTimeToLiveInMinutes + "m");
    rootNode.put("scroll_id", scrollId);

    return mapper.writeValueAsString(rootNode);

  }

  /**
   * Parses the elastic search result.
   *
   * @param jsonResult the json result
   * @return the json node
   * @throws JsonProcessingException the json processing exception
   * @throws IOException Signals that an I/O exception has occurred.
   */
  protected JsonNode parseElasticSearchResult(String jsonResult)
      throws JsonProcessingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readTree(jsonResult);
  }

  /**
   * Lookup index doc.
   *
   * @param ids the ids
   * @param docs the docs
   * @return the array list
   */
  protected ArrayList<SearchableEntity> lookupIndexDoc(ArrayList<String> ids,
      List<SearchableEntity> docs) {
    ArrayList<SearchableEntity> objs = new ArrayList<SearchableEntity>();

    if (ids != null && docs != null) {
      for (SearchableEntity d : docs) {
        if (ids.contains(d.getId())) {
          objs.add(d);
        }
      }
    }

    return objs;
  }

  /**
   * Builds the delete data object.
   *
   * @param index the index
   * @param type the type
   * @param id the id
   * @return the object node
   */
  protected ObjectNode buildDeleteDataObject(String index, String type, String id) {

    ObjectNode indexDocProperties = mapper.createObjectNode();

    indexDocProperties.put("_index", index);
    indexDocProperties.put("_type", type);
    indexDocProperties.put("_id", id);

    ObjectNode rootNode = mapper.createObjectNode();
    rootNode.set("delete", indexDocProperties);

    return rootNode;
  }

  /**
   * This method might appear to be a little strange, and is simply an optimization to take an
   * elipsed JsonNode key path and retrieve the node at the end of the path, if it exists.
   *
   * @param startNode the start node
   * @param fieldPath the field path
   * @return the node path
   */
  protected JsonNode getNodePath(JsonNode startNode, String... fieldPath) {

    JsonNode jsonNode = null;

    for (String field : fieldPath) {
      if (jsonNode == null) {
        jsonNode = startNode.get(field);
      } else {
        jsonNode = jsonNode.get(field);
      }

      /*
       * This is our safety net in case any intermediate path returns a null
       */

      if (jsonNode == null) {
        return null;
      }

    }

    return jsonNode;
  }

  /**
   * Gets the full url.
   *
   * @param resourceUrl the resource url
   * @return the full url
   */
  private String getFullUrl(String resourceUrl) {
    return String.format("http://%s:%s%s", host, port, resourceUrl);
  }

  /**
   * Retrieve all document identifiers.
   *
   * @return the object id collection
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public ObjectIdCollection retrieveAllDocumentIdentifiers() throws IOException {

    ObjectIdCollection currentDocumentIds = new ObjectIdCollection();

    long opStartTimeInMs = System.currentTimeMillis();

    List<String> fields = new ArrayList<String>();
    fields.add("_id");
    // fields.add("entityType");

    String scrollRequestPayload =
        buildInitialScrollRequestPayload(this.numItemsToGetBulkRequest, fields);

    final String fullUrlStr = getFullUrl("/" + indexName + "/" + indexType + "/_search?scroll="
        + this.scrollContextTimeToLiveInMinutes + "m");

    OperationResult result =
        restDataProvider.doPost(fullUrlStr, scrollRequestPayload, "application/json");

    if (result.wasSuccessful()) {

      JsonNode rootNode = parseElasticSearchResult(result.getResult());

      /*
       * Check the result for success / failure, and enumerate all the index ids that resulted in
       * success, and ignore the ones that failed or log them so we have a record of the failure.
       */
      int totalRecordsAvailable = 0;
      String scrollId = null;
      int numRecordsFetched = 0;

      if (rootNode != null) {

        scrollId = getFieldValue(rootNode, "_scroll_id");
        final String tookStr = getFieldValue(rootNode, "took");
        int tookInMs = (tookStr == null) ? 0 : Integer.parseInt(tookStr);
        boolean timedOut = Boolean.parseBoolean(getFieldValue(rootNode, "timed_out"));

        if (timedOut) {
          LOG.error(AaiUiMsgs.COLLECT_TIME_WITH_ERROR, "all document Identifiers",
              String.valueOf(tookInMs));
        } else {
          LOG.info(AaiUiMsgs.COLLECT_TIME_WITH_SUCCESS, "all document Identifiers",
              String.valueOf(tookInMs));
        }

        JsonNode hitsNode = rootNode.get("hits");
        totalRecordsAvailable = Integer.parseInt(hitsNode.get("total").asText());

        LOG.info(AaiUiMsgs.COLLECT_TOTAL, "all document Identifiers",
            String.valueOf(totalRecordsAvailable));

        /*
         * Collect all object ids
         */

        ArrayNode hitsArray = (ArrayNode) hitsNode.get("hits");

        Iterator<JsonNode> nodeIterator = hitsArray.iterator();

        String key = null;
        String value = null;
        JsonNode jsonNode = null;

        while (nodeIterator.hasNext()) {

          jsonNode = nodeIterator.next();

          key = getFieldValue(jsonNode, "_id");

          if (key != null) {
            currentDocumentIds.addObjectId(key);
          }

          /*
           * if (key != null) {
           * 
           * JsonNode fieldsNode = jNode.get("fields");
           * 
           * if (fieldsNode != null) {
           * 
           * JsonNode entityTypeNode = fieldsNode.get("entityType");
           * 
           * if (entityTypeNode != null) { ArrayNode aNode = (ArrayNode) entityTypeNode;
           * 
           * if (aNode.size() > 0) { value = aNode.get(0).asText(); objAndtTypesMap.put(key, value);
           * numRecordsFetched++; } } } }
           */

        }

        int totalRecordsRemainingToFetch = (totalRecordsAvailable - numRecordsFetched);

        int numRequiredAdditionalFetches =
            (totalRecordsRemainingToFetch / this.numItemsToGetBulkRequest);

        /*
         * Do an additional fetch for the remaining items (if needed)
         */

        if (totalRecordsRemainingToFetch % numItemsToGetBulkRequest != 0) {
          numRequiredAdditionalFetches += 1;
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug(AaiUiMsgs.SYNC_NUMBER_REQ_FETCHES,
              String.valueOf(numRequiredAdditionalFetches));
        }


        for (int x = 0; x < numRequiredAdditionalFetches; x++) {

          if (collectItemsFromScrollContext(scrollId, currentDocumentIds) != OperationState.OK) {
            // abort the whole thing because now we can't reliably cleanup the orphans.
            throw new IOException(
                "Failed to collect pre-sync doc collection from index.  Aborting operation");
          }
          if (LOG.isDebugEnabled()) {
            LOG.debug(AaiUiMsgs.SYNC_NUMBER_TOTAL_FETCHES,
                String.valueOf(currentDocumentIds.getSize()),
                String.valueOf(totalRecordsAvailable));
          }

        }

      }

    } else {
      // scroll context get failed, nothing else to do
      LOG.error(AaiUiMsgs.ERROR_GENERIC, result.toString());
    }

    LOG.info(AaiUiMsgs.COLLECT_TOTAL_TIME, "all document Identifiers",
        String.valueOf((System.currentTimeMillis() - opStartTimeInMs)));

    return currentDocumentIds;

  }

  /**
   * Collect items from scroll context.
   *
   * @param scrollId the scroll id
   * @param objectIds the object ids
   * @return the operation state
   * @throws IOException Signals that an I/O exception has occurred.
   */
  private OperationState collectItemsFromScrollContext(String scrollId,
      ObjectIdCollection objectIds) throws IOException {

    // ObjectIdCollection documentIdCollection = new ObjectIdCollection();

    String requestPayload =
        buildSubsequentScrollContextRequestPayload(scrollId, scrollContextTimeToLiveInMinutes);

    final String fullUrlStr = getFullUrl("/_search/scroll");

    OperationResult opResult =
        restDataProvider.doPost(fullUrlStr, requestPayload, "application/json");

    if (opResult.getResultCode() >= 300) {
      LOG.warn(AaiUiMsgs.ES_SCROLL_CONTEXT_ERROR, opResult.getResult());
      return OperationState.ERROR;
    }

    JsonNode rootNode = parseElasticSearchResult(opResult.getResult());
    boolean timedOut = Boolean.parseBoolean(getFieldValue(rootNode, "timed_out"));
    final String tookStr = getFieldValue(rootNode, "took");
    int tookInMs = (tookStr == null) ? 0 : Integer.parseInt(tookStr);

    JsonNode hitsNode = rootNode.get("hits");

    /*
     * Check the result for success / failure, and enumerate all the index ids that resulted in
     * success, and ignore the ones that failed or log them so we have a record of the failure.
     */

    if (rootNode != null) {

      if (timedOut) {
        LOG.info(AaiUiMsgs.COLLECT_TIME_WITH_ERROR, "Scroll Context", String.valueOf(tookInMs));
      } else {
        LOG.info(AaiUiMsgs.COLLECT_TIME_WITH_SUCCESS, "Scroll Context", String.valueOf(tookInMs));
      }

      /*
       * Collect all object ids
       */

      ArrayNode hitsArray = (ArrayNode) hitsNode.get("hits");
      String key = null;
      String value = null;
      JsonNode jsonNode = null;

      Iterator<JsonNode> nodeIterator = hitsArray.iterator();

      while (nodeIterator.hasNext()) {

        jsonNode = nodeIterator.next();

        key = getFieldValue(jsonNode, "_id");

        if (key != null) {
          objectIds.addObjectId(key);

          /*
           * JsonNode fieldsNode = jNode.get("fields");
           * 
           * if (fieldsNode != null) {
           * 
           * JsonNode entityTypeNode = fieldsNode.get("entityType");
           * 
           * if (entityTypeNode != null) { ArrayNode aNode = (ArrayNode) entityTypeNode;
           * 
           * if (aNode.size() > 0) { value = aNode.get(0).asText(); objectIdsAndTypes.put(key,
           * value); } } } }
           */

        }

      }
    }

    return OperationState.OK;
  }

  /**
   * Gets the field value.
   *
   * @param node the node
   * @param fieldName the field name
   * @return the field value
   */
  protected String getFieldValue(JsonNode node, String fieldName) {

    JsonNode field = node.get(fieldName);

    if (field != null) {
      return field.asText();
    }

    return null;

  }

  /**
   * Bulk delete.
   *
   * @param docIds the doc ids
   * @return the operation result
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public OperationResult bulkDelete(Collection<String> docIds) throws IOException {

    if (docIds == null || docIds.size() == 0) {
      LOG.info(AaiUiMsgs.ES_BULK_DELETE_SKIP);
      return new OperationResult(500,
          "Skipping bulkDelete(); operation because docs to delete list is empty");
    }

    LOG.info(AaiUiMsgs.ES_BULK_DELETE_START, String.valueOf(docIds.size()));

    StringBuilder sb = new StringBuilder(128);

    for (String id : docIds) {
      sb.append(
          String.format(BULK_OP_LINE_TEMPLATE, buildDeleteDataObject(indexName, indexType, id)));
    }

    sb.append("\n");

    final String fullUrlStr = getFullUrl("/_bulk");

    return restDataProvider.doPost(fullUrlStr, sb.toString(), "application/x-www-form-urlencoded");

  }

  /*
  
  */

}