Catalog alignment
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / catalog / impl / DmaapProducerHealth.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.catalog.impl;
22
23 import org.openecomp.sdc.be.config.BeEcompErrorManager;
24 import org.openecomp.sdc.be.config.ConfigurationManager;
25 import org.openecomp.sdc.be.config.DmaapProducerConfiguration;
26 import org.openecomp.sdc.common.api.Constants;
27 import org.openecomp.sdc.common.api.HealthCheckInfo;
28 import org.openecomp.sdc.common.log.wrappers.Logger;
29 import org.springframework.stereotype.Component;
30
31 import javax.annotation.PostConstruct;
32 import javax.annotation.PreDestroy;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.ScheduledFuture;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.atomic.AtomicBoolean;
38
39 @Component("dmaapProducerHealth")
40 public class DmaapProducerHealth {
41
42
43     private static final String DMAAP_HEALTH_LOG_CONTEXT = "dmaapProducer.healthcheck";
44     private static final String DMAAP_HEALTH_CHECK_STR = "dmaapProducerHealthCheck";
45     private static final Logger log = Logger.getLogger(DmaapProducerHealth.class.getName());
46     private static final Logger logHealth = Logger.getLogger(DMAAP_HEALTH_LOG_CONTEXT);
47     private HealthCheckInfo healthCheckInfo = DmaapProducerHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
48     private long healthCheckReadTimeout = 20;
49     private long reconnectInterval = 5;
50     private HealthCheckScheduledTask healthCheckScheduledTask = null ;
51     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
52     private ScheduledFuture<?> scheduledFuture = null;
53     private DmaapProducerConfiguration configuration = null ;
54
55     private volatile AtomicBoolean lastHealthState = new AtomicBoolean(false);
56     private volatile AtomicBoolean reportedHealthState = null;
57
58     public enum HealthCheckInfoResult {
59         OK(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())),
60         UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())),
61         DOWN(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription()));
62
63         private HealthCheckInfo healthCheckInfo;
64         HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
65             this.healthCheckInfo = healthCheckInfo;
66         }
67         public HealthCheckInfo getHealthCheckInfo() {
68             return healthCheckInfo;
69         }
70     }
71
72     public enum DmaapStatusDescription {
73         OK("OK"), UNAVAILABLE("DmaapProducer is not available"),DOWN("DOWN"), NOT_CONFIGURED("DmaapProducer configuration is missing/wrong ");
74
75         private String desc;
76         DmaapStatusDescription(String desc) {
77             this.desc = desc;
78         }
79         public String getDescription() {
80             return desc;
81         }
82
83     }
84
85     @PostConstruct
86     public DmaapProducerHealth init() {
87         log.trace("Enter init method of DmaapProducer health");
88         synchronized (DmaapProducerHealth.class){
89             this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapProducerConfiguration();
90
91             Integer pollingInterval = configuration.getPollingInterval();
92             if (pollingInterval != null && pollingInterval!=0) {
93                 reconnectInterval = pollingInterval;
94             }
95             Integer healthCheckReadTimeoutConfig = configuration.getTimeoutMs();
96             if (healthCheckReadTimeoutConfig != null) {
97                 this.healthCheckReadTimeout = healthCheckReadTimeoutConfig;
98             }
99             this.healthCheckScheduledTask = new HealthCheckScheduledTask( configuration ); //what is the representation? csv? delimiter? json or other
100             startHealthCheckTask(true);
101         }
102         log.trace("Exit init method of DistributionEngineClusterHealth");
103         return this;
104     }
105
106     @PreDestroy
107     protected void destroy() {
108         if (scheduledFuture != null) {
109             scheduledFuture.cancel(true);
110             scheduledFuture = null;
111         }
112         if (scheduler != null) {
113             scheduler.shutdown();
114         }
115     }
116
117     /**
118      * Start health check task.
119      *
120      * @param startTask
121      */
122     private void startHealthCheckTask(boolean startTask) {
123         synchronized (DmaapProducerHealth.class){
124             if (startTask && this.scheduledFuture == null) {
125                 this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS);
126             }
127         }
128     }
129
130     void report(Boolean isUp){
131         if (reportedHealthState == null)
132             reportedHealthState = new AtomicBoolean(isUp);
133         reportedHealthState.set(isUp);
134     }
135
136
137     public HealthCheckInfo getHealthCheckInfo() {
138         return healthCheckInfo;
139     }
140
141     /**
142      * Health Check Task Scheduler - infinite check.
143      */
144     public class HealthCheckScheduledTask implements Runnable {
145         private final DmaapProducerConfiguration config;
146         private static final int TIMEOUT = 8192;
147
148         HealthCheckScheduledTask(final DmaapProducerConfiguration config){
149             this.config = config;
150         }
151         @Override
152         public void run() {
153             logHealth.trace("Executing Dmaap Health Check Task - Start");
154             boolean prevIsReachable;
155             boolean reachable;
156             //first try simple ping
157             try{
158                 if ( reportedHealthState != null ){
159                     reachable = reportedHealthState.get();
160                 }
161                 else{
162                     reachable =  false;
163                 }
164                 prevIsReachable = lastHealthState.getAndSet( reachable );
165                 healthCheckInfo = reachable ? HealthCheckInfoResult.OK.healthCheckInfo : HealthCheckInfoResult.DOWN.healthCheckInfo;
166             }
167             catch( Exception e ){
168                 log.debug("{} - cannot check connectivity -> {}",DMAAP_HEALTH_CHECK_STR, e );
169                 prevIsReachable = lastHealthState.getAndSet(false);
170                 healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.healthCheckInfo;
171             }
172             if (prevIsReachable != lastHealthState.get())
173                 logAlarm( lastHealthState.get() );
174         }
175
176
177        
178
179         private void logAlarm(boolean lastHealthState) {
180             try{
181                 if ( lastHealthState ) {
182                     BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery( DMAAP_HEALTH_CHECK_STR );
183                 } else {
184                     BeEcompErrorManager.getInstance().logDmaapHealthCheckError( DMAAP_HEALTH_CHECK_STR );
185                 }
186             }catch( Exception e ){
187                 log.debug("cannot logAlarm -> {}" ,e );
188             }
189         }
190
191     }
192
193    
194 }