summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp/sparky/synchronizer/AbstractEntitySynchronizer.java
blob: 55578b4d7931cfcaa983035a6ee2434dd4d9b34a (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
/**
 * ============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 java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.EnumSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

import org.openecomp.cl.api.Logger;
import org.openecomp.sparky.config.oxm.OxmModelLoader;
import org.openecomp.sparky.dal.NetworkTransaction;
import org.openecomp.sparky.dal.aai.ActiveInventoryDataProvider;
import org.openecomp.sparky.dal.aai.ActiveInventoryEntityStatistics;
import org.openecomp.sparky.dal.aai.ActiveInventoryProcessingExceptionStatistics;
import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
import org.openecomp.sparky.dal.elasticsearch.ElasticSearchDataProvider;
import org.openecomp.sparky.dal.elasticsearch.ElasticSearchEntityStatistics;
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.dal.rest.RestOperationalStatistics;
import org.openecomp.sparky.logging.AaiUiMsgs;
import org.openecomp.sparky.util.NodeUtils;

import org.openecomp.cl.mdc.MdcContext;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * The Class AbstractEntitySynchronizer.
 *
 * @author davea.
 */
public abstract class AbstractEntitySynchronizer {

  protected static final int VERSION_CONFLICT_EXCEPTION_CODE = 409;
  protected static final Integer RETRY_COUNT_PER_ENTITY_LIMIT = new Integer(3);

  protected final Logger logger;
  protected ObjectMapper mapper;
  protected OxmModelLoader oxmModelLoader;
  protected long syncDurationInMs;
  /**
   * The Enum StatFlag.
   */
  protected enum StatFlag {
    AAI_REST_STATS, AAI_ENTITY_STATS, AAI_PROCESSING_EXCEPTION_STATS,
    AAI_TASK_PROCESSING_STATS, ES_REST_STATS, ES_ENTITY_STATS, ES_TASK_PROCESSING_STATS
  }

  protected EnumSet<StatFlag> enabledStatFlags;

  protected ActiveInventoryDataProvider aaiDataProvider;
  protected ElasticSearchDataProvider esDataProvider;

  protected ExecutorService synchronizerExecutor;
  protected ExecutorService aaiExecutor;
  protected ExecutorService esExecutor;

  private RestOperationalStatistics esRestStats;
  protected ElasticSearchEntityStatistics esEntityStats;

  private RestOperationalStatistics aaiRestStats;
  protected ActiveInventoryEntityStatistics aaiEntityStats;
  private ActiveInventoryProcessingExceptionStatistics aaiProcessingExceptionStats;

  private TaskProcessingStats aaiTaskProcessingStats;
  private TaskProcessingStats esTaskProcessingStats;

  private TransactionRateController aaiTransactionRateController;
  private TransactionRateController esTransactionRateController;

  protected AtomicInteger aaiWorkOnHand;
  protected AtomicInteger esWorkOnHand;
  protected String synchronizerName;

  protected abstract boolean isSyncDone();
  protected boolean shouldSkipSync;
  
  public String getActiveInventoryStatisticsReport() {

    StringBuilder sb = new StringBuilder(128);

    if (enabledStatFlags.contains(StatFlag.AAI_REST_STATS)) {
      sb.append("\n\n        ").append("REST Operational Stats:");
      sb.append(aaiRestStats.getStatisticsReport());
    }

    if (enabledStatFlags.contains(StatFlag.AAI_ENTITY_STATS)) {
      sb.append("\n\n        ").append("Entity Stats:");
      sb.append(aaiEntityStats.getStatisticsReport());
    }

    if (enabledStatFlags.contains(StatFlag.AAI_PROCESSING_EXCEPTION_STATS)) {
      sb.append("\n\n        ").append("Processing Exception Stats:");
      sb.append(aaiProcessingExceptionStats.getStatisticsReport());
    }

    return sb.toString();

  }

  public String getElasticSearchStatisticsReport() {

    StringBuilder sb = new StringBuilder(128);

    if (enabledStatFlags.contains(StatFlag.ES_REST_STATS)) {
      sb.append("\n\n        ").append("REST Operational Stats:");
      sb.append(esRestStats.getStatisticsReport());
    }

    if (enabledStatFlags.contains(StatFlag.ES_ENTITY_STATS)) {
      sb.append("\n\n        ").append("Entity Stats:");
      sb.append(esEntityStats.getStatisticsReport());
    }

    return sb.toString();

  }

  /**
   * Adds the active inventory stat report.
   *
   * @param sb the sb
   */
  private void addActiveInventoryStatReport(StringBuilder sb) {

    if (sb == null) {
      return;
    }

    sb.append("\n\n    AAI");
    sb.append(getActiveInventoryStatisticsReport());

    double currentTps = 0;
    if (enabledStatFlags.contains(StatFlag.AAI_TASK_PROCESSING_STATS)) {
      sb.append("\n\n        ").append("Task Processor Stats:");
      sb.append(aaiTaskProcessingStats.getStatisticsReport(false, "        "));

      currentTps = aaiTransactionRateController.getCurrentTps();

      sb.append("\n          ").append("Current TPS: ").append(currentTps);
    }

    sb.append("\n          ").append("Current WOH: ").append(aaiWorkOnHand.get());

    if (enabledStatFlags.contains(StatFlag.AAI_TASK_PROCESSING_STATS)) {
      if (currentTps > 0) {
        double numMillisecondsToCompletion = (aaiWorkOnHand.get() / currentTps) * 1000;
        sb.append("\n            ").append("SyncDurationRemaining=")
            .append(NodeUtils.getDurationBreakdown((long) numMillisecondsToCompletion));
      }
    }

  }

  /**
   * Adds the elastic stat report.
   *
   * @param sb the sb
   */
  private void addElasticStatReport(StringBuilder sb) {

    if (sb == null) {
      return;
    }

    sb.append("\n\n    ELASTIC");
    sb.append(getElasticSearchStatisticsReport());

    double currentTps = 0;

    if (enabledStatFlags.contains(StatFlag.ES_TASK_PROCESSING_STATS)) {
      sb.append("\n\n        ").append("Task Processor Stats:");
      sb.append(esTaskProcessingStats.getStatisticsReport(false, "           "));

      currentTps = esTransactionRateController.getCurrentTps();

      sb.append("\n        ").append("Current TPS: ").append(currentTps);
    }

    sb.append("\n        ").append("Current WOH: ").append(esWorkOnHand.get());

    if (enabledStatFlags.contains(StatFlag.ES_TASK_PROCESSING_STATS)) {
      if (currentTps > 0) {
        double numMillisecondsToCompletion = (esWorkOnHand.get() / currentTps) * 1000;
        sb.append("\n            ").append("SyncDurationRemaining=")
            .append(NodeUtils.getDurationBreakdown((long) numMillisecondsToCompletion));
      }
    }


  }

  /**
   * Gets the stat report.
   *
   * @param syncOpTimeInMs the sync op time in ms
   * @param showFinalReport the show final report
   * @return the stat report
   */
  protected String getStatReport(long syncOpTimeInMs, boolean showFinalReport) {

    StringBuilder sb = new StringBuilder(128);

    sb.append("\n").append(synchronizerName + " Statistics: ( Sync Operation Duration = "
        + NodeUtils.getDurationBreakdown(syncOpTimeInMs) + " )");

    addActiveInventoryStatReport(sb);
    addElasticStatReport(sb);

    if (showFinalReport) {
      sb.append("\n\n        ").append("Sync Completed!\n");
    } else {
      sb.append("\n\n        ").append("Sync in Progress...\n");
    }

    return sb.toString();

  }

  protected String indexName;
  protected long syncStartedTimeStampInMs;

  /**
   * Instantiates a new abstract entity synchronizer.
   *
   * @param logger the logger
   * @param syncName the sync name
   * @param numSyncWorkers the num sync workers
   * @param numActiveInventoryWorkers the num active inventory workers
   * @param numElasticsearchWorkers the num elasticsearch workers
   * @param indexName the index name
   * @throws Exception the exception
   */
  protected AbstractEntitySynchronizer(Logger logger, String syncName, int numSyncWorkers,
      int numActiveInventoryWorkers, int numElasticsearchWorkers, String indexName)
          throws Exception {
    this.logger = logger;
    this.synchronizerExecutor =
        NodeUtils.createNamedExecutor(syncName + "-INTERNAL", numSyncWorkers, logger);
    this.aaiExecutor =
        NodeUtils.createNamedExecutor(syncName + "-AAI", numActiveInventoryWorkers, logger);
    this.esExecutor =
        NodeUtils.createNamedExecutor(syncName + "-ES", numElasticsearchWorkers, logger);
    this.mapper = new ObjectMapper();
    this.oxmModelLoader = OxmModelLoader.getInstance();
    this.indexName = indexName;
    this.esRestStats = new RestOperationalStatistics();
    this.esEntityStats = new ElasticSearchEntityStatistics(oxmModelLoader);
    this.aaiRestStats = new RestOperationalStatistics();
    this.aaiEntityStats = new ActiveInventoryEntityStatistics(oxmModelLoader);
    this.aaiProcessingExceptionStats = new ActiveInventoryProcessingExceptionStatistics();
    this.aaiTaskProcessingStats =
        new TaskProcessingStats(ActiveInventoryConfig.getConfig().getTaskProcessorConfig());
    this.esTaskProcessingStats =
        new TaskProcessingStats(ElasticSearchConfig.getConfig().getProcessorConfig());

    this.aaiTransactionRateController =
        new TransactionRateController(ActiveInventoryConfig.getConfig().getTaskProcessorConfig());
    this.esTransactionRateController =
        new TransactionRateController(ElasticSearchConfig.getConfig().getProcessorConfig());

    this.aaiWorkOnHand = new AtomicInteger(0);
    this.esWorkOnHand = new AtomicInteger(0);

    enabledStatFlags = EnumSet.allOf(StatFlag.class);

    this.synchronizerName = "Abstact Entity Synchronizer";
    
    String txnID = NodeUtils.getRandomTxnId();
	MdcContext.initialize(txnID, "AbstractEntitySynchronizer", "", "Sync", "");
	
	this.shouldSkipSync = false;
    this.syncStartedTimeStampInMs = System.currentTimeMillis();
    this.syncDurationInMs = -1;
  }

  public boolean shouldSkipSync() {
    return shouldSkipSync;
  }

  public void setShouldSkipSync(boolean shouldSkipSync) {
    this.shouldSkipSync = shouldSkipSync;
  }

  /**
   * Inc active inventory work on hand counter.
   */
  protected void incActiveInventoryWorkOnHandCounter() {
    aaiWorkOnHand.incrementAndGet();
  }

  /**
   * Dec active inventory work on hand counter.
   */
  protected void decActiveInventoryWorkOnHandCounter() {
    aaiWorkOnHand.decrementAndGet();
  }

  /**
   * Inc elastic search work on hand counter.
   */
  protected void incElasticSearchWorkOnHandCounter() {
    esWorkOnHand.incrementAndGet();
  }

  /**
   * Dec elastic search work on hand counter.
   */
  protected void decElasticSearchWorkOnHandCounter() {
    esWorkOnHand.decrementAndGet();
  }

  /**
   * Shutdown executors.
   */
  protected void shutdownExecutors() {
    try {
      synchronizerExecutor.shutdown();
      aaiExecutor.shutdown();
      esExecutor.shutdown();
      aaiDataProvider.shutdown();
      esDataProvider.shutdown();
    } catch (Exception exc) {
      logger.error(AaiUiMsgs.ERROR_SHUTDOWN_EXECUTORS, exc );
    }
  }

  /**
   * Clear cache.
   */
  public void clearCache() {
    if (aaiDataProvider != null) {
      aaiDataProvider.clearCache();
    }
  }

  protected ActiveInventoryDataProvider getAaiDataProvider() {
    return aaiDataProvider;
  }

  public void setAaiDataProvider(ActiveInventoryDataProvider aaiDataProvider) {
    this.aaiDataProvider = aaiDataProvider;
  }

  protected ElasticSearchDataProvider getEsDataProvider() {
    return esDataProvider;
  }

  public void setEsDataProvider(ElasticSearchDataProvider provider) {
    this.esDataProvider = provider;
  }

  /**
   * Gets the elastic full url.
   *
   * @param resourceUrl the resource url
   * @param indexName the index name
   * @param indexType the index type
   * @return the elastic full url
   * @throws Exception the exception
   */
  protected String getElasticFullUrl(String resourceUrl, String indexName, String indexType)
      throws Exception {
    return ElasticSearchConfig.getConfig().getElasticFullUrl(resourceUrl, indexName, indexType);
  }

  /**
   * Gets the elastic full url.
   *
   * @param resourceUrl the resource url
   * @param indexName the index name
   * @return the elastic full url
   * @throws Exception the exception
   */
  protected String getElasticFullUrl(String resourceUrl, String indexName) throws Exception {
    return ElasticSearchConfig.getConfig().getElasticFullUrl(resourceUrl, indexName);
  }

  public String getIndexName() {
    return indexName;
  }

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


  /**
   * Gets the response length.
   *
   * @param txn the txn
   * @return the response length
   */
  private long getResponseLength(NetworkTransaction txn) {

    if (txn == null) {
      return -1;
    }

    OperationResult result = txn.getOperationResult();

    if (result == null) {
      return -1;
    }

    if (result.getResult() != null) {
      return result.getResult().length();
    }

    return -1;
  }

  /**
   * Update elastic search counters.
   *
   * @param method the method
   * @param or the or
   */
  protected void updateElasticSearchCounters(HttpMethod method, OperationResult or) {
    updateElasticSearchCounters(new NetworkTransaction(method, null, or));
  }

  /**
   * Update elastic search counters.
   *
   * @param method the method
   * @param entityType the entity type
   * @param or the or
   */
  protected void updateElasticSearchCounters(HttpMethod method, String entityType,
      OperationResult or) {
    updateElasticSearchCounters(new NetworkTransaction(method, entityType, or));
  }

  /**
   * Update elastic search counters.
   *
   * @param txn the txn
   */
  protected void updateElasticSearchCounters(NetworkTransaction txn) {

    if (enabledStatFlags.contains(StatFlag.ES_REST_STATS)) {
      esRestStats.updateCounters(txn);
    }

    if (enabledStatFlags.contains(StatFlag.ES_ENTITY_STATS)) {
      esEntityStats.updateCounters(txn);
    }

    if (enabledStatFlags.contains(StatFlag.ES_TASK_PROCESSING_STATS)) {

      esTransactionRateController.trackResponseTime(txn.getOperationResult().getResponseTimeInMs());

      esTaskProcessingStats
          .updateTaskResponseStatsHistogram(txn.getOperationResult().getResponseTimeInMs());
      esTaskProcessingStats.updateTaskAgeStatsHistogram(txn.getTaskAgeInMs());

      // don't know the cost of the lengh calc, we'll see if it causes a
      // problem

      long responsePayloadSizeInBytes = getResponseLength(txn);
      if (responsePayloadSizeInBytes >= 0) {
        esTaskProcessingStats.updateResponseSizeInBytesHistogram(responsePayloadSizeInBytes);
      }

      esTaskProcessingStats
          .updateTransactionsPerSecondHistogram((long) esTransactionRateController.getCurrentTps());
    }
  }

  /**
   * Update active inventory counters.
   *
   * @param method the method
   * @param or the or
   */
  protected void updateActiveInventoryCounters(HttpMethod method, OperationResult or) {
    updateActiveInventoryCounters(new NetworkTransaction(method, null, or));
  }

  /**
   * Update active inventory counters.
   *
   * @param method the method
   * @param entityType the entity type
   * @param or the or
   */
  protected void updateActiveInventoryCounters(HttpMethod method, String entityType,
      OperationResult or) {
    updateActiveInventoryCounters(new NetworkTransaction(method, entityType, or));
  }

  /**
   * Update active inventory counters.
   *
   * @param txn the txn
   */
  protected void updateActiveInventoryCounters(NetworkTransaction txn) {

    if (enabledStatFlags.contains(StatFlag.AAI_REST_STATS)) {
      aaiRestStats.updateCounters(txn);
    }

    if (enabledStatFlags.contains(StatFlag.AAI_ENTITY_STATS)) {
      aaiEntityStats.updateCounters(txn);
    }

    if (enabledStatFlags.contains(StatFlag.AAI_PROCESSING_EXCEPTION_STATS)) {
      aaiProcessingExceptionStats.updateCounters(txn);
    }

    if (enabledStatFlags.contains(StatFlag.AAI_TASK_PROCESSING_STATS)) {
      aaiTransactionRateController
          .trackResponseTime(txn.getOperationResult().getResponseTimeInMs());

      aaiTaskProcessingStats
          .updateTaskResponseStatsHistogram(txn.getOperationResult().getResponseTimeInMs());
      aaiTaskProcessingStats.updateTaskAgeStatsHistogram(txn.getTaskAgeInMs());

      // don't know the cost of the lengh calc, we'll see if it causes a
      // problem

      long responsePayloadSizeInBytes = getResponseLength(txn);
      if (responsePayloadSizeInBytes >= 0) {
        aaiTaskProcessingStats.updateResponseSizeInBytesHistogram(responsePayloadSizeInBytes);
      }

      aaiTaskProcessingStats.updateTransactionsPerSecondHistogram(
          (long) aaiTransactionRateController.getCurrentTps());
    }
  }

  /**
   * Reset counters.
   */
  protected void resetCounters() {
    aaiRestStats.reset();
    aaiEntityStats.reset();
    aaiProcessingExceptionStats.reset();

    esRestStats.reset();
    esEntityStats.reset();
  }

}