Support TOSCA functions in sub properties
[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.KeyspaceMetadata;
25 import com.datastax.driver.core.Metadata;
26 import com.datastax.driver.core.Session;
27 import java.io.FileInputStream;
28 import java.io.InputStream;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Properties;
35 import java.util.Set;
36 import javax.annotation.PostConstruct;
37 import javax.annotation.PreDestroy;
38 import org.openecomp.sdc.be.config.ConfigurationManager;
39 import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
40 import org.openecomp.sdc.be.dao.cassandra.schema.Table;
41 import org.openecomp.sdc.common.log.wrappers.Logger;
42 import org.openecomp.sdc.common.util.GeneralUtility;
43 import org.springframework.stereotype.Component;
44
45 @Component("cassandra-health-check")
46 public class CassandraHealthCheck {
47
48     private static final Logger log = Logger.getLogger(CassandraHealthCheck.class);
49     private final Set<String> sdcKeyspaces = new HashSet<>();
50     private String localDataCenterName;
51     private int HC_FormulaNumber;
52     private SdcSchemaUtils sdcSchemaUtils;
53
54     @PostConstruct
55     private void init() {
56         //Initialize local data center name - this field must be filled by DevOps
57         localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();
58         if (GeneralUtility.isEmptyString(localDataCenterName)) {
59             log.error("localDataCenter Name in configuration.yaml is missing.");
60             return;
61         }
62         //Collect all SDC keyspaces
63         for (Table table : Table.values()) {
64             sdcKeyspaces.add(table.getTableDescription().getKeyspace());
65         }
66         String janusGraphCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphCfgFile();
67         Properties prop = new Properties();
68         try (final InputStream janusGraphProp = new FileInputStream(janusGraphCfgFile)) {
69             //load a properties file
70             prop.load(janusGraphProp);
71             //Add janusgraph keyspace
72             String janusGraphKeyspace = prop.getProperty("storage.cassandra.keyspace");
73             if (!GeneralUtility.isEmptyString(janusGraphKeyspace)) {
74                 sdcKeyspaces.add(janusGraphKeyspace);
75             }
76         } catch (Exception e) {
77             log.error("Failed to open janusGraph.properties file , url is : {}", janusGraphCfgFile, e);
78         }
79         log.info("All sdc keyspaces are : {}", sdcKeyspaces);
80         sdcSchemaUtils = new SdcSchemaUtils();
81         //Calculate the Formula of Health Check
82         try {
83             log.info("creating cluster for Cassandra Health Check.");
84             //Create cluster from nodes in cassandra configuration
85             Metadata metadata = sdcSchemaUtils.getMetadata();
86             if (metadata == null) {
87                 log.error("Failure get cassandra metadata.");
88                 return;
89             }
90             log.info("Cluster Metadata: {}", metadata);
91             List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
92             List<Integer> replactionFactorList = new ArrayList<>();
93             //Collect the keyspaces Replication Factor of current localDataCenter
94             for (KeyspaceMetadata keyspace : keyspaces) {
95                 if (sdcKeyspaces.contains(keyspace.getName())) {
96                     log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication());
97                     Map<String, String> replicationOptions = keyspace.getReplication();
98                     //In 1 site with one data center
99                     if (replicationOptions.containsKey("replication_factor")) {
100                         replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
101                     }
102                     //In multiple sites with some data center
103                     else if (replicationOptions.containsKey(localDataCenterName)) {
104                         replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName)));
105                     }
106                 }
107             }
108             if (replactionFactorList.isEmpty()) {
109                 log.error("Replication factor NOT found in all keyspaces");
110                 return;
111             }
112             int maxReplicationFactor = Collections.max(replactionFactorList);
113             log.info("maxReplication Factor is: {}", maxReplicationFactor);
114             int localQuorum = maxReplicationFactor / 2 + 1;
115             log.info("localQuorum is: {}", localQuorum);
116             HC_FormulaNumber = maxReplicationFactor - localQuorum;
117             log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber);
118         } catch (Exception e) {
119             log.error("create cassandra cluster failed with exception.", e);
120         }
121     }
122
123     public boolean getCassandraStatus() {
124         if (GeneralUtility.isEmptyString(localDataCenterName)) {
125             log.error("localDataCenter Name in configuration.yaml is missing.");
126             return false;
127         }
128         try (final Session session = sdcSchemaUtils.connect()) {
129             log.info("creating cluster for Cassandra for monitoring.");
130             log.info("The cassandra session is {}", session);
131             if (session == null) {
132                 log.error("Failed to connect to cassandra ");
133                 return false;
134             }
135             Metadata metadata = sdcSchemaUtils.getMetadata();
136             if (metadata == null) {
137                 log.error("Failure get cassandra metadata.");
138                 return false;
139             }
140             log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());
141             //Count the number of data center nodes that are down
142             Long downHostsNumber = metadata.getAllHosts().stream().filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
143             log.info("The cassandra down nodes number is {}", downHostsNumber);
144             return HC_FormulaNumber >= downHostsNumber;
145         } catch (Exception e) {
146             log.error("create cassandra cluster failed with exception.", e);
147             return false;
148         }
149     }
150
151     @PreDestroy
152     public void closeClient() {
153         if (sdcSchemaUtils != null) {
154             sdcSchemaUtils.closeCluster();
155         }
156         log.info("** sdcSchemaUtils cluster closed");
157     }
158 }