2 * Copyright © 2016-2017 European Support Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.openecomp.core.nosqldb.impl.cassandra;
19 import com.datastax.driver.core.Cluster;
20 import com.datastax.driver.core.ConsistencyLevel;
21 import com.datastax.driver.core.QueryOptions;
22 import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
23 import com.datastax.driver.core.SSLOptions;
24 import com.datastax.driver.core.Session;
27 import com.datastax.driver.core.policies.*;
28 import org.openecomp.core.nosqldb.util.CassandraUtils;
29 import org.openecomp.sdc.common.errors.SdcConfigurationException;
30 import org.openecomp.sdc.common.session.SessionContextProviderFactory;
31 import org.openecomp.sdc.logging.api.Logger;
32 import org.openecomp.sdc.logging.api.LoggerFactory;
34 import javax.net.ssl.SSLContext;
35 import javax.net.ssl.TrustManagerFactory;
36 import java.io.FileInputStream;
37 import java.security.KeyStore;
38 import java.security.SecureRandom;
39 import java.util.Objects;
40 import java.util.Optional;
42 public class CassandraSessionFactory {
44 private static final Logger LOGGER = LoggerFactory.getLogger(CassandraSessionFactory.class);
46 private CassandraSessionFactory() {
47 // static methods, cannot be instantiated
50 public static Session getSession() {
51 return ReferenceHolder.CASSANDRA;
55 * New cassandra session session.
59 public static Session newCassandraSession() {
60 String[] addresses = CassandraUtils.getAddresses();
61 int cassandraPort = CassandraUtils.getCassandraPort();
62 Long reconnectTimeout = CassandraUtils.getReconnectTimeout();
64 Cluster.Builder builder = Cluster.builder();
66 if(null != reconnectTimeout) {
67 builder.withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
68 .withRetryPolicy(DefaultRetryPolicy.INSTANCE);
71 builder.withPort(cassandraPort);
73 for (String address : addresses) {
74 builder.addContactPoint(address);
78 Boolean isSsl = CassandraUtils.isSsl();
80 builder.withSSL(getSslOptions());
84 Boolean isAuthenticate = CassandraUtils.isAuthenticate();
86 builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
89 setConsistencyLevel(builder, addresses);
91 setLocalDataCenter(builder);
93 Cluster cluster = builder.build();
94 String keyStore = SessionContextProviderFactory.getInstance().createInterface().get()
96 LOGGER.info("Cassandra client created hosts: {} port: {} SSL enabled: {} reconnectTimeout",
97 addresses, cassandraPort, isSsl, reconnectTimeout);
98 return cluster.connect(keyStore);
101 private static void setLocalDataCenter(Cluster.Builder builder) {
102 String localDataCenter = CassandraUtils.getLocalDataCenter();
103 if (Objects.nonNull(localDataCenter)) {
104 LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as local.",
107 LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
108 DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
109 builder.withLoadBalancingPolicy(tokenAwarePolicy);
112 "localDatacenter was provided, the driver will use the datacenter of the first contact " +
113 "point that was reached at initialization");
117 private static void setConsistencyLevel(Cluster.Builder builder, String[] addresses) {
118 if (addresses != null && addresses.length > 1) {
119 String consistencyLevel = CassandraUtils.getConsistencyLevel();
120 if (Objects.nonNull(consistencyLevel)) {
122 "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" +
125 builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf
126 (consistencyLevel)));
131 private static SSLOptions getSslOptions() {
133 Optional<String> trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore());
134 if (!trustStorePath.isPresent()) {
135 throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath");
138 Optional<String> trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword());
139 if (!trustStorePassword.isPresent()) {
140 throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword");
143 SSLContext context = getSslContext(trustStorePath.get(), trustStorePassword.get());
144 String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"};
145 return RemoteEndpointAwareJdkSSLOptions.builder().withSSLContext(context).withCipherSuites(css).build();
148 private static SSLContext getSslContext(String truststorePath, String trustStorePassword) {
150 try (FileInputStream tsf = new FileInputStream(truststorePath)) {
152 SSLContext ctx = SSLContext.getInstance("SSL");
154 KeyStore ts = KeyStore.getInstance("JKS");
155 ts.load(tsf, trustStorePassword.toCharArray());
156 TrustManagerFactory tmf =
157 TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
160 ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
163 } catch (Exception exception) {
164 throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception);
168 private static class ReferenceHolder {
169 private static final Session CASSANDRA = newCassandraSession();
171 private ReferenceHolder() {
172 // prevent instantiation