aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java
blob: 87c0055b441c62b78db4568ed4f32eb914635a2f (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
/*
 * Copyright © 2016-2017 European Support Limited
 *
 * 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.
 */

package org.openecomp.core.nosqldb.impl.cassandra;

import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.LoadBalancingPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.QueryOptions;
import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
import com.datastax.driver.core.SSLOptions;
import com.datastax.driver.core.Session;


import org.openecomp.core.nosqldb.util.CassandraUtils;
import org.openecomp.sdc.common.errors.SdcConfigurationException;
import org.openecomp.sdc.common.session.SessionContextProviderFactory;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Objects;
import java.util.Optional;

public class CassandraSessionFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraSessionFactory.class);

    private CassandraSessionFactory() {
        // static methods, cannot be instantiated
    }

    public static Session getSession() {
        return ReferenceHolder.CASSANDRA;
    }

    /**
     * New cassandra session session.
     *
     * @return the session
     */
    public static Session newCassandraSession() {
        Cluster.Builder builder = Cluster.builder();
        String[] addresses = CassandraUtils.getAddresses();
        for (String address : addresses) {
            builder.addContactPoint(address);
        }

        //Check if ssl
        Boolean isSsl = CassandraUtils.isSsl();
        if (isSsl) {
            builder.withSSL(getSslOptions());
        }
        int port = CassandraUtils.getCassandraPort();
        if (port > 0) {
            builder.withPort(port);
        }
        //Check if user/pass
        Boolean isAuthenticate = CassandraUtils.isAuthenticate();
        if (isAuthenticate) {
            builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
        }

        setConsistencyLevel(builder, addresses);

        setLocalDataCenter(builder);


        Cluster cluster = builder.build();
        String keyStore = SessionContextProviderFactory.getInstance().createInterface().get()
            .getTenant();
        return cluster.connect(keyStore);
    }

    private static void setLocalDataCenter(Cluster.Builder builder) {
        String localDataCenter = CassandraUtils.getLocalDataCenter();
        if (Objects.nonNull(localDataCenter)) {
            LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as " +
                    "local.", localDataCenter);

            LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
                    DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
            builder.withLoadBalancingPolicy(tokenAwarePolicy);
        } else {
            LOGGER.info(
                    "localDatacenter was provided,  the driver will use the datacenter of the first contact " +
                            "point that was reached at initialization");
        }
    }

    private static void setConsistencyLevel(Cluster.Builder builder, String[] addresses) {
        if (addresses != null && addresses.length > 1) {
            String consistencyLevel = CassandraUtils.getConsistencyLevel();
            if (Objects.nonNull(consistencyLevel)) {
                LOGGER.info(
                        "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" +
                                " as "
                        , consistencyLevel);
                builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf
                        (consistencyLevel)));
            }
        }
    }

    private static SSLOptions getSslOptions() {

        Optional<String> trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore());
        if (!trustStorePath.isPresent()) {
            throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath");
        }

        Optional<String> trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword());
        if (!trustStorePassword.isPresent()) {
            throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword");
        }

        SSLContext context = getSslContext(trustStorePath.get(), trustStorePassword.get());
        String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"};
        return RemoteEndpointAwareJdkSSLOptions.builder().withSSLContext(context).withCipherSuites(css).build();
    }

    private static SSLContext getSslContext(String truststorePath, String trustStorePassword) {

        try (FileInputStream tsf = new FileInputStream(truststorePath)) {

            SSLContext ctx = SSLContext.getInstance("SSL");

            KeyStore ts = KeyStore.getInstance("JKS");
            ts.load(tsf, trustStorePassword.toCharArray());
            TrustManagerFactory tmf =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(ts);

            ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
            return ctx;

        } catch (Exception exception) {
            throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception);
        }
    }

    private static class ReferenceHolder {
        private static final Session CASSANDRA = newCassandraSession();

        private ReferenceHolder() {
            // prevent instantiation
        }
    }


}