summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp/sparky/synchronizer/GeoSynchronizer.java
blob: 493f3c9a8085aa25a840e56c520edb65fa20545f (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
/**
 * ============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 static java.util.concurrent.CompletableFuture.supplyAsync;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.Supplier;

import org.openecomp.cl.api.Logger;
import org.openecomp.cl.eelf.LoggerFactory;
import org.openecomp.cl.mdc.MdcContext;
import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
import org.openecomp.sparky.dal.NetworkTransaction;
import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig;
import org.openecomp.sparky.dal.rest.HttpMethod;
import org.openecomp.sparky.dal.rest.OperationResult;
import org.openecomp.sparky.inventory.entity.GeoIndexDocument;
import org.openecomp.sparky.logging.AaiUiMsgs;
import org.openecomp.sparky.synchronizer.entity.SelfLinkDescriptor;
import org.openecomp.sparky.synchronizer.enumeration.OperationState;
import org.openecomp.sparky.synchronizer.enumeration.SynchronizerState;
import org.openecomp.sparky.synchronizer.task.PerformActiveInventoryRetrieval;
import org.openecomp.sparky.synchronizer.task.StoreDocumentTask;
import org.openecomp.sparky.util.NodeUtils;
import org.slf4j.MDC;

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


/**
 * The Class GeoSynchronizer.
 */
public class GeoSynchronizer extends AbstractEntitySynchronizer implements IndexSynchronizer {

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

  private boolean allWorkEnumerated;
  private Deque<SelfLinkDescriptor> selflinks;

  private ElasticSearchConfig elasticConfig = null;
  private Map<String, OxmEntityDescriptor> geoDescriptorMap = null;

  /**
   * Instantiates a new geo synchronizer.
   *
   * @param indexName the index name
   * @throws Exception the exception
   */
  public GeoSynchronizer(String indexName) throws Exception {

    super(LOG, "GEO", 2, 5, 5, indexName);
    this.allWorkEnumerated = false;
    this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
    this.synchronizerName = "Geo Synchronizer";
    this.geoDescriptorMap = oxmModelLoader.getGeoEntityDescriptors();
    this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors(geoDescriptorMap);
    this.esEntityStats.initializeCountersFromOxmEntityDescriptors(geoDescriptorMap);
    this.syncDurationInMs = -1;
  }


  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
   */
  @Override
  public OperationState doSync() {
    resetCounters();
    allWorkEnumerated = false;
    syncStartedTimeStampInMs = System.currentTimeMillis();
    String txnID = NodeUtils.getRandomTxnId();
    MdcContext.initialize(txnID, "GeoSynchronizer", "", "Sync", "");
	
    collectAllTheWork();
    return OperationState.OK;
  }


  /**
   * Collect all the work.
   *
   * @return the operation state
   */
  public OperationState collectAllTheWork() {
	final Map<String,String> contextMap = MDC.getCopyOfContextMap();
    if (elasticConfig == null) {
      try {
        elasticConfig = ElasticSearchConfig.getConfig();
      } catch (Exception exc) {
        LOG.error(AaiUiMsgs.CONFIGURATION_ERROR, "Search");
      }
    }

    if (geoDescriptorMap.isEmpty()) {
      setShouldSkipSync(true);
      LOG.error(AaiUiMsgs.OXM_FAILED_RETRIEVAL, "geo entities");
      return OperationState.ERROR;
    }

    Collection<String> syncTypes = geoDescriptorMap.keySet();

    try {

      /*
       * launch a parallel async thread to process the documents for each entity-type (to max the of
       * the configured executor anyway)
       */

      aaiWorkOnHand.set(syncTypes.size());

      for (String key : syncTypes) {

        supplyAsync(new Supplier<Void>() {

          @Override
          public Void get() {
        	MDC.setContextMap(contextMap);
            OperationResult typeLinksResult = null;
            try {
              typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
              aaiWorkOnHand.decrementAndGet();
              processEntityTypeSelfLinks(typeLinksResult);
            } catch (Exception exc) {
              LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, exc);
            }

            return null;
          }

        }, aaiExecutor).whenComplete((result, error) -> {

          if (error != null) {
            LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
          }
        });

      }

      while (aaiWorkOnHand.get() != 0) {

        if (LOG.isDebugEnabled()) {
          LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
        }

        Thread.sleep(1000);
      }

      aaiWorkOnHand.set(selflinks.size());
      allWorkEnumerated = true;
      syncEntityTypes();

    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, exc);
    }
    return OperationState.OK;
  }

  /**
   * Sync entity types.
   */
  private void syncEntityTypes() {

    while (selflinks.peek() != null) {

      SelfLinkDescriptor linkDescriptor = selflinks.poll();
      aaiWorkOnHand.decrementAndGet();

      OxmEntityDescriptor descriptor = null;

      if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {

        descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());

        if (descriptor == null) {
          LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
          // go to next element in iterator
          continue;
        }

        NetworkTransaction txn = new NetworkTransaction();
        txn.setDescriptor(descriptor);
        txn.setLink(linkDescriptor.getSelfLink());
        txn.setOperationType(HttpMethod.GET);
        txn.setEntityType(linkDescriptor.getEntityType());

        aaiWorkOnHand.incrementAndGet();

        supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
            .whenComplete((result, error) -> {

              aaiWorkOnHand.decrementAndGet();

              if (error != null) {
                LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
              } else {
                if (result == null) {
                  LOG.error(AaiUiMsgs.SELF_LINK_GET_NO_RESPONSE, linkDescriptor.getSelfLink());
                } else {
                  processEntityTypeSelfLinkResult(result);
                }
              }
            });
      }
    }
  }

  /**
   * Process entity type self links.
   *
   * @param operationResult the operation result
   */
  private void processEntityTypeSelfLinks(OperationResult operationResult) {

    JsonNode rootNode = null;

    final String jsonResult = operationResult.getResult();

    if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {

      try {
        rootNode = mapper.readTree(jsonResult);
      } catch (IOException exc) {
        LOG.error(AaiUiMsgs.ERROR_GENERIC, exc);
        return;
      }

      JsonNode resultData = rootNode.get("result-data");
      ArrayNode resultDataArrayNode = null;

      if (resultData.isArray()) {
        resultDataArrayNode = (ArrayNode) resultData;

        Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
        JsonNode element = null;

        while (elementIterator.hasNext()) {
          element = elementIterator.next();

          final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
          final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");

          if (resourceType != null && resourceLink != null) {

            if (geoDescriptorMap.containsKey(resourceType)) {
              selflinks.add(new SelfLinkDescriptor(resourceLink + "?nodes-only", resourceType));
            } else {
              LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
              // go to next element in iterator
              continue;
            }

          }
        }
      }
    }

  }

  /**
   * Process entity type self link result.
   *
   * @param txn the txn
   */
  private void processEntityTypeSelfLinkResult(NetworkTransaction txn) {

    updateActiveInventoryCounters(txn);

    if (!txn.getOperationResult().wasSuccessful()) {
      return;
    }

    try {
      if (!(txn.getDescriptor().getGeoLatName().isEmpty()
          && txn.getDescriptor().getGeoLongName().isEmpty())) {

        GeoIndexDocument geoDoc = new GeoIndexDocument(oxmModelLoader);

        final String jsonResult = txn.getOperationResult().getResult();

        if (jsonResult != null && jsonResult.length() > 0) {

          populateGeoDocument(geoDoc, jsonResult, txn.getDescriptor(), txn.getLink());

          if (!geoDoc.isValidGeoDocument()) {

            LOG.info(AaiUiMsgs.GEO_SYNC_IGNORING_ENTITY, geoDoc.getEntityType(), geoDoc.toString());

          } else {

            String link = null;
            try {
              link = getElasticFullUrl("/" + geoDoc.getId(), getIndexName(), "default");
            } catch (Exception exc) {
              LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc);
            }

            if (link != null) {

              NetworkTransaction n2 = new NetworkTransaction();
              n2.setLink(link);
              n2.setEntityType(txn.getEntityType());
              n2.setDescriptor(txn.getDescriptor());
              n2.setOperationType(HttpMethod.PUT);

              esWorkOnHand.incrementAndGet();

              supplyAsync(new StoreDocumentTask(geoDoc, n2, esDataProvider), esExecutor)
                  .whenComplete((result, error) -> {

                    esWorkOnHand.decrementAndGet();

                    if (error != null) {
                      LOG.error(AaiUiMsgs.ES_STORE_FAILURE, error.getMessage());
                    } else {
                      updateElasticSearchCounters(result);
                      processStoreDocumentResult(result);
                    }
                  });
            }
          }
        }
      }
    } catch (JsonProcessingException exc) {
      LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, exc);
    } catch (IOException exc) {
      LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, exc);
    }

    return;
  }


  /**
   * Process store document result.
   *
   * @param txn the txn
   */
  private void processStoreDocumentResult(NetworkTransaction txn) {

    OperationResult or = txn.getOperationResult();

    if (!or.wasSuccessful()) {
      LOG.error(AaiUiMsgs.ES_STORE_FAILURE, or.toString());
      /*
       * if(or.getResultCode() != 404 || (or.getResultCode() == 404 &&
       * !synchronizerConfig.isResourceNotFoundErrorsSupressed())) { logger.error(
       * "Skipping failed resource = " + "link" + " RC=[" + or.getResultCode() + "]. Message: " +
       * or.getResult()); }
       */

    }

  }


  @Override
  public SynchronizerState getState() {

    if (!isSyncDone()) {
      return SynchronizerState.PERFORMING_SYNCHRONIZATION;
    }

    return SynchronizerState.IDLE;

  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
   */
  @Override
  public String getStatReport(boolean showFinalReport) {
	  syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
	  return this.getStatReport(syncDurationInMs, showFinalReport);
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
   */
  @Override
  public void shutdown() {
    this.shutdownExecutors();
  }

  /**
   * Populate geo document.
   *
   * @param doc the doc
   * @param result the result
   * @param resultDescriptor the result descriptor
   * @param entityLink the entity link
   * @throws JsonProcessingException the json processing exception
   * @throws IOException Signals that an I/O exception has occurred.
   */
  protected void populateGeoDocument(GeoIndexDocument doc, String result,
      OxmEntityDescriptor resultDescriptor, String entityLink)
          throws JsonProcessingException, IOException {

    doc.setSelfLink(entityLink);
    doc.setEntityType(resultDescriptor.getEntityName());

    JsonNode entityNode = mapper.readTree(result);

    List<String> primaryKeyValues = new ArrayList<String>();
    String pkeyValue = null;

    for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
      pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
      if (pkeyValue != null) {
        primaryKeyValues.add(pkeyValue);
      } else {
        LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
      }
    }

    final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
    doc.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
    String geoLatKey = resultDescriptor.getGeoLatName();
    String geoLongKey = resultDescriptor.getGeoLongName();

    doc.setLatitude(NodeUtils.getNodeFieldAsText(entityNode, geoLatKey));
    doc.setLongitude(NodeUtils.getNodeFieldAsText(entityNode, geoLongKey));
    doc.deriveFields();

  }

  @Override
  protected boolean isSyncDone() {
    int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();

    if (totalWorkOnHand > 0 || !allWorkEnumerated) {
      return false;
    }

    return true;
  }

}