Adding UI extensibility
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / sync / SyncControllerService.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.onap.aai.sparky.sync;
24
25 import java.lang.Thread.UncaughtExceptionHandler;
26 import java.util.concurrent.ExecutorService;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.ScheduledExecutorService;
29 import java.util.concurrent.TimeUnit;
30
31 import org.onap.aai.cl.api.Logger;
32 import org.onap.aai.cl.eelf.LoggerFactory;
33 import org.onap.aai.sparky.logging.AaiUiMsgs;
34 import org.onap.aai.sparky.sync.SyncControllerImpl.SyncActions;
35 import org.onap.aai.sparky.sync.enumeration.OperationState;
36 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
37 import org.springframework.context.ApplicationListener;
38 import org.springframework.context.event.ApplicationContextEvent;
39
40 import com.google.common.util.concurrent.ThreadFactoryBuilder;
41
42 public class SyncControllerService implements ApplicationListener<ApplicationContextEvent> {
43
44   private SyncControllerRegistry syncControllerRegistry;
45   private ExecutorService runonceSyncExecutor;
46   private ScheduledExecutorService periodicSyncExecutor;
47   private boolean syncStarted;
48
49   private static final Logger LOG =
50       LoggerFactory.getInstance().getLogger(SyncControllerService.class);
51
52   private class SyncControllerTask implements Runnable {
53
54     private SyncController controller;
55
56     public SyncControllerTask(SyncController controller) {
57       this.controller = controller;
58     }
59
60     @Override
61     public void run() {
62
63       try {
64
65         if (controller.getState() == SynchronizerState.IDLE) {
66
67           /*
68            * This is a blocking-call, but would be nicer if it was async internally within the
69            * controller but at the moment, that's not the way it works.
70            */
71
72           if (controller.performAction(SyncActions.SYNCHRONIZE) != OperationState.OK) {
73
74             LOG.info(AaiUiMsgs.INFO_GENERIC,
75                 controller.getControllerName() + " is not idle, sync attempt has been skipped.");
76           }
77         } else {
78
79           LOG.info(AaiUiMsgs.INFO_GENERIC,
80               controller.getControllerName() + " is not idle, sync attempt has been skipped.");
81         }
82
83       } catch (Exception exception) {
84         LOG.error(AaiUiMsgs.ERROR_GENERIC,
85             "Error while attempting synchronization.  Error = " + exception.getMessage());
86       }
87
88     }
89
90   }
91
92   public SyncControllerService(SyncControllerRegistry syncControllerRegistry, int numRunOnceWorkers,
93       int numPeriodicWorkers) {
94     this.syncControllerRegistry = syncControllerRegistry;
95     this.syncStarted = false;
96
97     UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
98
99       @Override
100       public void uncaughtException(Thread thread, Throwable exc) {
101         LOG.error(AaiUiMsgs.ERROR_GENERIC, thread.getName() + ": " + exc);
102       }
103     };
104
105     runonceSyncExecutor = Executors.newFixedThreadPool(numRunOnceWorkers,
106         new ThreadFactoryBuilder().setNameFormat("RunonceSyncWorker-%d")
107             .setUncaughtExceptionHandler(uncaughtExceptionHandler).build());
108
109
110     periodicSyncExecutor = Executors.newScheduledThreadPool(numPeriodicWorkers,
111         new ThreadFactoryBuilder().setNameFormat("PeriodicSyncWorker-%d")
112             .setUncaughtExceptionHandler(uncaughtExceptionHandler).build());
113
114   }
115
116   public SyncControllerRegistry getSyncControllerRegistry() {
117     return syncControllerRegistry;
118   }
119
120   public void startSync() {
121
122     long syncInitialDelayInMs = 0;
123
124     for (SyncController controller : syncControllerRegistry.getControllers()) {
125
126       syncInitialDelayInMs = controller.getDelayInMs();
127
128       if (!controller.isPeriodicSyncEnabled()) {
129
130         if (controller.isRunOnceSyncEnabled()) {
131           LOG.info(AaiUiMsgs.INFO_GENERIC, controller.getControllerName() + " is enabled.");
132           runonceSyncExecutor.submit(new SyncControllerTask(controller));
133         } else {
134           LOG.info(AaiUiMsgs.INFO_GENERIC, controller.getControllerName() + " is disabled.");
135         }
136
137       } else {
138
139         /**
140          * Do both. We'll take one instance of the SyncController and wrap the object instance into
141          * two SyncControllerTasks. The responsibility for preventing a conflicting sync should live
142          * in the SyncController instance. If a sync is underway when the periodic sync kicks in,
143          * then it will be ignored by the SyncController which is already underway.
144          * 
145          * The SyncController instance itself would then also be stateful such that it would know
146          * the last time it ran, and the next time it is supposed to run, the number times a sync
147          * has executed, etc.
148          */
149
150         if (controller.isRunOnceSyncEnabled()) {
151           LOG.info(AaiUiMsgs.INFO_GENERIC,
152               controller.getControllerName() + " run-once sync is enabled.");
153           runonceSyncExecutor.submit(new SyncControllerTask(controller));
154         } else {
155           LOG.info(AaiUiMsgs.INFO_GENERIC,
156               controller.getControllerName() + " run-once sync is disabled.");
157         }
158
159         /*
160          * The controller knows it's configuredfrequency and we can just ask it to tell us what the
161          * delay and frequency needs to be, rather than trying to calculate the configured frequency
162          * per controller which "could" be different for each controller.
163          */
164
165         if (controller.isPeriodicSyncEnabled()) {
166
167           LOG.info(AaiUiMsgs.INFO_GENERIC,
168               controller.getControllerName() + " periodic sync is enabled and scheduled to start @ "
169                   + controller.getNextSyncTime());
170
171           periodicSyncExecutor.scheduleAtFixedRate(new SyncControllerTask(controller),
172               controller.getDelayInMs(), controller.getSyncFrequencyInMs(), TimeUnit.MILLISECONDS);
173
174         } else {
175
176           LOG.info(AaiUiMsgs.INFO_GENERIC,
177               controller.getControllerName() + " periodic sync is disabled.");
178
179         }
180
181       }
182
183     }
184
185   }
186
187   public void shutdown() {
188
189     if (runonceSyncExecutor != null) {
190       runonceSyncExecutor.shutdown();
191     }
192
193     if (periodicSyncExecutor != null) {
194       periodicSyncExecutor.shutdown();
195     }
196
197     if (syncControllerRegistry != null) {
198       for (SyncController controller : syncControllerRegistry.getControllers()) {
199         controller.shutdown();
200       }
201     }
202
203   }
204
205   @Override
206   public synchronized void onApplicationEvent(ApplicationContextEvent arg0) {
207
208     /*
209      * Start sync service processing when spring-context-initialization has finished
210      */
211
212     if (!syncStarted) {
213       syncStarted = true;
214       startSync();
215     }
216
217   }
218
219
220 }