Catalog alignment
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / CassandraHealthCheck.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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  * Modifications copyright (c) 2018 Nokia
20  * ================================================================================
21  */
22 package org.openecomp.sdc.be.components.impl;
23
24 import com.datastax.driver.core.Cluster;
25 import com.datastax.driver.core.KeyspaceMetadata;
26 import com.datastax.driver.core.Metadata;
27 import com.datastax.driver.core.Session;
28 import org.openecomp.sdc.be.config.ConfigurationManager;
29 import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
30 import org.openecomp.sdc.be.dao.cassandra.schema.Table;
31 import org.openecomp.sdc.common.log.wrappers.Logger;
32 import org.openecomp.sdc.common.util.GeneralUtility;
33 import org.springframework.stereotype.Component;
34
35 import javax.annotation.PostConstruct;
36 import javax.annotation.PreDestroy;
37 import java.io.FileInputStream;
38 import java.io.InputStream;
39 import java.util.ArrayList;
40 import java.util.Collections;
41 import java.util.HashSet;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Properties;
45 import java.util.Set;
46
47 @Component("cassandra-health-check")
48 public class CassandraHealthCheck {
49
50     private static final Logger log = Logger.getLogger(CassandraHealthCheck.class.getName());
51
52     private String localDataCenterName = null;
53
54     private Set<String> sdcKeyspaces = new HashSet<>();
55
56     private int HC_FormulaNumber;
57
58     private SdcSchemaUtils sdcSchemaUtils;
59     
60
61     @PostConstruct
62     private void init() {
63
64         //Initialize local data center name - this field must be filled by DevOps
65         localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();
66
67         if (GeneralUtility.isEmptyString(localDataCenterName))  {
68             log.error("localDataCenter Name in configuration.yaml is missing.");
69             return;
70         }
71
72         //Collect all SDC keyspaces
73         for (Table table : Table.values()) {
74             sdcKeyspaces.add(table.getTableDescription().getKeyspace());
75         }
76
77         String janusGraphCfgFile = ConfigurationManager.getConfigurationManager()
78             .getConfiguration().getJanusGraphCfgFile();
79         Properties prop = new Properties();
80         InputStream janusGraphProp = null;
81         try {
82             //load a properties file
83             janusGraphProp = new FileInputStream(janusGraphCfgFile);
84             prop.load(janusGraphProp);
85             //Add janusgraph keyspace
86             String janusGraphKeyspace = prop.getProperty("storage.cassandra.keyspace");
87             if (!GeneralUtility.isEmptyString(janusGraphKeyspace))  {
88                 sdcKeyspaces.add(janusGraphKeyspace);
89             }
90         } catch (Exception e) {
91             log.error("Failed to open titen.properties file , url is : {}", janusGraphCfgFile, e);
92         }
93
94         log.info("All sdc keyspaces are : {}", sdcKeyspaces);
95         sdcSchemaUtils = new SdcSchemaUtils();
96         //Calculate the Formula of Health Check
97         Cluster cluster = null;
98         try {
99
100             log.info("creating cluster for Cassandra Health Check.");
101             //Create cluster from nodes in cassandra configuration
102            
103             Metadata metadata = sdcSchemaUtils.getMetadata();
104
105             if (metadata == null) {
106                 log.error("Failure get cassandra metadata.");
107                 return;
108             }
109
110             log.info("Cluster Metadata: {}", metadata);
111             List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
112             List<Integer> replactionFactorList = new ArrayList<>();
113
114             //Collect the keyspaces Replication Factor of current localDataCenter
115             for (KeyspaceMetadata keyspace : keyspaces) {
116
117                 if (sdcKeyspaces.contains(keyspace.getName()))  {
118
119                     log.info("keyspace : {} , replication: {}",  keyspace.getName(), keyspace.getReplication());
120                     Map<String, String> replicationOptions = keyspace.getReplication();
121
122                     //In 1 site with one data center
123                     if (replicationOptions.containsKey("replication_factor")) {
124                         replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
125                     }
126                     //In multiple sites with some data center
127                     else if (replicationOptions.containsKey(localDataCenterName)) {
128                         replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName)));
129                     }
130                 }
131             }
132
133             if (replactionFactorList.size() == 0)  {
134                 log.error("Replication factor NOT found in all keyspaces");
135                 return;
136             }
137
138             int maxReplicationFactor = Collections.max(replactionFactorList);
139             log.info("maxReplication Factor is: {}", maxReplicationFactor);
140
141             int localQuorum = maxReplicationFactor/2 + 1;
142             log.info("localQuorum is: {}", localQuorum);
143
144             HC_FormulaNumber = maxReplicationFactor - localQuorum;
145
146             log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber);
147
148
149         } catch (Exception e) {
150             log.error("create cassandra cluster failed with exception.", e);
151         } finally {
152             if (cluster != null) {
153                 cluster.close();
154             }
155         }
156
157     }
158     
159  
160     public boolean getCassandraStatus()  {
161
162         if (GeneralUtility.isEmptyString(localDataCenterName)) {
163             log.error("localDataCenter Name in configuration.yaml is missing.");
164             return false;
165         }
166
167        
168         Session session = null;
169         try {
170             log.info("creating cluster for Cassandra for monitoring.");           
171             
172             session = sdcSchemaUtils.connect();
173             log.info("The cassandra session is {}", session);
174             if(session == null){
175                 log.error("Failed to connect to cassandra ");
176                 return false;
177             }
178             
179             Metadata metadata = sdcSchemaUtils.getMetadata();
180
181             if (metadata == null) {
182                 log.error("Failure get cassandra metadata.");
183                 return false;
184             }
185
186             log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());
187
188             //Count the number of data center nodes that are down
189             Long downHostsNumber = metadata.getAllHosts().stream()
190                     .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
191
192             log.info("The cassandra down nodes number is {}", downHostsNumber);
193             return HC_FormulaNumber >= downHostsNumber;
194
195         } catch (Exception e) {
196             log.error("create cassandra cluster failed with exception.", e);
197             return false;
198         } finally {
199             if (session != null) {
200                 log.info("close session for Cassandra for monitoring.");
201                 session.close();
202             }
203             
204         }
205     }
206     
207     @PreDestroy
208     public void closeClient() {
209         if (sdcSchemaUtils!= null) {
210             sdcSchemaUtils.closeCluster();
211         }
212         log.info("** sdcSchemaUtils cluster closed");
213     }
214 }