aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
blob: 56cad89569c89f7aa86caad62c5a58de8ffa4962 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 * Modifications copyright (c) 2018 Nokia
 * ================================================================================
 */
package org.openecomp.sdc.be.components.impl;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
import org.openecomp.sdc.be.dao.cassandra.schema.Table;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

@Component("cassandra-health-check")
public class CassandraHealthCheck {

    private static final Logger log = Logger.getLogger(CassandraHealthCheck.class.getName());

    private String localDataCenterName = null;

    private Set<String> sdcKeyspaces = new HashSet<>();

    private int HC_FormulaNumber;

    private SdcSchemaUtils sdcSchemaUtils;

    @PostConstruct
    private void init() {

        //Initialize local data center name - this field must be filled by DevOps
        localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();

        if (GeneralUtility.isEmptyString(localDataCenterName))  {
            log.error("localDataCenter Name in configuration.yaml is missing.");
            return;
        }

        //Collect all SDC keyspaces
        for (Table table : Table.values()) {
            sdcKeyspaces.add(table.getTableDescription().getKeyspace());
        }

        String janusGraphCfgFile = ConfigurationManager.getConfigurationManager()
            .getConfiguration().getJanusGraphCfgFile();
        Properties prop = new Properties();
        InputStream janusGraphProp = null;
        try {
            //load a properties file
            janusGraphProp = new FileInputStream(janusGraphCfgFile);
            prop.load(janusGraphProp);
            //Add janusgraph keyspace
            String janusGraphKeyspace = prop.getProperty("storage.cassandra.keyspace");
            if (!GeneralUtility.isEmptyString(janusGraphKeyspace))  {
                sdcKeyspaces.add(janusGraphKeyspace);
            }
        } catch (Exception e) {
            log.error("Failed to open titen.properties file , url is : {}", janusGraphCfgFile, e);
        }

        log.info("All sdc keyspaces are : {}", sdcKeyspaces);
        sdcSchemaUtils = new SdcSchemaUtils();
        //Calculate the Formula of Health Check
        Cluster cluster = null;
        try {

            log.info("creating cluster for Cassandra Health Check.");
            //Create cluster from nodes in cassandra configuration
            cluster = sdcSchemaUtils.createCluster();
            if (cluster == null) {
                log.error("Failure create cassandra cluster.");
                return;
            }

            Metadata metadata = cluster.getMetadata();

            if (metadata == null) {
                log.error("Failure get cassandra metadata.");
                return;
            }

            log.info("Cluster Metadata: {}", metadata);
            List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
            List<Integer> replactionFactorList = new ArrayList<>();

            //Collect the keyspaces Replication Factor of current localDataCenter
            for (KeyspaceMetadata keyspace : keyspaces) {

                if (sdcKeyspaces.contains(keyspace.getName()))  {

                    log.info("keyspace : {} , replication: {}",  keyspace.getName(), keyspace.getReplication());
                    Map<String, String> replicationOptions = keyspace.getReplication();

                    //In 1 site with one data center
                    if (replicationOptions.containsKey("replication_factor")) {
                        replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
                    }
                    //In multiple sites with some data center
                    else if (replicationOptions.containsKey(localDataCenterName)) {
                        replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName)));
                    }
                }
            }

            if (replactionFactorList.size() == 0)  {
                log.error("Replication factor NOT found in all keyspaces");
                return;
            }

            int maxReplicationFactor = Collections.max(replactionFactorList);
            log.info("maxReplication Factor is: {}", maxReplicationFactor);

            int localQuorum = maxReplicationFactor/2 + 1;
            log.info("localQuorum is: {}", localQuorum);

            HC_FormulaNumber = maxReplicationFactor - localQuorum;

            log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber);


        } catch (Exception e) {
            log.error("create cassandra cluster failed with exception.", e);
        } finally {
            if (cluster != null) {
                cluster.close();
            }
        }

    }

    public boolean getCassandraStatus()  {

        if (GeneralUtility.isEmptyString(localDataCenterName)) {
            log.error("localDataCenter Name in configuration.yaml is missing.");
            return false;
        }

        Cluster cluster = null;
        Session session = null;
        try {
            log.info("creating cluster for Cassandra for monitoring.");
            cluster = sdcSchemaUtils.createCluster();
            if (cluster == null) {
                log.error("Failure create cassandra cluster.");
                return false;
            }
            session = cluster.connect();
            Metadata metadata = cluster.getMetadata();

            if (metadata == null) {
                log.error("Failure get cassandra metadata.");
                return false;
            }

            log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());

            //Count the number of data center nodes that are down
            Long downHostsNumber = metadata.getAllHosts().stream()
                    .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();

            log.info("The cassandra down nodes number is {}", downHostsNumber);
            return HC_FormulaNumber >= downHostsNumber;

        } catch (Exception e) {
            log.error("create cassandra cluster failed with exception.", e);
            return false;
        } finally {
            if (session != null) {
                session.close();
            }
            if (cluster != null) {
                cluster.close();
            }
        }
    }
}