aboutsummaryrefslogtreecommitdiffstats
path: root/common/openecomp-common-configuration-management/openecomp-configuration-management-core/src/main/java/org/openecomp/config/impl/ConfigurationChangeNotifier.java
blob: 5c3df4a56d6a27108c6d23c3b3acb22dd2260123 (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
package org.openecomp.config.impl;

import static org.openecomp.config.ConfigurationUtils.isArray;

import org.openecomp.config.ConfigurationUtils;
import org.openecomp.config.Constants;
import org.openecomp.config.api.ConfigurationChangeListener;
import org.openecomp.config.api.ConfigurationManager;
import org.openecomp.config.api.Hint;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;


/**
 * The type Configuration change notifier.
 */
public final class ConfigurationChangeNotifier {

  private HashMap<String, List<NotificationData>> store = new HashMap<>();
  private ScheduledExecutorService executor =
      Executors.newScheduledThreadPool(5, ConfigurationUtils.getThreadFactory());
  private ExecutorService notificationExcecutor =
      Executors.newCachedThreadPool(ConfigurationUtils.getThreadFactory());
  private Map<String, WatchService> watchServiceCollection =
      Collections.synchronizedMap(new HashMap<>());

  {
    if (!Thread.currentThread().getStackTrace()[2].getClassName()
        .equals(ConfigurationImpl.class.getName())) {
      throw new RuntimeException("Illegal access.");
    }
  }

  /**
   * Instantiates a new Configuration change notifier.
   *
   * @param inMemoryConfig the in memory config
   */
  public ConfigurationChangeNotifier(Map<String, AggregateConfiguration> inMemoryConfig) {
    executor.scheduleWithFixedDelay(() -> this
        .pollFilesystemAndUpdateConfigurationIfREquired(inMemoryConfig,
            System.getProperty("config.location"), false), 1, 1, TimeUnit.MILLISECONDS);
    executor.scheduleWithFixedDelay(() -> this
        .pollFilesystemAndUpdateConfigurationIfREquired(inMemoryConfig,
            System.getProperty("tenant.config.location"), true), 1, 1, TimeUnit.MILLISECONDS);
    executor.scheduleWithFixedDelay(() -> this
        .pollFilesystemAndUpdateNodeSpecificConfigurationIfREquired(
            System.getProperty("node.config.location")), 1, 1, TimeUnit.MILLISECONDS);
  }

  /**
   * Shutdown.
   */
  public void shutdown() {
    for (WatchService watch : watchServiceCollection.values()) {
      try {
        watch.close();
      } catch (IOException exception) {
        //do nothing
      }
    }
    executor.shutdownNow();
  }

  /**
   * Poll filesystem and update configuration if r equired.
   *
   * @param inMemoryConfig   the in memory config
   * @param location         the location
   * @param isTenantLocation the is tenant location
   */
  public void pollFilesystemAndUpdateConfigurationIfREquired(
      Map<String, AggregateConfiguration> inMemoryConfig, String location,
      boolean isTenantLocation) {
    try {
      Set<Path> paths = watchForChange(location);
      if (paths != null) {
        for (Path path : paths) {
          File file = path.toAbsolutePath().toFile();
          String repositoryKey = null;
          if (ConfigurationUtils.isConfig(file) && file.isFile()) {
            if (isTenantLocation) {
              Collection<File> tenantsRoot =
                  ConfigurationUtils.getAllFiles(new File(location), false, true);
              for (File tenantRoot : tenantsRoot) {
                if (file.getAbsolutePath().startsWith(tenantRoot.getAbsolutePath())) {
                  repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(
                      (tenantRoot.getName() + Constants.TENANT_NAMESPACE_SAPERATOR
                          + ConfigurationUtils.getNamespace(file))
                          .split(Constants.TENANT_NAMESPACE_SAPERATOR));
                }
              }
            } else {
              repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(file);
            }
            AggregateConfiguration config = inMemoryConfig.get(repositoryKey);
            if (config != null) {
              LinkedHashMap origConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
              config.addConfig(file);
              LinkedHashMap latestConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
              Map map = ConfigurationUtils.diff(origConfig, latestConfig);
              String[] tenantNamespaceArray =
                  repositoryKey.split(Constants.KEY_ELEMENTS_DELEMETER);
              updateConfigurationValues(tenantNamespaceArray[0], tenantNamespaceArray[1], map);
            }
          } else {
            Iterator<String> repoKeys = inMemoryConfig.keySet().iterator();
            while (repoKeys.hasNext()) {
              repositoryKey = repoKeys.next();
              AggregateConfiguration config = inMemoryConfig.get(repositoryKey);
              if (config.containsConfig(file)) {
                LinkedHashMap origConfig = ConfigurationUtils.toMap(config.getFinalConfiguration());
                config.removeConfig(file);
                LinkedHashMap latestConfig =
                    ConfigurationUtils.toMap(config.getFinalConfiguration());
                Map map = ConfigurationUtils.diff(origConfig, latestConfig);
                String[] tenantNamespaceArray =
                    repositoryKey.split(Constants.KEY_ELEMENTS_DELEMETER);
                updateConfigurationValues(tenantNamespaceArray[0], tenantNamespaceArray[1],
                    map);
              }
            }
          }
        }
      }
    } catch (ClosedWatchServiceException exception) {
      // do nothing.
    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }

  private void updateConfigurationValues(String tenant, String namespace, Map map)
      throws Exception {
    MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
    ObjectName mbeanName = new ObjectName(Constants.MBEAN_NAME);
    ConfigurationManager conf =
        JMX.newMBeanProxy(mbsc, mbeanName, org.openecomp.config.api.ConfigurationManager.class,
            true);
    conf.updateConfigurationValues(tenant, namespace, map);
  }

  /**
   * Poll filesystem and update node specific configuration if r equired.
   *
   * @param location the location
   */
  public void pollFilesystemAndUpdateNodeSpecificConfigurationIfREquired(String location) {
    try {
      Set<Path> paths = watchForChange(location);
      if (paths != null) {
        for (Path path : paths) {
          File file = path.toAbsolutePath().toFile();
          String repositoryKey = null;
          if (ConfigurationUtils.isConfig(file)) {
            repositoryKey = ConfigurationUtils.getConfigurationRepositoryKey(file);
            ConfigurationRepository.lookup().populateOverrideConfigurtaion(repositoryKey, file);
          } else {
            ConfigurationRepository.lookup().removeOverrideConfigurtaion(file);
          }
        }
      }
    } catch (Throwable exception) {
      exception.printStackTrace();
    }
  }

  /**
   * Notify changes towards.
   *
   * @param tenant    the tenant
   * @param component the component
   * @param key       the key
   * @param myself    the myself
   * @throws Exception the exception
   */
  public void notifyChangesTowards(String tenant, String component, String key,
                                   ConfigurationChangeListener myself) throws Exception {
    List<NotificationData> notificationList =
        store.get(tenant + Constants.KEY_ELEMENTS_DELEMETER + component);
    if (notificationList == null) {
      notificationList = Collections.synchronizedList(new ArrayList<NotificationData>());
      store.put(tenant + Constants.KEY_ELEMENTS_DELEMETER + component, notificationList);
      executor.scheduleWithFixedDelay(
          () -> triggerScanning(tenant + Constants.KEY_ELEMENTS_DELEMETER + component), 1, 30000,
          TimeUnit.MILLISECONDS);
    }
    notificationList.add(new NotificationData(tenant, component, key, myself));
  }

  /**
   * Stop notification towards.
   *
   * @param tenant    the tenant
   * @param component the component
   * @param key       the key
   * @param myself    the myself
   * @throws Exception the exception
   */
  public void stopNotificationTowards(String tenant, String component, String key,
                                      ConfigurationChangeListener myself) throws Exception {
    List<NotificationData> notificationList =
        store.get(tenant + Constants.KEY_ELEMENTS_DELEMETER + component);
    if (notificationList != null) {
      boolean removed =
          notificationList.remove(new NotificationData(tenant, component, key, myself));
      if (removed && notificationList.isEmpty()) {
        store.remove(tenant + Constants.KEY_ELEMENTS_DELEMETER + component);
      }
    }

  }

  private void triggerScanning(String key) {
    if (store.get(key) != null) {
      notificationExcecutor.submit(() -> scanForChanges(key));
    } else {
      throw new IllegalArgumentException("Notification service for " + key + " is suspended.");
    }
  }

  private void scanForChanges(String key) {
    List<NotificationData> list = store.get(key);
    if (list != null) {
      int size = list.size();
      for (int i = 0; i < size; i++) {
        NotificationData notificationData = list.get(i);
        if (notificationData.isChanged()) {
          notificationExcecutor.submit(() -> sendNotification(notificationData));
        }
      }
    }
  }

  private void sendNotification(NotificationData notificationData) {
    try {
      notificationData.dispatchNotification();
    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }

  private Set<Path> watchForChange(String location) throws Exception {
    if (location == null || location.trim().length() == 0) {
      return null;
    }
    File file = new File(location);
    if (!file.exists()) {
      return null;
    }
    Path path = file.toPath();
    Set<Path> toReturn = new HashSet<>();
    try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
      watchServiceCollection.put(location, watchService);
      path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
          StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
      for (File dir : ConfigurationUtils.getAllFiles(file, true, true)) {
        dir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
      }
      while (true) {
        final WatchKey wk = watchService.take();
        Thread.sleep(ConfigurationRepository.lookup()
            .getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
            .getLong("event.fetch.delay"));
        for (WatchEvent<?> event : wk.pollEvents()) {
          Object context = event.context();
          if (context instanceof Path) {
            File newFile = new File(((Path) wk.watchable()).toFile(), context.toString());
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
              if (newFile.isDirectory()) {
                newFile.toPath().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
                continue;
              }
            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
              if (newFile.isDirectory()) {
                continue;
              }
            }
            toReturn.add(newFile.toPath());
          }
        }
        if (toReturn.isEmpty()) {
          continue;
        }
        break;
      }
    }
    return toReturn;
  }

  /**
   * The type Notification data.
   */
  class NotificationData {

    /**
     * The Tenant.
     */
    String tenant;
    /**
     * The Namespace.
     */
    String namespace;
    /**
     * The Key.
     */
    String key;
    /**
     * The Myself.
     */
    ConfigurationChangeListener myself;
    /**
     * The Current value.
     */
    Object currentValue;
    /**
     * The Is array.
     */
    boolean isArray;

    /**
     * Instantiates a new Notification data.
     *
     * @param tenant    the tenant
     * @param component the component
     * @param key       the key
     * @param myself    the myself
     * @throws Exception the exception
     */
    public NotificationData(String tenant, String component, String key,
                            ConfigurationChangeListener myself) throws Exception {
      this.tenant = tenant;
      this.namespace = component;
      this.key = key;
      this.myself = myself;
      if (!ConfigurationRepository.lookup().getConfigurationFor(tenant, component)
          .containsKey(key)) {
        throw new RuntimeException("Key[" + key + "] not found.");
      }
      isArray = isArray(tenant, component, key, Hint.DEFAULT.value());
      if (isArray) {
        currentValue = ConfigurationManager.lookup().getAsStringValues(tenant, component, key);
      } else {
        currentValue = ConfigurationManager.lookup().getAsString(tenant, component, key);
      }
    }

    @Override
    public boolean equals(Object obj) {
      if (!(obj instanceof NotificationData)) {
        return false;
      }
      NotificationData nd = (NotificationData) obj;
      return tenant.equals(nd.tenant) && namespace.equals(nd.namespace) && key.equals(nd.key)
          && myself.equals(nd.myself);
    }

    /**
     * Is changed boolean.
     *
     * @return the boolean
     */
    public boolean isChanged() {
      Object latestValue;
      try {
        if (isArray) {
          latestValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
        } else {
          latestValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
        }
        if (!isArray) {
          return !currentValue.equals(latestValue);
        } else {
          Collection<String> oldCollection = (Collection<String>) currentValue;
          Collection<String> newCollection = (Collection<String>) latestValue;
          for (String val : oldCollection) {
            if (!newCollection.remove(val)) {
              return true;
            }
          }
          return !newCollection.isEmpty();
        }
      } catch (Exception exception) {
        return false;
      }
    }

    /**
     * Dispatch notification.
     *
     * @throws Exception the exception
     */
    public void dispatchNotification() throws Exception {
      Method method = null;
      Vector<Object> parameters = null;
      try {
        Object latestValue = null;
        if (isArray) {
          latestValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
        } else {
          latestValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
        }
        Method[] methods = myself.getClass().getDeclaredMethods();
        if (methods != null && methods.length > 0) {
          method = methods[0];
          int paramCount = method.getParameterCount();
          parameters = new Vector<>();
          if (paramCount > 4) {
            if (tenant.equals(Constants.DEFAULT_TENANT)) {
              parameters.add(null);
            } else {
              parameters.add(tenant);
            }
          }
          if (paramCount > 3) {
            if (namespace.equals(Constants.DEFAULT_NAMESPACE)) {
              parameters.add(null);
            } else {
              parameters.add(namespace);
            }
          }
          parameters.add(key);
          parameters.add(currentValue);
          parameters.add(latestValue);
          method.setAccessible(true);
        }
      } catch (Exception exception) {
        exception.printStackTrace();
      } finally {
        isArray = isArray(tenant, namespace, key, Hint.DEFAULT.value());
        if (isArray) {
          currentValue = ConfigurationManager.lookup().getAsStringValues(tenant, namespace, key);
        } else {
          currentValue = ConfigurationManager.lookup().getAsString(tenant, namespace, key);
        }
        if (method != null && parameters != null) {
          method.invoke(myself, parameters.toArray());
        }
      }
    }
  }
}