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